18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-01 03:37:09 +01:00

refactor(physics): physics/mover.cpp split into the files of its subsystems

The 15 900 lines of mover.cpp go into physics/mover/, a file for each part of
the vehicle, from 220 to 1850 lines:

  mover.cpp           the vehicle as a body: construction, forces, movement
  couplers.cpp        attaching, detaching, coupler forces, automatic coupling
  collisions.cpp      collisions of the ends, crush, derailment, repair
  pneumatics.cpp      brake controls, pipes, valves, compressor, spring brake
  electrics.cpp       batteries, main switch, pantographs, converter, heating,
                      lights, genset
  traction.cpp        traction motors and forces of each drive, relays, fuses,
                      dynamic brake
  controllers.cpp     master and secondary controllers, automatic relay,
                      camshaft, integrated controller, speed control
  diesel.cpp          diesel engine, gearbox, clutch, hydraulic transmission
  cab.cpp             cab activation, direction, horns
  doors.cpp           doors and the load exchange
  securitysystem.cpp  vigilance, cab signalling, radio-stop
  commands.cpp        commands passed between the vehicles
  fizparser.cpp       reading the .fiz: the parser and its tables
  fizsections.cpp     reading the .fiz: the sections and their keywords
  setup.cpp           checks, brake valves, handles and pipes after loading

Every definition moved as it was, byte for byte, in its original order. The
helpers of the anonymous namespaces went with the file using them; the seven
used by several files (CouplerTune, square, DirPatch, DirF,
TableInterpolation, compression_at, issection) are declared or defined in
physics/mover/internal.h, which only these files include.

`git blame -C -C` follows the lines into the new files.

1142/1142 tests, golden traces exact against staging 62f7a29b.
This commit is contained in:
2026-11-27 17:47:24 +01:00
parent 5a537e69f2
commit 653aec7fbe
18 changed files with 16400 additions and 15914 deletions
+16 -1
View File
@@ -57,6 +57,7 @@ set(CMAKE_CXX_STANDARD 20)
file(GLOB HEADERS "*.h"
"Console/*.h"
"physics/*.h"
"physics/mover/*.h"
"gl/*.h"
"network/*.h"
"vr/*.h"
@@ -742,7 +743,21 @@ set(CORE_SOURCES
"audio/startsample.cpp"
"physics/friction.cpp"
"physics/brakes.cpp"
"physics/mover.cpp"
"physics/mover/mover.cpp"
"physics/mover/cab.cpp"
"physics/mover/collisions.cpp"
"physics/mover/commands.cpp"
"physics/mover/controllers.cpp"
"physics/mover/couplers.cpp"
"physics/mover/diesel.cpp"
"physics/mover/doors.cpp"
"physics/mover/electrics.cpp"
"physics/mover/fizparser.cpp"
"physics/mover/fizsections.cpp"
"physics/mover/pneumatics.cpp"
"physics/mover/securitysystem.cpp"
"physics/mover/setup.cpp"
"physics/mover/traction.cpp"
"physics/couplerphysics.cpp"
"physics/derailment.cpp"
"physics/collision.cpp"
-15913
View File
File diff suppressed because it is too large Load Diff
+250
View File
@@ -0,0 +1,250 @@
/*
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 cab: activation, the direction, the horns, the pullee mode
#include "stdafx.h"
#include "physics/mover.h"
#include "vehicle/DynObj.h"
#include "physics/oerlikonest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/Timer.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
#include "vehicle/fieldshunting.h"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <functional>
#include <limits>
#include <utility>
#include <vector>
#include "physics/mover/internal.h"
bool TMoverParameters::DirectionForward()
{
if (false == EIMDirectionChangeAllow())
{
return false;
}
if (MainCtrlPosNo > 0 && DirActive < 1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0))
{
++DirActive;
DirAbsolute = DirActive * CabActive;
SendCtrlToNext("Direction", DirActive, CabActive);
return true;
}
else if (DirActive == 1 && IsMainCtrlNoPowerPos() && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor)
return MinCurrentSwitch(true); //"wysoki rozruch" EN57
return false;
};
bool TMoverParameters::ChangeCab(int direction)
{ // zmiana kabiny i resetowanie ustawien
if (std::abs(CabOccupied + direction) < 2)
{
CabOccupied = CabOccupied + direction;
if (BrakeCtrlPosNo > 0 && (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic))
{
BrakeLevelSet(Handle->GetPos(bh_NP));
LimPipePress = PipePress;
ActFlowSpeed = 0;
}
else
BrakeLevelSet(Handle->GetPos(bh_NP));
MainCtrlPos = MainCtrlNoPowerPos();
ScndCtrlPos = 0;
return true;
}
return false;
};
int TMoverParameters::SoundingHorns(int const Signal) const
{
auto const supplied{[this](horn_supply const Supply) {
if (Supply == horn_supply::electric)
{
return Power24vIsAvailable || Power110vIsAvailable;
}
if (VeselVolume > 0.0)
{
return Compressor >= HornMinPressure;
}
// a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either
// (a road vehicle, say) has no air to check
auto const mainpipe{((Couplers[end::front].AllowedFlag | Couplers[end::rear].AllowedFlag) & coupling::mainhose) != 0};
return false == mainpipe || ScndPipePress >= HornMinPressure;
}};
auto horns{0};
if (supplied(HornSupply))
{
horns |= Signal & (1 | 2);
}
if (supplied(Horn3Supply))
{
horns |= Signal & 4;
}
return horns;
}
// *************************************************************************************************
// Q: 20160710
// załączenie rozrządu
// *************************************************************************************************
bool TMoverParameters::CabActivisation(bool const Enforce)
{
bool OK = false;
OK = Enforce || CabActive == 0; // numer kabiny, z której jest sterowanie
if (PulleeMode)
{
// nobody drives from a vehicle prepared for hauling
OK = false;
}
if (OK)
{
CabActive = CabOccupied; // sterowanie jest z kabiny z obsadą
DirAbsolute = DirActive * CabActive;
CabMaster = true;
SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection
SendCtrlToNext("CabActivisation", 1, CabActive);
SendCtrlToNext("Direction", DirActive, CabActive);
if (InactiveCabFlag & activation::springbrakeoff)
{
SpringBrakeActivate(false);
}
}
return OK;
}
bool TMoverParameters::CabActivisationAuto(bool const Enforce)
{
bool OK = AutomaticCabActivation ? CabActivisation(Enforce) : false;
return OK;
}
// *************************************************************************************************
// Q: 20160710
// wyłączenie rozrządu
// *************************************************************************************************
bool TMoverParameters::CabDeactivisation(bool const Enforce)
{
bool OK = false;
OK = Enforce || IsCabMaster(); // o ile obsada jest w kabinie ze sterowaniem
if (OK)
{
if (InactiveCabFlag & activation::springbrakeon)
{
SpringBrakeActivate(true);
}
if (InactiveCabFlag & activation::pantographsup)
{
InactiveCabPantsCheck = true;
}
if (InactiveCabFlag & activation::doorpermition)
{
PermitDoors(side::right, true, range_t::consist);
PermitDoors(side::left, true, range_t::consist);
}
if (InactiveCabFlag & activation::neutraldirection)
{
DirActive = 0;
SendCtrlToNext("Direction", 0, CabActive);
}
CabActive = 0;
DirAbsolute = DirActive * CabActive;
CabMaster = false;
DepartureSignal = false; // nie buczeć z nieaktywnej kabiny
SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection
SendCtrlToNext("CabActivisation", 0, CabOccupied); // CabActive==0!
}
return OK;
}
bool TMoverParameters::CabDeactivisationAuto(bool const Enforce)
{
bool OK = AutomaticCabActivation ? CabDeactivisation(Enforce) : false;
return OK;
}
// *************************************************************************************************
// pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): prepares the vehicle for being hauled dead in a
// train, or puts it back in service. while in the mode the vehicle:
// - vents the brake pipe for nothing of its own (inactive cab, vigilance, radio-stop, spring brake), only when
// the train parts (UpdatePipePressure()),
// - gets no force from its spring brake, whatever air its cylinder has (BrakeForce()),
// - has its driver's valve cut out and its local brake released, whatever the handles show; the distributor
// stays on the brake pipe, so it brakes and releases with the train,
// - keeps its battery off and takes no cab (BatterySwitch(), CabActivisation() and their commands).
// entering it also lets go of the hand brake and of the spring brake switch.
// returns whether the mode changed; a vehicle driven from can't enter it
// *************************************************************************************************
bool TMoverParameters::PulleeModeSwitch(bool const State)
{
if (PulleeMode == State || (State && CabActive != 0))
{
return false;
}
PulleeMode = State;
if (PulleeMode)
{
DecManualBrakeLevel(ManualBrakePosNo);
SpringBrake.Activate = false;
SecuritySystem.set_enabled(false);
Battery = false;
}
return true;
}
// *************************************************************************************************
// Q: 20160710
// kierunek do tyłu
// *************************************************************************************************
bool TMoverParameters::DirectionBackward(void)
{
if (false == EIMDirectionChangeAllow())
{
return false;
}
if (DirActive == 1 && MainCtrlPos == 0 && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false))
{
return true;
}
if (MainCtrlPosNo > 0 && DirActive > -1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0))
{
if (EngineType == TEngineType::WheelsDriven)
--CabActive;
// else
--DirActive;
DirAbsolute = DirActive * CabActive;
SendCtrlToNext("Direction", DirActive, CabActive);
return true;
}
return false;
}
bool TMoverParameters::EIMDirectionChangeAllow(void) const
{
bool OK = false;
/*
// NOTE: disabled while eimic variables aren't immediately synced with master controller changes inside ai module
OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimic_real <= 0) && (Vel < 0.1)));
*/
OK = MainCtrlPos <= MainCtrlMaxDirChangePos;
return OK;
}
+875
View File
@@ -0,0 +1,875 @@
/*
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/.
*/
// collisions of the ends, their crush and repair, derailment and putting back on the rails
#include "stdafx.h"
#include "physics/mover.h"
#include "vehicle/DynObj.h"
#include "physics/oerlikonest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/Timer.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
#include "vehicle/fieldshunting.h"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <functional>
#include <limits>
#include <utility>
#include <vector>
#include "physics/mover/internal.h"
double ComputeCollision(double &v1, double &v2, double m1, double m2, double beta, bool vc)
{ // oblicza zmiane predkosci i przyrost pedu wskutek kolizji
assert(beta < 1.0);
if (v1 < v2 && vc == true)
return 0;
else
{
double sum = m1 + m2;
double w1 = (m2 * v2 * 2.0 + v1 * (m1 - m2)) / sum;
double w2 = (m1 * v1 * 2.0 + v2 * (m2 - m1)) / sum;
// the collision changes the velocities directly: the bounce loses energy in the velocities relative to the
// centre of mass only, the pair keeps its momentum. scaling the velocities themselves braked the vehicles
// down with every step their couplers spent stretched or pressed in all the way (eu07/maszyna#553)
auto const centre{(m1 * v1 + m2 * v2) / sum};
auto const restitution{std::sqrt(1.0 - beta)};
v1 = std::lerp(centre, w1, restitution);
v2 = std::lerp(centre, w2, restitution);
return m1 * (w2 - w1) * (1 - beta);
}
}
namespace
{
// a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency
void tear_brake_hoses(TMoverParameters &Vehicle)
{
if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; }))
{
Vehicle.AlarmChainFlag = true;
}
}
} // namespace
// *************************************************************************************************
// Q: 20160716
// Wykrywanie kolizji
// *************************************************************************************************
void TMoverParameters::CollisionDetect(int const End, double const dt)
{
if (Neighbours[End].vehicle == nullptr)
{
return;
} // shouldn't normally happen but, eh
auto const &thiscoupler{Couplers[End]};
auto *othervehicle{Neighbours[End].vehicle->MoverParameters};
auto const otherend{Neighbours[End].vehicle_end};
auto const &othercoupler{othervehicle->Couplers[otherend]};
auto const physical{coupler_physics_at(End)};
// physics.collisions new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays
// the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule
auto const rails{TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)};
auto const crushing{Global.collisions == global_settings::collision_model::physical && rails};
if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt)))
{
return;
}
// physics.collisions monitor: the legacy collision follows, the log tells what the crush would be
if (Global.collisions == global_settings::collision_model::monitor && rails)
{
crush_hit(End, dt);
}
if (physical && false == coupler_stop_hit(End, *othervehicle, otherend))
{
return;
}
// the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give
// for good, rather than spring back as the legacy model has it
auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0};
// 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)};
auto velocity{V};
auto othervehiclevelocity{othervehicle->V * otherdirection};
// calculate collision force and new velocities for involved vehicles
auto const VirtualCoupling{(thiscoupler.CouplingFlag == coupling::faux)};
auto CCF{0.0};
switch (End)
{
case 0:
{
CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt;
break; // yB: ej ej ej, a po
}
case 1:
{
CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt;
break;
}
default:
{
break;
}
}
// the new model crushes the ends and derails the vehicles by the crush, see crush_hit()
if (Global.crash_damage && false == crushing)
{
// the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit())
if (false == physical && -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);
}
// HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist
auto const outsideconsist{thiscoupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)};
auto const velocitydifference{outsideconsist ? CollisionVelocity(End, *othervehicle, otherend) : 0.0};
if (velocitydifference > SafeCollisionVelocity)
{
// HACK: crude estimation for potential derail, will take place with velocity difference > 15 km/h adjusted for vehicle mass ratio
if (false == TestFlag(DamageFlag, dtrain_out) || false == TestFlag(othervehicle->DamageFlag, dtrain_out))
{
WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h");
}
if (velocitydifference > SafeCollisionVelocity * (TotalMass / othervehicle->TotalMass))
{
Derail(COLLISION);
}
if (velocitydifference > SafeCollisionVelocity * (othervehicle->TotalMass / TotalMass))
{
othervehicle->Derail(COLLISION);
}
}
}
// 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{physical ? 0.0 : 1.0};
// derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with
// the crush, the vehicles coupled to the wall push it on (crush_hit())
auto const coupled{thiscoupler.CouplingFlag != coupling::faux};
auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) {
return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled));
};
if (false == wall(*this))
{
auto const accelerationchange{(velocity - V) / dt};
AccS += accelerationchange * accelerationspike;
V = velocity;
}
if (false == wall(*othervehicle))
{
auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis
auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt};
othervehicle->AccS += othervehicleaccelerationchange * accelerationspike;
othervehicle->V = othervehiclenewvelocity;
}
}
void TMoverParameters::damage_coupler(int const End)
{
auto &thiscoupler{Couplers[End]};
if (thiscoupler.type() == TCouplerType::Articulated)
{
return;
} // HACK: don't break articulated couplings no matter what
if (SetFlag(DamageFlag, dtrain_coupling))
EventFlag = true;
auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose};
if (hosetorn)
{
// hamowanie nagle - zerwanie przewodow hamulcowych
AlarmChainFlag = true;
}
thiscoupler.CouplingFlag = 0;
thiscoupler.broken = true;
if (thiscoupler.Connected != nullptr)
{
// 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
auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]};
othercoupler.CouplingFlag = coupling::faux;
// the coupling broke between the two, either end can be repaired
othercoupler.broken = true;
if (hosetorn && coupler_physics_at(End))
{
// the brake pipe of the other part of the train vents through the torn hose as well
thiscoupler.Connected->AlarmChainFlag = true;
}
}
WriteLog("Bad driving: " + Name + " broke a coupler");
}
// *************************************************************************************************
// physics.collisions new: the collisions past the buffers, see collision.h
// *************************************************************************************************
collision::vehicle_kind TMoverParameters::collision_kind() const
{
auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb};
auto const unit{is_multiple_unit()};
auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })};
// a coach heats its compartments; the crash zone is a matter of each end (crush_of())
return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false);
}
collision::crush_curve TMoverParameters::crush_curve_at(int const End) const
{
return collision::crush_of(Couplers[End].collision, collision_kind());
}
double TMoverParameters::buffer_height_at(int const End) const
{
auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0};
return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare);
}
void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why)
{
if (false == SetFlag(DamageFlag, dtrain_out))
{
return;
}
// upright, it slides on the sleepers and keeps passing the forces on
Derailed = derailment::outcome::off_rails;
DerailCause = derail_motion::cause::collision;
DerailAcceleration = 0.0;
DerailSide = 0;
CollisionDerail = Reason;
EventFlag = true;
MainSwitch(false, range_t::local);
if (Vel < 5.0)
{
// HACK: prevent permanent axle spin in static vehicle after a collision
nrot = 0.0;
SlippingWheels = false;
}
// the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency
tear_brake_hoses(*this);
derailment_monitor.reset();
pushed_off_monitor.reset();
ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why));
}
namespace
{
char const *end_name(int const End)
{
return End == end::front ? "front" : "rear";
}
char const *kind_name(collision::vehicle_kind const Kind)
{
switch (Kind)
{
case collision::vehicle_kind::locomotive:
return "locomotive";
case collision::vehicle_kind::coach:
return "coach";
case collision::vehicle_kind::crash_zone:
return "crash zone";
case collision::vehicle_kind::wagon:
default:
return "wagon";
}
}
} // namespace
// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls
double compression_at(TCoupling const &Coupler, int const End)
{
return std::max(0.0, (End == end::front ? -1.0 : 1.0) * Coupler.CForce);
}
namespace
{
// the steel parts of both ends in series [N/m]
double steel_stiffness(TCoupling const &First, TCoupling const &Second)
{
auto const first{std::max(First.physics.link_stiffness, 1.0)};
auto const second{std::max(Second.physics.link_stiffness, 1.0)};
return first * second / (first + second);
}
// the hit of the pair in the step, for the push off the track: the peak force and how long it acted
void record_hit(TCoupling &Coupler, double const Force, double const Duration)
{
Coupler.hit_force = std::max(Coupler.hit_force, Force);
Coupler.hit_duration = std::max(Coupler.hit_duration, Duration);
}
} // namespace
bool TMoverParameters::crush_hit(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 const physical{coupler_physics_at(End)};
// the buffers pressed all the way, not the draw gear pulled all the way, and the pair still closing in
auto const buffers{physical ? thiscoupler.physics_state.stop < 0 : thiscoupler.Dist < 0.0};
auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)};
if (false == Global.crash_damage || false == buffers || closing <= 0.0)
{
// the hit is over, the next one is another one for the monitor
thiscoupler.crush_monitored = false;
othercoupler.crush_monitored = false;
return false;
}
auto const monitor{Global.collisions == global_settings::collision_model::monitor};
// put down by the scenery inside each other: pressed past the stop of the buffers and the crush of the ends by more
// than a hit takes them in a step. the legacy collision pushes them apart; their springs, the stops at both ends
// and the neighbours found at either end there make up any closing velocity, not a hit
auto const stop{std::max(thiscoupler.DmaxB + othercoupler.DmaxB, thiscoupler.physics.buffers.travel + othercoupler.physics.buffers.travel) + thiscoupler.crush + othercoupler.crush};
auto const overlap{-static_cast<double>(Neighbours[End].distance)};
if (overlap > stop + collision::inside_margin + closing * dt)
{
// nor is what their springs took in pressed past the stop and back a hit, for as long as the buffers touch
thiscoupler.contact.inside();
othercoupler.contact.inside();
if (false == thiscoupler.inside_reported)
{
thiscoupler.inside_reported = true;
othercoupler.inside_reported = true;
WriteLog(std::format("Bad scenery: {} and {} are inside each other, their buffers pressed {:.2f} m past their stop, no crush", Name, othervehicle->Name, overlap - stop));
}
return false;
}
// parting at the start of the step: what closes the pair in now is the knock of a hit of either vehicle in the step,
// or of the vehicles inside each other next to it, not a hit of this pair. the legacy collision takes it; a pair
// still closing in at the start of the next step is a hit
if (thiscoupler.closing < 0.0)
{
return false;
}
// a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it from outside its
// train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it
// stopped the whole train at once, and the vehicles behind it crushed by the energy of the train
auto const coupled{thiscoupler.CouplingFlag != coupling::faux};
auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none};
auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none};
if (wall && otherwall)
{
return false;
}
constexpr double immovable{1e12};
auto const mass{wall ? immovable : TotalMass};
auto const othermass{otherwall ? immovable : othervehicle->TotalMass};
auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0};
auto const firstcurve{crush_curve_at(End)};
auto const secondcurve{othervehicle->crush_curve_at(otherend)};
auto const stiffness{steel_stiffness(thiscoupler, othercoupler)};
auto const springs{compression_at(thiscoupler, End)};
collision::hit_input input;
input.velocity = closing;
input.mass1 = mass;
input.mass2 = othermass;
input.restitution = std::sqrt(std::max(0.0, 1.0 - loss));
input.stiffness = stiffness;
input.springs = springs;
// the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts
input.dt = monitor ? 1.0 : dt;
input.start_velocity = thiscoupler.closing;
// the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in. an automatic
// coupler (or its adapter) has no buffers at the side: its draft gear takes in what its springs of the .fiz do
auto const reduced{mass * othermass / (mass + othermass)};
auto const central{thiscoupler.type() == TCouplerType::Automatic || othercoupler.type() == TCouplerType::Automatic || thiscoupler.has_adapter() || othercoupler.has_adapter()};
auto const capacity{central ? 0.0 : collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())};
auto const hitvelocity{std::max(closing, thiscoupler.closing)};
input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity);
auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)};
// the override, by the crush of both ends
auto const climbing_of = [&](double const Crush1, double const Crush2) {
collision::override_input climbing;
climbing.crush1 = Crush1;
climbing.crush2 = Crush2;
climbing.mass1 = TotalMass - Mred;
climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred;
climbing.height1 = buffer_height_at(End);
climbing.height2 = othervehicle->buffer_height_at(otherend);
climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind());
climbing.zone1 = firstcurve.densify;
climbing.zone2 = secondcurve.densify;
return climbing;
};
if (monitor)
{
if (hit.crushing && false == thiscoupler.crush_monitored)
{
thiscoupler.crush_monitored = true;
othercoupler.crush_monitored = true;
++crush_reports;
auto const crush1{thiscoupler.crush + hit.crush1};
auto const crush2{othercoupler.crush + hit.crush2};
auto const climbed{collision::override_of(climbing_of(crush1, crush2))};
auto const torn{std::max(crush1, crush2) >= collision::draw_gear_crush};
std::string const outcome{climbed.first && climbed.second ? std::string{"both would leave the rails"}
: climbed.first ? Name + " would ride up onto " + othervehicle->Name
: climbed.second ? othervehicle->Name + " would ride up onto " + Name
: std::string{"both would stay on the rails"}};
WriteLog(std::format("collision monitor: {} and {} collided at {:.0f} km/h: the {} end of {} ({:.1f} t {}) would crush by {:.2f} m, the {} end of {} ({:.1f} t {}) by {:.2f} m, "
"at {:.0f} kN; draw gear {}; {}",
Name, othervehicle->Name, closing * 3.6, end_name(End), Name, TotalMass / 1000.0, kind_name(collision_kind()), crush1, end_name(otherend), othervehicle->Name,
othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), crush2, hit.force / 1000.0, torn ? "torn off" : "holds", outcome));
}
return false;
}
if (false == hit.crushing)
{
// the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push
// off the track
auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))};
auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)};
auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))};
record_hit(thiscoupler, peak, duration);
record_hit(othercoupler, peak, duration);
return false;
}
// the other vehicle doesn't take it again in this step
thiscoupler.hit_handled = true;
othercoupler.hit_handled = true;
// the hit at the force the weaker end gives at pushes the vehicles apart: the velocities alone change, along this
// vehicle's axis as in CollisionDetect()
auto const otherdirection{DirPatch(End, otherend)};
auto const apart{End == end::front ? -1.0 : 1.0};
if (false == wall)
{
V += apart * hit.impulse / mass;
}
if (false == otherwall)
{
othervehicle->V -= apart * hit.impulse / othermass * otherdirection;
}
record_hit(thiscoupler, hit.force, hit.duration);
record_hit(othercoupler, hit.force, hit.duration);
// the energy the crush took, for both vehicles' count of the contact
thiscoupler.contact.crushed(hit.work);
othercoupler.contact.crushed(hit.work);
// what the log tells of the pair, for the analysis of a crush
auto const kinetic{0.5 * reduced * hitvelocity * hitvelocity};
auto const pair = [&]() {
return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, "
"closing at {:.1f} km/h at the start of the step; energy {:.0f} kJ of the motion and {:.0f} kJ in the buffers, past the {:.0f} kJ they take in, "
"{:.0f} kJ crushed in the contact",
Name, TotalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name,
othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush,
secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0,
thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0);
};
auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) {
if (Before < collision::crush_mark && After >= collision::crush_mark)
{
ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name, pair()));
}
};
auto const before{thiscoupler.crush};
auto const otherbefore{othercoupler.crush};
thiscoupler.crush += hit.crush1;
othercoupler.crush += hit.crush2;
crushed(*this, End, before, thiscoupler.crush);
crushed(*othervehicle, otherend, otherbefore, othercoupler.crush);
// the crushed headstock tears off the draw gear, with the brake hose: both parts of the train brake in emergency.
// the coupler of an end not coupled is gone as well, it doesn't couple any more
if (thiscoupler.CouplingFlag != coupling::faux && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush)
{
auto const hose{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose};
damage_coupler(End);
if (hose)
{
othervehicle->AlarmChainFlag = true;
}
}
else if (thiscoupler.CouplingFlag == coupling::faux)
{
if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken)
{
damage_coupler(End);
}
if (othercoupler.crush >= collision::draw_gear_crush && false == othercoupler.broken)
{
othervehicle->damage_coupler(otherend);
}
}
// the end crushed deep enough lets one vehicle climb onto the other one
auto const climbing{climbing_of(thiscoupler.crush, othercoupler.crush)};
auto const climbed{collision::override_of(climbing)};
auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) {
return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6,
thiscoupler.crush + othercoupler.crush, climbing.height1 * 1000.0, climbing.height2 * 1000.0, climbing.anticlimbers ? "yes" : "no", pair());
};
if (climbed.first)
{
derail_in_collision(COLLISION_OVERRIDE, why(*this, *othervehicle));
}
if (climbed.second)
{
othervehicle->derail_in_collision(COLLISION_OVERRIDE, why(*othervehicle, *this));
}
return true;
}
void TMoverParameters::check_pushed_off(double const dt, double const Distance)
{
if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) ||
DebugModeFlag)
{
pushed_off_monitor.reset();
return;
}
collision::pushed_vehicle vehicle;
vehicle.mass = TotalMass - Mred;
vehicle.axles = NAxles > 0 ? NAxles : 4;
vehicle.length = Dim.L;
vehicle.pivots = BDist;
vehicle.axle_base = ADist > 0.0 ? ADist : BDist;
auto climbs{false};
auto distance{0.0};
auto lifted{false};
auto duration{0.0};
auto worst{0.0};
auto worstforce{0.0};
auto worstend{static_cast<int>(end::front)};
for (int end = end::front; end <= end::rear; ++end)
{
auto const *other{Neighbours[end].vehicle};
if (other == nullptr)
{
continue;
}
auto const &coupler{Couplers[end]};
collision::pushed_end pushed;
pushed.other_length = other->MoverParameters->Dim.L;
pushed.crush = coupler.crush;
// the steady push of the springs over the step, or the peak of a hit for as long as it lasted: the flange climbs
// over the distance the wheels rolled meanwhile, a wheel lifted off the rail goes in a short time, rolling or not
for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}})
{
pushed.force = force;
auto const wheel{collision::pushed_forces(vehicle, pushed, RunningShape.R)};
auto const ratio{wheel.ratio()};
if (ratio < derailment::climbing_limit)
{
continue;
}
climbs = true;
distance = std::max(distance, Distance * std::clamp(time / std::max(dt, 1e-9), 0.0, 1.0));
if (wheel.lifted())
{
lifted = true;
duration = std::max(duration, time);
}
if (ratio > worst)
{
worst = ratio;
worstforce = force;
worstend = end;
}
}
}
if (pushed_off_monitor.update(climbs, distance, lifted, duration))
{
derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, {}, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, "
"springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)",
worstforce / 1000.0, end_name(worstend),
lifted ? std::format("its wheels lifted off the rail for {:.3f} s", pushed_off_monitor.time())
: std::format("the flange climbing over {:.2f} m", pushed_off_monitor.distance()),
Vel, std::abs(RunningShape.R), std::min(worst, 99.0),
vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0,
compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0,
Couplers[end::front].crush, Couplers[end::rear].crush));
}
}
namespace
{
// the end as it was built (physics.collisions new): not crushed, and nothing of a contact or a hit kept
void restore_end(TCoupling &Coupler)
{
Coupler.crush = 0.0;
Coupler.contact.reset();
Coupler.hit_handled = false;
Coupler.hit_force = 0.0;
Coupler.hit_duration = 0.0;
Coupler.crush_monitored = false;
Coupler.inside_reported = false;
}
// the coupler as good as new, its end with it (the crush that tore the draw gear off), the vehicle without the coupler
// damage (and the emergency braking of the torn brake hose) once neither of its couplers is broken
void repair(TMoverParameters &Vehicle, TCoupling &Coupler)
{
Coupler.broken = false;
Coupler.stretch_duration = 0.f;
Coupler.physics_state.couple();
restore_end(Coupler);
if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken)
{
return;
}
ClearFlag(Vehicle.DamageFlag, dtrain_coupling);
// either vehicle of the pair may have been braking through the torn hose
Vehicle.AlarmChainFlag = false;
}
} // namespace
bool TMoverParameters::repair_coupler(int const End)
{
auto &thiscoupler{Couplers[End]};
if (false == thiscoupler.broken)
{
return false;
}
repair(*this, thiscoupler);
// the other half of the coupling, which may be the vehicle flagged with the damage
if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken)
{
repair(*other, other->Couplers[thiscoupler.ConnectedNr]);
}
WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear"));
return true;
}
static_assert(derailment::track_damage::railwear == dtrack_railwear && derailment::track_damage::freerail == dtrack_freerail && derailment::track_damage::thinrail == dtrack_thinrail &&
derailment::track_damage::railbend == dtrack_railbend);
double TMoverParameters::centre_of_gravity() const
{
auto const kind{EngineType == TEngineType::None ? derailment::vehicle_class::unpowered : derailment::vehicle_class::powered};
auto const empty{CentreOfGravity > 0.0 ? CentreOfGravity : derailment::default_centre_of_gravity(Dim.H, kind)};
auto const loadmass{TotalMass - Mass - Mred};
auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 1.0};
return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H);
}
void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance)
{
if (TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag)
{
derailment_monitor.reset();
return;
}
derailment::vehicle_state vehicle;
vehicle.mass = TotalMass - Mred;
vehicle.axles = NAxles > 0 ? NAxles : 4;
vehicle.length = Dim.L;
vehicle.axle_base = ADist > 0.0 ? ADist : BDist;
vehicle.centre_of_gravity = centre_of_gravity();
for (int end = end::front; end <= end::rear; ++end)
{
auto const *other{Neighbours[end].vehicle};
if (other == nullptr)
{
continue;
}
// the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls
vehicle.ends[end].compression = (end == end::front ? -1.0 : 1.0) * Couplers[end].CForce;
vehicle.ends[end].other_length = other->MoverParameters->Dim.L;
}
derailment::track_state track;
track.radius = Shape.R;
track.cant = Shape.dHrail;
track.gauge = TrackW;
track.uneven_curvature = Shape.uneven_curvature;
track.uneven_cross = Shape.uneven_cross;
track.buckle_curvature = Shape.buckle_curvature;
track.damage = Track.DamageFlag;
auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)};
if (verdict.result == derailment::outcome::none)
{
return;
}
if (Global.derailment == global_settings::derailment_model::physical)
{
derail(verdict, vehicle, track, Track.Name);
return;
}
// physics.derailment monitor: the legacy draw decides, the log tells what the criteria would do, once on a track
if (derailment_reported.has_value() && *derailment_reported == Track.Name)
{
return;
}
derailment_reported = Track.Name;
++derailment_reports;
WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{}));
}
void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName)
{
if (false == SetFlag(DamageFlag, dtrain_out))
{
return;
}
Derailed = Verdict.result;
DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails;
// out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve
DerailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration;
DerailSide = 0;
EventFlag = true;
MainSwitch(false, range_t::local);
// the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency
tear_brake_hoses(*this);
ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{}));
if (Track.buckle_curvature != 0.0)
{
ErrorLog(std::format("Bad driving: {} derailed on buckled track, the buckle bending the line by 1/{:.0f} m {} the curve", Name, 1.0 / std::abs(Track.buckle_curvature),
Track.buckle_curvature > 0.0 ? "with" : "against"));
}
}
void TMoverParameters::rerail()
{
ClearFlag(DamageFlag, dtrain_out);
Derailed = derailment::outcome::none;
// and back on the track; what derailed it before has no say in how it leaves the track the next time
OffTrack.reset();
DerailCause = derail_motion::cause::off_rails;
DerailAcceleration = 0.0;
DerailSide = 0;
derailment_monitor.reset();
derailment_distance = 0.0;
derailment_reported.reset();
// nor derailed in a collision
CollisionDerail = NONE;
pushed_off_monitor.reset();
// back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps
// its place on the road)
if (TestFlag(CategoryFlag, 1))
{
OffsetTrackH = 0.0;
OffsetTrackV = 0.0;
}
// a derailed vehicle which stopped sleeps (Global.physics_sleepheld) with the friction of the derailment in FStand and
// where the derailment put it, until something wakes it: the physics on, for the friction of the rails and its place on
// them. it is put back by a command (resetconsist, SetDamage) or by the road spawner, which sets it going anyway
switch_physics(true, wake_cause::command);
}
void TMoverParameters::repair_damage()
{
DamageFlag = 0;
EngDmgFlag = 0;
WheelFlat = 0.0;
AlarmChainFlag = false;
// the crushed ends rebuilt
for (auto &coupler : Couplers)
{
restore_end(coupler);
}
rerail();
}
void TMoverParameters::Derail(DerailReason const Reason)
{
if (SetFlag(DamageFlag, dtrain_out))
{
EventFlag = true;
MainSwitch(false, range_t::local);
auto const velocity{V};
AccS *= 0.65;
V *= 0.65;
// physics.collisions new: the vehicles coupled to it lose the speed with it. the cut in a step stands for the
// train coming to a stop with the vehicle; the coupled ones keeping their speed would run into it at a third of
// the speed of the train, and crush their ends and ride up onto it for a hit no train had
if (Global.collisions == global_settings::collision_model::physical && TestFlag(CategoryFlag, 1))
{
change_train_velocity(V - velocity);
}
RunningShape.R = 0;
if (Vel < 5.0)
{
// HACK: prevent permanent axle spin in static vehicle after a collision
nrot = 0.0;
SlippingWheels = false;
}
// physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the
// ground as the vehicles the criteria derail do, and its brake hoses tear
if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1))
{
Derailed = derailment::outcome::off_rails;
DerailCause = derail_motion::cause::end_of_track;
DerailAcceleration = 0.0;
DerailSide = 0;
tear_brake_hoses(*this);
}
// Print a message in the log.
if (Reason == END_OF_TRACK)
ErrorLog("Bad driving: " + Name + " derailed due to end of track");
else if (Reason == TOO_HIGH_SPEED)
ErrorLog("Bad driving: " + Name + " derailed due to too high speed");
else if (Reason == GAUGE_MISMATCH)
ErrorLog("Bad dynamic: " + Name + " derailed due to track width"); // błąd w scenerii
else if (Reason == WRONG_TRACK_TYPE)
ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii
else if (Reason == COLLISION)
WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `TMoverParameters::CollisionDetect()`
else if (Reason == TRAILED_SWITCH)
ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way");
}
}
bool TMoverParameters::leaves_track() const
{
return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none &&
false == OffTrack.active();
}
void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why)
{
if (Global.derailment != global_settings::derailment_model::physical || false == SetFlag(DamageFlag, dtrain_out))
{
return;
}
// upright, its flange climbs the rail the coupling pulls it over
Derailed = derailment::outcome::off_rails;
DerailCause = derail_motion::cause::pulled_off;
DerailAcceleration = Acceleration;
DerailSide = Side;
EventFlag = true;
MainSwitch(false, range_t::local);
tear_brake_hoses(*this);
derailment_monitor.reset();
ErrorLog(std::format("Bad driving: {} pulled off the track by the vehicle coupled to it, {}", Name, Why));
}
+807
View File
@@ -0,0 +1,807 @@
/*
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 commands passed between the vehicles of a train
#include "stdafx.h"
#include "physics/mover.h"
#include "vehicle/DynObj.h"
#include "physics/oerlikonest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/Timer.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
#include "vehicle/fieldshunting.h"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <functional>
#include <limits>
#include <utility>
#include <vector>
#include "physics/mover/internal.h"
// *************************************************************************************************
// Q: 20160714
// Wstawia komendę z parametrem, od sprzęgu i w lokalizacji do pojazdu
// *************************************************************************************************
void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation)
{
CommandLast = NewCommand; // zapamiętanie komendy
CommandIn.Command = NewCommand;
CommandIn.Value1 = NewValue1;
CommandIn.Value2 = NewValue2;
CommandIn.Location = NewLocation;
// czy uruchomic tu RunInternalCommand? nie wiem
}
// *************************************************************************************************
// Q: 20160714
// Pobiera komendę z parametru funkcji oraz wartość zmiennej jako return
// *************************************************************************************************
double TMoverParameters::GetExternalCommand(std::string &Command) const
{
Command = CommandOut;
return ValueOut;
}
// *************************************************************************************************
// Q: 20160714
// Ustawienie komendy wraz z parametrami
// *************************************************************************************************
bool TMoverParameters::SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype)
{
bool SIC;
if (CommandIn.Command == NewCommand && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.Coupling == Couplertype)
SIC = false;
else
{
CommandIn.Command = NewCommand;
CommandIn.Value1 = NewValue1;
CommandIn.Value2 = NewValue2;
CommandIn.Coupling = Couplertype;
SIC = true;
LastLoadChangeTime = 0; // zerowanie czasu (roz)ładowania
}
return SIC;
}
// *************************************************************************************************
// Q: 20160714
// wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego)
// *************************************************************************************************
bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype)
{
bool OK;
int d; // numer sprzęgu w kierunku którego wysyłamy
// Ra: był problem z propagacją, jeśli w składzie jest pojazd wstawiony odwrotnie
// Ra: problem jest również, jeśli AI będzie na końcu składu
OK = true; // ( dir != 0 ); // experimentally disabled
d = (1 + static_cast<int>(Sign(dir))) / 2; // dir=-1=>d=0, dir=1=>d=1 - wysyłanie tylko w tył
// musi być wybrana niezerowa kabina
if (OK && Couplers[d].Connected != nullptr && TestFlag(Couplers[d].CouplingFlag, Couplertype))
{
if (Couplers[d].ConnectedNr != d)
{
// jeśli ten nastpęny jest zgodny z aktualnym
if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, dir, Couplertype))
OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja
}
else
{
// jeśli następny jest ustawiony przeciwnie, zmieniamy kierunek
if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, -dir, Couplertype))
OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja
}
}
return OK;
}
// *************************************************************************************************
// Q: 20160723
// *************************************************************************************************
// wysłanie komendy otrzymanej z kierunku CValue2 (względem sprzęgów: 1=przod,-1=tył)
// Ra: Jest tu problem z rekurencją. Trzeba by oddzielić wykonywanie komend od mechanizmu
// ich propagacji w składzie. Osobnym problemem może być propagacja tylko w jedną stronę.
// Jeśli jakiś człon jest wstawiony odwrotnie, to również odwrotnie musi wykonywać
// komendy związane z kierunkami (PantFront, PantRear, DoorLeft, DoorRight).
// Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może
// sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania
// jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę.
bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype)
{
// the group of the command sets OK; a command none of them knows isn't done
if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunCabCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunBrakeCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunBrakeEquipmentCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunAuxiliariesCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunPumpsCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunBlowersCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunPowerCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunDoorsCommand(Command, CValue1, CValue2, Couplertype, OK) ||
RunLoadCommand(Command, CValue1, CValue2, Couplertype, OK))
{
return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie
}
return false;
}
// RunCommand() for the controllers; returns whether the command is one of them
bool TMoverParameters::RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "MainCtrl")
{
// sent as MainCtrlPosForCoupled(), passed on unchanged
if (auto const position{MainCtrlPosFromCoupled(static_cast<int>(floor(CValue1)))}; MainCtrlPosNo >= position)
{
MainCtrlPos = position;
if (DelayCtrlFlag)
{
if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1)
LastRelayTime = 0;
}
else if (LastRelayTime > CtrlDelay)
LastRelayTime = 0;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "ScndCtrl")
{
if (ScndCtrlPosNo >= floor(CValue1))
{
ScndCtrlPos = static_cast<int>(floor(CValue1));
if (LastRelayTime > CtrlDelay)
LastRelayTime = 0;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
/* else if command='BrakeCtrl' then
begin
if BrakeCtrlPosNo>=Trunc(CValue1) then
begin
BrakeCtrlPos:=Trunc(CValue1);
OK:=SendCtrlToNext(command,CValue1,CValue2);
end;
end */
else if (Command == "EIMIC") // ElectricInductionMotor Integrated Control - propulsion and brakes in relative values
{
eimic_real = CValue1;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else
{
return false;
}
return true;
}
// RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them
bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "Direction")
{
DirActive = static_cast<int>(floor(CValue1));
DirAbsolute = DirActive * CabActive;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "AutoRelaySwitch")
{
if (CValue1 == 1 && AutoRelayType == 2)
AutoRelayFlag = true;
else
AutoRelayFlag = false;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "MaxCurrentSwitch")
{
MaxCurrentSwitch(CValue1 == 1, range_t::local);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "MinCurrentSwitch")
{
OK = MinCurrentSwitch(CValue1 == 1);
}
/*test komend oddzialywujacych na tabor*/
else
{
return false;
}
return true;
}
// RunCommand() for the cab and the speed control; returns whether the command is one of them
bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "CabActivisation")
{
// OK:=Power>0.01;
switch (static_cast<int>(CValue1 * CValue2))
{ // CValue2 ma zmieniany znak przy niezgodności sprzęgów
case 1:
{
CabActive = 1;
break;
}
case -1:
{
CabActive = -1;
break;
}
default:
{
CabActive = 0; // gdy CValue1==0
break;
}
}
if (PulleeMode)
{
// a vehicle prepared for hauling takes no cab, the command only passes through it
CabActive = 0;
}
DirAbsolute = DirActive * CabActive;
CabMaster = false;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "SpeedCntrl")
{
if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl)
SpeedCtrlValue = static_cast<int>(round(CValue1));
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "SpeedCtrlUnit.Parking")
{
SpeedCtrlUnit.Parking = static_cast<bool>(CValue1);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else
{
return false;
}
return true;
}
// RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them
bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac...
{
if (CValue1 < 0.001)
DynamicBrakeEMUStatus = true;
double temp1 = CValue1;
if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus)
temp1 = 0;
if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus)
temp1 = 0;
Hamulec->SetEPS(temp1);
TUHEX_StageActual = static_cast<int>(CValue1);
TUHEX_Active = TUHEX_StageActual > 0;
if (CValue1 < 0.001)
DynamicBrakeEMUStatus = true;
// fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!!
BrakePressureActual = BrakePressureTable[BrakeCtrlPos];
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
} // youby - odluzniacz hamulcow, przyda sie
else if (Command == "BrakeReleaser")
{
OK = BrakeReleaser(static_cast<int>(Round(CValue1))); // samo się przesyła dalej
// OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n
}
else if (Command == "Emergency_brake")
{
if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne?
OK = true;
else
OK = false;
}
else
{
return false;
}
return true;
}
// RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them
bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "BrakeDelay")
{
if (auto const brakesetting = static_cast<int>(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting))
{
BrakeDelayFlag = brakesetting;
OK = true;
}
else
{
OK = false;
}
SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "SpringBrakeActivate")
{
if (Power24vIsAvailable || Power110vIsAvailable)
{
SpringBrake.Activate = CValue1 > 0;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else
OK = true;
}
else if (Command == "Sandbox")
{
OK = Sandbox(CValue1 == 1, range_t::local);
}
else if (Command == "CabSignal") /*SHP,Indusi*/
{ // Ra: to powinno działać tylko w członie obsadzonym
SecuritySystem.set_cabsignal();
// else OK:=false;
OK = true; // true, gdy można usunąć komendę
}
/*naladunek/rozladunek*/
// TODO: have these commands leverage load exchange system instead
// TODO: CValue1 defines amount to load/unload
else
{
return false;
}
return true;
}
// RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them
bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "HeatingSwitch")
{
HeatingSwitch_(CValue1 > 0.0);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "ConverterSwitch") /*NBMX*/
{
if (ConverterStart == start_t::manual)
{
ConverterAllow = CValue1 > 0.0;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "BatterySwitch") /*NBMX*/
{
// the battery of a vehicle prepared for hauling (PulleeMode) stays off
if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0))
{
Battery = CValue1 > 0.0;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
// else if command='EpFuseSwitch' then {NBMX}
// begin
// if (CValue1=1) then EpFuse:=true
// else if (CValue1=0) then EpFuse:=false;
// OK:=SendCtrlToNext(command,CValue1,CValue2);
// end
else if (Command == "CompressorSwitch") /*NBMX*/
{
CompressorSwitch(CValue1 == 1, range_t::local);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "CompressorPreset")
{
CompressorListPos = safe_clamp(static_cast<int>(CValue1), 0, CompressorListPosNo);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else
{
return false;
}
return true;
}
// RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them
bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "WaterPumpBreakerSwitch")
{
/*
if( FuelPump.start_type != start::automatic ) {
// automatic fuel pump ignores 'manual' state commands
*/
WaterPump.breaker = CValue1 == 1;
/*
}
*/
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "WaterPumpSwitch")
{
if (WaterPump.start_type != start_t::battery)
{
// automatic fuel pump ignores 'manual' state commands
WaterPump.is_enabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "WaterPumpSwitchOff")
{
if (WaterPump.start_type != start_t::battery)
{
// automatic fuel pump ignores 'manual' state commands
WaterPump.is_disabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "WaterHeaterBreakerSwitch")
{
/*
if( FuelPump.start_type != start::automatic ) {
// automatic fuel pump ignores 'manual' state commands
*/
WaterHeater.breaker = CValue1 == 1;
/*
}
*/
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "WaterHeaterSwitch")
{
/*
if( FuelPump.start_type != start::automatic ) {
// automatic fuel pump ignores 'manual' state commands
*/
WaterHeater.is_enabled = CValue1 == 1;
/*
}
*/
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "WaterCircuitsLinkSwitch")
{
if (true == dizel_heat.auxiliary_water_circuit)
{
// can only link circuits if the vehicle has more than one of them
WaterCircuitsLink = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "FuelPumpSwitch")
{
if (FuelPump.start_type != start_t::automatic)
{
// automatic fuel pump ignores 'manual' state commands
FuelPump.is_enabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "FuelPumpSwitchOff")
{
if (FuelPump.start_type != start_t::automatic)
{
// automatic fuel pump ignores 'manual' state commands
FuelPump.is_disabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "OilPumpSwitch")
{
if (OilPump.start_type != start_t::automatic)
{
// automatic pump ignores 'manual' state commands
OilPump.is_enabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "OilPumpSwitchOff")
{
if (OilPump.start_type != start_t::automatic)
{
// automatic pump ignores 'manual' state commands
OilPump.is_disabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else
{
return false;
}
return true;
}
// RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them
bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "MotorBlowersFrontSwitch")
{
if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback)
{
// automatic device ignores 'manual' state commands
MotorBlowers[end::front].is_enabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "MotorBlowersFrontSwitchOff")
{
if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback)
{
// automatic device ignores 'manual' state commands
MotorBlowers[end::front].is_disabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "MotorBlowersRearSwitch")
{
if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback)
{
// automatic device ignores 'manual' state commands
MotorBlowers[end::rear].is_enabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "MotorBlowersRearSwitchOff")
{
if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback)
{
// automatic device ignores 'manual' state commands
MotorBlowers[end::rear].is_disabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "CompartmentLightsSwitch")
{
if (CompartmentLights.start_type != start_t::automatic)
{
// automatic lights ignore 'manual' state commands
CompartmentLights.is_enabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "CompartmentLightsSwitchOff")
{
if (CompartmentLights.start_type != start_t::automatic)
{
// automatic lights ignore 'manual' state commands
CompartmentLights.is_disabled = CValue1 == 1;
}
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else
{
return false;
}
return true;
}
// RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them
bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "MainSwitch")
{
MainSwitch_(CValue1 > 0.0);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "RelayReset")
{
RelayReset(static_cast<int>(CValue1), range_t::local);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "PantValve") // Winger 160204
{ // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów
auto const inputend{(static_cast<int>(CValue1) & 0x80) != 0 ? 1 : 0};
auto const inputcab{(static_cast<int>(CValue1) & 0x40) != 0 ? 1 : 0};
auto const inputoperation{static_cast<int>(CValue1) & ~(0x80 | 0x40)};
auto const noswap{TrainType == train_type::emu || TrainType == train_type::et41};
auto swap{false == noswap && TestFlag(Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag, coupling::control)};
if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed)
{
swap = !swap;
} // TODO: check whether this part has RL equivalent
OperatePantographValve(static_cast<end>(swap ? 1 - inputend : inputend), static_cast<operation_t>(inputoperation), range_t::local);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "PantsValve")
{
OperatePantographsValve(static_cast<operation_t>(static_cast<int>(CValue1)), range_t::local);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "PantAllDown")
{
DropAllPantographs(CValue1 == 1, range_t::local);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "TractionMode")
{
TractionModeSwitch(CValue1 > 0.5 ? traction_mode::genset : traction_mode::catenary, range_t::local);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "GensetSwitch")
{
GensetSwitch(CValue1 > 0.5, range_t::local);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else
{
return false;
}
return true;
}
// RunCommand() for the doors and the departure signal; returns whether the command is one of them
bool TMoverParameters::RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK)
{
if (Command == "DoorPermit")
{
DoorPermitCommand(CValue1, CValue2);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "DoorOpen" || Command == "DoorClose") /*NBMX*/
{ // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów
DoorRemoteCommand(Command == "DoorOpen", CValue1, CValue2);
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "DoorLock")
{
Doors.lock_enabled = CValue1 == 1 ? true : false;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "DoorStep")
{
Doors.step_enabled = CValue1 == 1 ? true : false;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "DoorMode")
{
Doors.remote_only = CValue1 == 1 ? true : false;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else if (Command == "DepartureSignal")
{
DepartureSignal = CValue1 == 1 ? true : false;
OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype);
}
else
{
return false;
}
return true;
}
// the doors' permits, on the sides the command names: CValue1 the sides, negative to take the permit back, CValue2 the
// direction the command comes from
void TMoverParameters::DoorPermitCommand(double const CValue1, double const CValue2)
{
auto const leftside{CValue2 > 0 ? 1 : 2};
if (auto const rightside{3 - leftside}; std::abs(static_cast<int>(CValue1)) & rightside)
{
PermitDoors_(side::right, CValue1 > 0);
}
if (std::abs(static_cast<int>(CValue1)) & leftside)
{
PermitDoors_(side::left, CValue1 > 0);
}
}
// the doors opened or closed from afar on the sides the command names, unless they're only worked locally
void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2)
{
using enum control_t;
if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control};
(doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == Power24vIsAvailable && false == Power110vIsAvailable))
{
return;
}
auto const leftside{CValue2 > 0 ? 1 : 2};
if (auto const rightside{3 - leftside}; static_cast<int>(CValue1) & rightside)
{
Doors.instances[side::right].remote_open = Open;
Doors.instances[side::right].remote_close = false == Open;
}
if (static_cast<int>(CValue1) & leftside)
{
Doors.instances[side::left].remote_open = Open;
Doors.instances[side::left].remote_close = false == Open;
}
}
// RunCommand() for the load and the damage; returns whether the command is one of them
bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int const /*Couplertype*/, bool &OK)
{
if (issection("Load=", Command))
{
OK = false; // będzie powtarzane aż się załaduje
if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist
&& MaxLoad > 0 && LoadAmount < MaxLoad * (1.0 + OverLoadFactor) && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0))
{ // ten peron/rampa
auto const loadname{ToLower(extract_value("Load", Command))};
if (LoadAmount == 0.f)
{
AssignLoad(loadname);
}
OK = LoadingDone(LoadSpeed,
loadname); // zmienia LoadStatus
}
else
{
// no loading can be done if conditions aren't met
LastLoadChangeTime = 0.0;
}
}
else if (issection("UnLoad=", Command))
{
OK = false; // będzie powtarzane aż się rozładuje
if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist
&& LoadAmount > 0 // czy jest co rozladowac?
&& Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0))
{ // ten peron
/*mozna to rozladowac*/
OK = LoadingDone(-1.f * LoadSpeed, ToLower(extract_value("UnLoad", Command)));
}
else
{
// no loading can be done if conditions aren't met
LastLoadChangeTime = 0.0;
}
}
else if (Command == "SetDamage")
{
if (CValue2 == 1)
OK = SetFlag(DamageFlag, static_cast<int>(floor(CValue1)));
if (CValue2 == -1)
{
auto const derailed{TestFlag(DamageFlag, dtrain_out)};
OK = SetFlag(DamageFlag, static_cast<int>(-floor(CValue1)));
// taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held
if (derailed && false == TestFlag(DamageFlag, dtrain_out))
rerail();
}
}
else
{
return false;
}
return true;
}
// *************************************************************************************************
// Q: 20160714
// Uruchamia funkcję RunCommand aż do skutku. Jeśli będzie pozytywny to kasuje komendę.
// *************************************************************************************************
bool TMoverParameters::RunInternalCommand()
{
bool OK;
if (!CommandIn.Command.empty())
{
OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.Coupling);
if (OK)
{
CommandIn.Command.clear(); // kasowanie bo rozkaz wykonany
CommandIn.Value1 = 0;
CommandIn.Value2 = 0;
CommandIn.Coupling = 0;
CommandIn.Location.X = 0;
CommandIn.Location.Y = 0;
CommandIn.Location.Z = 0;
switch_physics(true, wake_cause::command);
}
}
else
OK = false;
return OK;
}
File diff suppressed because it is too large Load Diff
+578
View File
@@ -0,0 +1,578 @@
/*
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/.
*/
// attaching and detaching, the forces in the couplers and the automatic coupling
#include "stdafx.h"
#include "physics/mover.h"
#include "vehicle/DynObj.h"
#include "physics/oerlikonest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/Timer.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
#include "vehicle/fieldshunting.h"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <functional>
#include <limits>
#include <utility>
#include <vector>
#include "physics/mover/internal.h"
// Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane.
// Jeśli jakieś zmienne nie są używane w mover.pas, też można je przenosić.
// Przeniesienie wszystkiego na raz zrobiło by zbyt wielki chaos do ogarnięcia.
const double dEpsilon = 0.01; // 1cm (zależy od typu sprzęgu...)
double TMoverParameters::Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2)
{ // zwraca odległość pomiędzy pojazdami (Loc1) i (Loc2) z uwzględnieneim ich długości (kule!)
return hypot(Loc2.X - Loc1.X, Loc1.Y - Loc2.Y) - 0.5 * (Dim2.L + Dim1.L);
};
double TMoverParameters::CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right)
{ // obliczenie odległości pomiędzy sprzęgami (kula!)
return Distance(Left->Loc, Right->Loc, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!)
};
bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, int CouplingType, bool Enforce, bool Audible)
{ // łączenie do swojego sprzęgu (ConnectNo) pojazdu (ConnectTo) stroną (ConnectToNr)
// Ra: zwykle wykonywane dwukrotnie, dla każdego pojazdu oddzielnie
// Ra: trzeba by odróżnić wymóg dociśnięcia od uszkodzenia sprzęgu przy podczepianiu AI do składu
if (ConnectTo == nullptr || CouplingType == coupling::faux)
{
return false;
}
auto &thiscoupler{Couplers[ConnectNo]};
auto const otherend{ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr};
auto &othercoupler = ConnectTo->Couplers[otherend];
auto const distance{CouplerDist(this, ConnectTo) - (thiscoupler.adapter_length + othercoupler.adapter_length)};
if (auto const couplercheck{Enforce || (distance <= dEpsilon && thiscoupler.type() != TCouplerType::NoCoupler && thiscoupler.type() == othercoupler.type())}; false == couplercheck)
{
return false;
}
// no multiple-unit control between an electric and a diesel locomotive, whoever asks for it: the scenario, the AI
// or the player (eu07/maszyna#520)
if (auto const compatible{CompatibleCoupling(ConnectNo, *ConnectTo, otherend, CouplingType)}; compatible != CouplingType)
{
WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name));
CouplingType = compatible;
if (CouplingType == coupling::faux)
{
return false;
}
}
// 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
}
auto const couplingchange{CouplingType ^ thiscoupler.CouplingFlag};
thiscoupler.Connected = ConnectTo;
thiscoupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu
if (ConnectToNr != 2)
{
thiscoupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone
}
othercoupler.Connected = this;
othercoupler.CouplingFlag = CouplingType;
othercoupler.ConnectedNr = ConnectNo;
if (true == Audible && couplingchange != 0)
{
// set sound event flag
int soundflag{sound::none};
std::vector<std::pair<coupling, sound>> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose},
{coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol},
{coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}};
for (auto const &[mappingcoupling, mappingsound] : soundmappings)
{
if ((couplingchange & mappingcoupling) != 0)
{
soundflag |= mappingsound;
}
}
SetFlag(thiscoupler.sounds, soundflag);
}
return true;
}
int TMoverParameters::DettachStatus(int ConnectNo)
{ // Ra: sprawdzenie, czy odległość jest dobra do rozłączania
// powinny być 3 informacje: =0 sprzęg już rozłączony, <0 da się rozłączyć. >0 nie da się rozłączyć
if (!Couplers[ConnectNo].Connected)
return 0; // nie ma nic, to rozłączanie jest OK
if ((Couplers[ConnectNo].CouplingFlag & ctrain_coupler) == 0)
return -Couplers[ConnectNo].CouplingFlag; // hak nie połączony - rozłączanie jest OK
if (TestFlag(DamageFlag, dtrain_coupling))
return -Couplers[ConnectNo].CouplingFlag; // hak urwany - rozłączanie jest OK
// CouplerDist(ConnectNo);
if (Couplers[ConnectNo].type() != TCouplerType::Screw || Neighbours[ConnectNo].distance < 0.01)
return -Couplers[ConnectNo].CouplingFlag; // można rozłączać, jeśli dociśnięty
return Neighbours[ConnectNo].distance > 0.2 ? -Couplers[ConnectNo].CouplingFlag : Couplers[ConnectNo].CouplingFlag;
};
bool TMoverParameters::Dettach(int ConnectNo)
{ // rozlaczanie
auto &thiscoupler{Couplers[ConnectNo]};
auto &othervehicle{thiscoupler.Connected};
auto &othercoupler{othervehicle->Couplers[thiscoupler.ConnectedNr]};
if (othervehicle == nullptr)
{
return true;
} // nie ma nic, to odczepiono
auto couplingchange{thiscoupler.CouplingFlag}; // presume we'll uncouple all active flags
auto const couplingstate{DettachStatus(ConnectNo)}; // stan sprzęgu
if (couplingstate < 0)
{
// gdy scisniete zderzaki, chyba ze zerwany sprzeg (wirtualnego nie odpinamy z drugiej strony)
std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux);
std::tie(thiscoupler.Connected, thiscoupler.ConnectedNr, thiscoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux);
}
else if (couplingstate > 0)
{ // odłączamy węże i resztę, pozostaje sprzęg fizyczny, który wymaga dociśnięcia (z wirtualnym nic)
thiscoupler.CouplingFlag &= coupling::coupler;
othercoupler.CouplingFlag &= coupling::coupler;
}
// set sound event flag
couplingchange ^= thiscoupler.CouplingFlag; // remaining bits were removed from coupling
if (couplingchange != 0)
{
int soundflag{sound::detach}; // HACK: use detach flag to indicate removal of listed coupling
std::vector<std::pair<coupling, sound>> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose},
{coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol},
{coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}};
for (auto const &[mappingcoupling, mappingsound] : soundmappings)
{
if ((couplingchange & mappingcoupling) != 0)
{
soundflag |= mappingsound;
}
}
SetFlag(thiscoupler.sounds, soundflag);
}
return couplingstate < 0;
};
// *************************************************************************************************
// prędkość zbliżania się stykających się końców pojazdów przy zderzeniu, w km/h
// *************************************************************************************************
double TMoverParameters::CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const
{
auto const velocitydifference{CouplerVelocityDifference(End, Other, OtherEnd)};
// the front end closes in on the other vehicle when this one moves forward faster, the rear end when it's slower
return (End == end::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h
}
double TMoverParameters::CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const
{
// V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the
// vehicles face each other (touch with the same ends)
return V - Other.V * DirPatch(End, OtherEnd);
}
bool TMoverParameters::AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const
{
return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity;
}
namespace
{
// the kind of traction a vehicle's engine stands for, as far as its multiple-unit control goes
enum class traction_kind
{
none,
electric,
diesel
};
traction_kind traction_of(TEngineType const Engine)
{
switch (Engine)
{
case TEngineType::ElectricSeriesMotor:
case TEngineType::ElectricInductionMotor:
return traction_kind::electric;
case TEngineType::DieselEngine:
case TEngineType::DieselElectric:
return traction_kind::diesel;
default:
return traction_kind::none;
}
}
} // namespace
bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const
{
if (false == Global.control_coupling_engine_check)
{
return true;
}
// the same control system named on both couplers is the vehicle authors' word that they work together
if (auto const &controltype{Couplers[End].control_type}; false == controltype.empty() && controltype == Other.Couplers[OtherEnd].control_type)
{
return true;
}
auto const traction{traction_of(EngineType)};
auto const othertraction{traction_of(Other.EngineType)};
return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction;
}
int TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const
{
if ((CouplingType & coupling::control) == 0 || (CouplingType & coupling::permanent) != 0 || ControlCouplingAllowed(End, Other, OtherEnd))
{
return CouplingType;
}
return CouplingType & ~coupling::control;
}
// *************************************************************************************************
// Q: 20160713
// Obliczanie sił dzialających na sprzęgach
// *************************************************************************************************
double TMoverParameters::CouplerForce(int const End, double dt)
{
if (coupler_physics_at(End))
{
return coupler_force_physical(End, dt);
}
auto &thiscoupler{Couplers[End]};
auto *othervehicle{Neighbours[End].vehicle->MoverParameters};
auto const otherend{Neighbours[End].vehicle_end};
auto const &othercoupler{othervehicle->Couplers[otherend]};
auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))};
auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada
auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)};
// the ends crushed for good (physics.collisions new, see collision.h) let the buffers meet that much closer
auto const crushed{thiscoupler.crush + othercoupler.crush};
auto const rawdistance{initialdistance + 10.0 * distancedelta};
auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance};
auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)};
auto const absdV{std::abs(dV)};
// potentially generate sounds on clash or stretch
if (newdistance < 0.0 && thiscoupler.Dist > newdistance && dV < -0.1 && false == thiscoupler.has_adapter())
{ // HACK: with adapter present we presume buffers won't clash
// 090503: dzwieki pracy zderzakow
SetFlag(thiscoupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash);
}
else if (thiscoupler.CouplingFlag != coupling::faux && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0)
{
// 090503: dzwieki pracy sprzegu
SetFlag(thiscoupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch);
}
thiscoupler.CheckCollision = false;
thiscoupler.Dist = 0.0;
double CF{0.0};
if (thiscoupler.CouplingFlag == coupling::faux && initialdistance > 0.05)
{ // arbitrary distance
// potentially reset auto coupling lock
thiscoupler.AutomaticCouplingAllowed = true;
}
if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0)
{
thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC);
double BetaAvg = 0;
double Fmax = 0;
if (thiscoupler.CouplingFlag == coupling::faux)
{
BetaAvg = thiscoupler.beta;
Fmax = (thiscoupler.FmaxC + thiscoupler.FmaxB) * CouplerTune;
}
else
{
// usrednij bo wspolny sprzeg
BetaAvg = 0.5 * (thiscoupler.beta + othercoupler.beta);
Fmax = 0.5 * (thiscoupler.FmaxC + thiscoupler.FmaxB + othercoupler.FmaxC + othercoupler.FmaxB) * CouplerTune;
}
auto const distDelta{std::abs(newdistance) - std::abs(thiscoupler.Dist)}; // McZapkie-191103: poprawka na histereze
if (newdistance > 0)
{
if (distDelta > 0)
{
CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg;
}
else
{
CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg;
}
// liczenie sily ze sprezystosci sprzegu
if (newdistance > thiscoupler.DmaxC + othercoupler.DmaxC)
{
// zderzenie
thiscoupler.CheckCollision = true;
}
CouplerStretchCheck(End, CF, dt);
}
if (newdistance < 0)
{
if (distDelta > 0)
{
CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg;
}
else
{
CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg;
}
// liczenie sily ze sprezystosci zderzaka
auto const collisiondistance{(thiscoupler.has_adapter() || othercoupler.has_adapter() ?
std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : // HACK: only take into account buffering ability of automatic coupler
thiscoupler.DmaxB + othercoupler.DmaxB)};
if (-newdistance > collisiondistance)
{
// zderzenie
thiscoupler.CheckCollision = true;
}
if (-newdistance >= std::min(collisiondistance, dEpsilon))
{
automatic_coupling(End, *othervehicle, otherend);
}
}
}
if (thiscoupler.CouplingFlag != coupling::faux)
{
// uzgadnianie prawa Newtona, on the coupler of the other vehicle this one is coupled with, along that vehicle's
// axis: turned around once more when the vehicles face each other
othervehicle->Couplers[otherend].CForce = -CF * DirPatch(End, otherend);
}
return CF;
}
// a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on
void TMoverParameters::CouplerStretchCheck(int const End, double const CF, double dt)
{
auto &thiscoupler{Couplers[End]};
if (std::abs(CF) > thiscoupler.FmaxC)
{
// coupler is stretched with excessive force, may break
thiscoupler.stretch_duration += static_cast<float>(dt);
// give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks
// (arbitrary) chance to break grows from 10-100% over 10 sec period
if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt)
{
damage_coupler(End);
}
}
else
{
thiscoupler.stretch_duration = 0.f;
}
}
bool TMoverParameters::coupler_physics_at(int const End) const
{
if (false == Global.coupler_physics)
{
return false;
}
if (Global.coupler_physics_all || CouplerPhysics)
{
return true;
}
// either vehicle of the pair covered takes the pair in, so both of them compute it the same way
auto const *other{Neighbours[End].vehicle};
return other != nullptr && other->MoverParameters->CouplerPhysics;
}
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;
}
// a coupler torn off by the crush of its end (physics.collisions new) doesn't catch
if (Global.collisions == global_settings::collision_model::physical && (thiscoupler.broken || othercoupler.broken))
{
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, thiscoupler.crush + othercoupler.crush})};
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<float>(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;
// with physics.collisions new the crush of the ends past the buffers is crush_hit()'s
if (hit.broken || (hit.crushed && Global.collisions != global_settings::collision_model::physical))
{
damage_coupler(End);
}
// a broken coupling lets the vehicles part
return false == hit.broken;
}
File diff suppressed because it is too large Load Diff
+592
View File
@@ -0,0 +1,592 @@
/*
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 doors and the exchange of the load
#include "stdafx.h"
#include "physics/mover.h"
#include "vehicle/DynObj.h"
#include "physics/oerlikonest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/Timer.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
#include "vehicle/fieldshunting.h"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <functional>
#include <limits>
#include <utility>
#include <vector>
#include "physics/mover/internal.h"
bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amount)
{
if (Loadname == "pantstate")
{
if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector)
{
// wartość niby "pantstate" - nazwa dla formalności, ważna jest ilość
auto const pantographsetup{static_cast<int>(Amount)};
if (pantographsetup & 1 << 2)
{
DoubleTr = -1;
}
if (pantographsetup & 1 << 0)
{
if (DoubleTr == 1)
{
OperatePantographValve(end::front, operation_t::enable, range_t::local);
}
else
{
OperatePantographValve(end::rear, operation_t::enable, range_t::local);
}
}
if (pantographsetup & 1 << 1)
{
if (DoubleTr == 1)
{
OperatePantographValve(end::rear, operation_t::enable, range_t::local);
}
else
{
OperatePantographValve(end::front, operation_t::enable, range_t::local);
}
}
return true;
}
else
{
return false;
}
}
if (Loadname.empty())
{
// empty the vehicle if requested
LoadTypeChange = LoadType.name != Loadname;
LoadType = load_attributes();
LoadAmount = 0.f;
return true;
}
// can't mix load types, at least for the time being
if (LoadAmount > 0 && LoadType.name != Loadname)
{
return false;
}
auto const loadattributes = std::ranges::find_if(LoadAttributes, [&](auto const &attributes) { return attributes.name == Loadname; });
if (loadattributes == std::end(LoadAttributes))
{
// didn't find matching load configuration, this type is unsupported
return false;
}
LoadTypeChange = LoadType.name != Loadname;
LoadType = *loadattributes;
LoadAmount = safe_clamp(Amount, 0.f, MaxLoad);
ComputeMass();
return true;
}
// *************************************************************************************************
// Q: 20160713
// Test zakończenia załadunku / rozładunku
// *************************************************************************************************
bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadname)
{
if (LSpeed == 0.0)
{
// zerowa prędkość zmiany, to koniec
LoadStatus = 4;
return true;
}
if (Loadname.empty())
{
return LoadStatus >= 4;
}
if (Loadname != LoadType.name)
{
return LoadStatus >= 4;
}
// test zakończenia załadunku/rozładunku
// load exchange speed is reduced if the wagon is overloaded
auto const loadchange{static_cast<float>(std::abs(LSpeed * LastLoadChangeTime) * (LoadAmount > MaxLoad ? 0.5 : 1.0))};
if (LSpeed < 0)
{
// gdy rozładunek
LoadStatus = 2; // trwa rozładunek (włączenie naliczania czasu)
if (loadchange > 0) // jeśli coś przeładowano
{
LastLoadChangeTime = 0; // naliczony czas został zużyty
LoadAmount -= loadchange; // zmniejszenie ilości ładunku
CommandIn.Value1 -= loadchange; // zmniejszenie ilości do rozładowania
if (LoadAmount <= 0 || CommandIn.Value1 <= 0)
{
// pusto lub rozładowano żądaną ilość
LoadStatus = 4; // skończony rozładunek
LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny
}
if (LoadAmount == 0.f)
{
AssignLoad(""); // jak nic nie ma, to nie ma też nazwy
}
ComputeMass();
}
}
else if (LSpeed > 0)
{
// gdy załadunek
LoadStatus = 1; // trwa załadunek (włączenie naliczania czasu)
if (loadchange > 0) // jeśli coś przeładowano
{
LastLoadChangeTime = 0; // naliczony czas został zużyty
LoadAmount += loadchange; // zwiększenie ładunku
CommandIn.Value1 -= loadchange;
if (LoadAmount >= MaxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0)
{
LoadStatus = 4; // skończony załadunek
LoadAmount = std::min<float>(static_cast<float>(MaxLoad * (1.0 + OverLoadFactor)), LoadAmount);
}
ComputeMass();
}
}
return LoadStatus >= 4;
}
bool TMoverParameters::ChangeDoorPermitPreset(int const Change, range_t const Notify)
{
auto const initialstate{Doors.permit_preset};
if (false == Doors.permit_presets.empty())
{
Doors.permit_preset = safe_clamp(Doors.permit_preset + Change, 0, static_cast<int>(Doors.permit_presets.size() - 1));
auto const doors{Doors.permit_presets[Doors.permit_preset]};
auto const permitleft{((doors & 1) != 0)};
auto const permitright{((doors & 2) != 0)};
PermitDoors(CabActive > 0 ? side::left : side::right, permitleft, Notify);
PermitDoors(CabActive > 0 ? side::right : side::left, permitright, Notify);
}
return Doors.permit_preset != initialstate;
}
bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify)
{
auto const initialstate{Doors.step_enabled};
Doors.step_enabled = State;
if (Notify != range_t::local)
{
// wysłanie wyłączenia do pozostałych?
SendCtrlToNext("DoorStep", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control);
}
return Doors.step_enabled != initialstate;
}
bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t const Notify)
{
bool const initialstate{Doors.instances[Door].open_permit};
PermitDoors_(Door, State);
if (Notify != range_t::local)
{
SendCtrlToNext("DoorPermit",
(State ? 1 : -1) // positive: grant, negative: revoke
* (Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed)
1 :
2),
CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control);
}
return Doors.instances[Door].open_permit != initialstate;
}
void TMoverParameters::PermitDoors_(side const Door, bool const State)
{
if (State && State != Doors.instances[Door].open_permit)
{
SetFlag(SoundFlag, sound::doorpermit);
}
Doors.instances[Door].open_permit = State;
}
bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Notify)
{
auto const initialstate{Doors.remote_only};
Doors.remote_only = State;
if (Notify != range_t::local)
{
// wysłanie wyłączenia do pozostałych?
SendCtrlToNext("DoorMode", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control);
}
if (true == State)
{
// when door are put in remote control mode they're automatically open
// TBD, TODO: make it dependant on config switch?
OperateDoors(side::left, true);
OperateDoors(side::right, true);
}
return Doors.remote_only != initialstate;
}
bool TMoverParameters::OperateDoors(side const Door, bool const State, range_t const Notify)
{
auto &door{Doors.instances[Door]};
/*
if( ( State == true ? door.is_open : door.is_closed ) ) {
// TBD: should the command be passed to other vehicles regardless of whether it affected the primary target?
// (for the time being no, methods are often invoked blindly which would lead to commands spam)
return false;
}
*/
bool result{false};
if (Notify == range_t::local)
{
door.local_open = State;
door.local_close = false == State;
result = true;
}
else
{
// remote door operation signals require power to propagate
if (Power24vIsAvailable || Power110vIsAvailable)
{
door.remote_open = State;
door.remote_close = false == State;
result = true;
}
}
if (Notify != range_t::local)
{
SendCtrlToNext(State == true ? "DoorOpen" : "DoorClose",
Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed)
1 :
2,
CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control);
}
return result;
}
// toggle door lock
bool TMoverParameters::LockDoors(bool const State, range_t const Notify)
{
auto const initialstate{Doors.lock_enabled};
Doors.lock_enabled = State;
if (Notify != range_t::local)
{
// wysłanie wyłączenia do pozostałych?
SendCtrlToNext("DoorLock", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control);
}
return Doors.lock_enabled != initialstate;
}
// toggles departure warning
bool TMoverParameters::signal_departure(bool const State, range_t const Notify)
{
if (DepartureSignal == State)
{
// TBD: should the command be passed to other vehicles regardless of whether it affected the primary target?
return false;
}
DepartureSignal = State;
if (Notify != range_t::local)
{
// wysłanie wyłączenia do pozostałych?
SendCtrlToNext("DepartureSignal", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control);
}
return true;
}
// state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while
// the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise.
// doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist
door_closure_t TMoverParameters::door_closure() const
{
if (Doors.range == 0.f || Doors.close_control == control_t::autonomous)
{
return door_closure_t::none;
}
if (std::ranges::any_of(Doors.instances, [](basic_door const &Door) { return false == Door.is_closed; }))
{
return door_closure_t::open;
}
if (Doors.is_locked)
{
return door_closure_t::locked;
}
if (Doors.permit_needed && std::ranges::none_of(Doors.instances, [](basic_door const &Door) { return Door.open_permit; }))
{
return door_closure_t::locked;
}
return door_closure_t::released;
}
bool TMoverParameters::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const
{
return Doors.closure_signal ? door_closure_lamp(Consist, BlinkLit) : Doors.is_locked;
}
bool door_closure_lamp(door_closure_t const State, bool const BlinkLit)
{
switch (State)
{
case door_closure_t::locked:
return true;
case door_closure_t::released:
return BlinkLit;
default:
return false;
}
}
// automatic door controller update
void TMoverParameters::update_doors(double const Deltatime)
{
if (Doors.range == 0.f)
{
return;
} // HACK: crude way to distinguish vehicles with actual doors
// NBMX Obsluga drzwi, MC: zuniwersalnione
auto const localopencontrol{false == Doors.remote_only && (Doors.open_control == control_t::passenger || Doors.open_control == control_t::mixed)};
auto const remoteopencontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed};
auto const localclosecontrol{false == Doors.remote_only && (Doors.close_control == control_t::passenger || Doors.close_control == control_t::mixed)};
auto const remoteclosecontrol{Doors.close_control == control_t::driver || Doors.close_control == control_t::conductor || Doors.close_control == control_t::mixed};
Doors.is_locked = true == Doors.has_lock && true == Doors.lock_enabled && Vel >= Doors.doorLockSpeed;
for (auto &door : Doors.instances)
{
update_door_requests(door, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol);
move_door(door, Deltatime);
}
if (false == Doors.instances[side::right].is_open && false == Doors.instances[side::left].is_open)
{
return;
}
if (Doors.auto_duration > 0.f)
{
update_door_timers(Deltatime);
}
/*
// the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold
std::array<side, 2> const doorids { side::right, side::left };
for( auto const doorid : doorids ) {
auto const &door { Doors.instances[ doorid ] };
if( true == door.is_open ) {
if( ( ( Doors.auto_velocity != -1.f ) && ( Vel > Doors.auto_velocity ) )
|| ( ( door.auto_timer != -1.f ) && ( door.auto_timer <= 0.f ) ) ) {
// close the door and set the timer to expired state (closing may happen sooner if vehicle starts moving)
OperateDoors( doorid, false, range_t::local );
}
}
}
*/
}
// the permit, the state and the requests of a door, and whether it and its step open or close
void TMoverParameters::update_door_requests(basic_door &door, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol)
{
// revoke permit if...
door.open_permit = true == door.open_permit // ...we already have one...
&& (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state...
|| (false == Doors.is_locked // ...and the door lock is engaged...
&& false == door.remote_close)); // ...or the door is about to be closed
door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f));
door.is_closed = door.position <= 0.f && door.step_position <= 0.f;
door.is_door_closed = door.position <= 0.f;
door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit);
door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit);
door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open);
door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open);
auto const openrequest{door_open_request(door, localopencontrol, remoteopencontrol)};
auto const closerequest{door_close_request(door, localclosecontrol, remoteclosecontrol)};
auto const ispowered{doors_powered()};
door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked));
door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest);
door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening;
door.step_folding = door_step_folding(door);
if (true == door.is_opening)
{
door.auto_timer = door_open_duration(door, localopencontrol, remoteopencontrol);
}
}
// whether the door is asked to open, by the passengers, from afar or by itself
bool TMoverParameters::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const
{
auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)};
return (localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open);
}
// whether the door is asked to close, by the passengers, from afar, or by itself: over the speed, after its time or
// with its permit taken back
bool TMoverParameters::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const
{
auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) ||
(Doors.permit_needed && false == door.open_permit)};
return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open);
}
// whether the doors have the voltage they work on
bool TMoverParameters::doors_powered() const
{
if (Doors.voltage == 0)
{
return true;
}
if (Doors.voltage == 24)
{
return Power24vIsAvailable || Power110vIsAvailable;
}
return Doors.voltage == 110 && Power110vIsAvailable;
}
// whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to
// close or closed
bool TMoverParameters::door_step_folding(basic_door const &door) const
{
auto const unfolded{door.step_position > 0.f};
auto const mayfold{false == Doors.step_enabled || (Doors.permit_needed ? false == door.open_permit : door.is_closing)};
return unfolded && mayfold && (door.close_delay > Doors.close_delay || door.position <= 0.f);
}
// how long the opening door stays open: the time of the doors, for the passengers' opening and, if it counts, the
// opening from afar; none otherwise
float TMoverParameters::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const
{
if (localopencontrol && door.local_open)
{
return Doors.auto_duration;
}
if (remoteopencontrol && door.remote_open && Doors.auto_include_remote)
{
return Doors.auto_duration;
}
return -1.f;
}
// a door and its step moved as they open or close
void TMoverParameters::move_door(basic_door &door, double const Deltatime)
{
// doors
if (true == door.is_opening)
{
// open door
if (false == door.step_unfolding // no wait if no doorstep
|| Doors.step_type == 2)
{ // no wait for rotating doorstep
door.open_delay += static_cast<float>(Deltatime);
if (door.open_delay > Doors.open_delay)
{
door.position = std::min<float>(Doors.range, static_cast<float>(door.position + Doors.open_rate * Deltatime));
}
}
door.close_delay = 0.f;
}
if (true == door.is_closing)
{
// close door
door.close_delay += static_cast<float>(Deltatime);
if (door.close_delay > Doors.close_delay)
{
door.position = std::max<float>(0.f, static_cast<float>(door.position - Doors.close_rate * Deltatime));
}
door.open_delay = 0.f;
}
// doorsteps
if (door.step_unfolding)
{
// unfold left doorstep
door.step_position = std::min<float>(1.f, static_cast<float>(door.step_position + Doors.step_rate * Deltatime));
}
if (door.step_folding)
{
// fold left doorstep
if (is_multiple_unit())
{
// multi-unit vehicles typically fold the doorstep only after closing the door
if (door.position <= 0.f)
{
door.step_position = std::max<float>(0.f, static_cast<float>(door.step_position - Doors.step_rate * Deltatime));
}
}
else
{
door.step_position = std::max<float>(0.f, static_cast<float>(door.step_position - Doors.step_rate * Deltatime));
}
}
}
// the timers of the open doors which close after a while, kept running while the load is exchanged
void TMoverParameters::update_door_timers(double const Deltatime)
{
// update door timers if the door close after defined time
for (auto &door : Doors.instances)
{
if (false == door.is_open)
{
continue;
}
if (door.auto_timer > 0.f)
{
door.auto_timer -= static_cast<float>(Deltatime);
}
// if there's load exchange in progress, reset the timer(s) for already open doors
if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0)
{
door.auto_timer = Doors.auto_duration;
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
/*
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 helpers the files of physics/mover/ share: only they include this header
#pragma once
#include "physics/mover.h"
const double CouplerTune = 0.1; // skalowanie tlumiennosci
inline double square(double val) // SQR() zle liczylo w current() ...
{
return val * val;
}
int DirPatch(int Coupler1, int Coupler2);
int DirF(int CouplerN);
double TableInterpolation(std::map<double, double> &Map, double Parameter);
double compression_at(TCoupling const &Coupler, int const End);
bool issection(std::string_view Name, std::string_view Input);
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+298
View File
@@ -0,0 +1,298 @@
/*
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 security system (vigilance, cab signalling, radio-stop)
#include "stdafx.h"
#include "physics/mover.h"
#include "vehicle/DynObj.h"
#include "physics/oerlikonest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/Timer.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
#include "vehicle/fieldshunting.h"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <functional>
#include <limits>
#include <utility>
#include <vector>
#include "physics/mover/internal.h"
void TSecuritySystem::set_enabled(bool e)
{
if (vigilance_enabled || cabsignal_enabled || radiostop_enabled)
enabled = e;
if (CabDependent)
cabactive = 0;
}
void TSecuritySystem::acknowledge_press()
{
pressed = true;
if (vigilance_timer > AwareDelay)
{
alert_timer = 0.0;
vigilance_timer = 0.0;
return;
}
vigilance_timer = 0.0;
if (!separate_acknowledge && cabsignal_active && !cabsignal_lock)
{
cabsignal_active = false;
alert_timer = 0.0;
}
}
void TSecuritySystem::acknowledge_release()
{
pressed = false;
if (press_timer > MaxHoldTime)
alert_timer = 0.0;
press_timer = 0.0;
}
void TSecuritySystem::cabsignal_reset()
{
if (cabsignal_active && !cabsignal_lock)
{
cabsignal_active = false;
alert_timer = 0.0;
}
}
void TSecuritySystem::update(double dt, double vel, bool pwr, int cab)
{
if (!enabled || !pwr || DebugModeFlag)
{
power = pwr;
cabsignal_active = false;
vigilance_timer = 0.0;
alert_timer = 0.0;
press_timer = 0.0;
return;
}
bool just_powered_on = !power && pwr;
bool just_activated = CabDependent && cabactive != cab;
/* enabling battery */
if (cabsignal_enabled && (just_powered_on || just_activated))
{
cabsignal_active = true;
alert_timer = SoundSignalDelay;
}
power = pwr;
velocity = vel;
cabactive = cab;
if (vigilance_suspended)
{
// the vigilance device is switched off: no time counts towards a new alarm, of the alerter or of the button held
// too long. an alarm already on, with the emergency braking it leads to, stays until it's acknowledged as usual
if (vigilance_timer <= AwareDelay)
vigilance_timer = 0.0;
if (press_timer <= MaxHoldTime)
press_timer = 0.0;
}
else
{
if (vigilance_enabled && velocity > AwareMinSpeed)
vigilance_timer += dt;
if (pressed && (!is_sifa || velocity > AwareMinSpeed))
press_timer += dt;
}
if (vigilance_timer > AwareDelay || press_timer > MaxHoldTime || cabsignal_active)
alert_timer += dt;
}
void TSecuritySystem::set_cabsignal()
{
if (cabsignal_enabled && power)
cabsignal_active = true;
}
bool TSecuritySystem::has_separate_acknowledge() const
{
return separate_acknowledge;
}
bool TSecuritySystem::is_blinking() const
{
if (!power)
return false;
return alert_timer > 0.0;
}
bool TSecuritySystem::is_vigilance_blinking() const
{
if (!power)
return false;
return press_timer > MaxHoldTime || vigilance_timer > AwareDelay;
}
bool TSecuritySystem::is_cabsignal_blinking() const
{
if (!power)
return false;
return cabsignal_active;
}
bool TSecuritySystem::is_beeping() const
{
if (!power)
return false;
return alert_timer > SoundSignalDelay && (!separate_acknowledge || is_vigilance_blinking());
}
bool TSecuritySystem::is_cabsignal_beeping() const
{
if (!power)
return false;
return alert_timer > SoundSignalDelay && is_cabsignal_blinking();
}
bool TSecuritySystem::is_braking() const
{
if (!power && enabled)
return true;
return alert_timer > SoundSignalDelay + EmergencyBrakeDelay;
}
bool TSecuritySystem::radiostop_available() const
{
return radiostop_enabled;
}
void TSecuritySystem::set_cabsignal_lock(bool v)
{
cabsignal_lock = v;
}
void TSecuritySystem::set_shunt_mode(bool const State)
{
vigilance_suspended = State && AwareOffInShuntMode;
}
bool TSecuritySystem::is_engine_blocked() const
{
if (!is_sifa)
return false;
return velocity < AwareMinSpeed && pressed;
}
void TSecuritySystem::load(std::string const &line, double Vmax)
{
std::string awaresystem = extract_value("AwareSystem", line);
if (awaresystem.find("Active") != std::string::npos)
vigilance_enabled = true;
if (awaresystem.find("CabSignal") != std::string::npos)
cabsignal_enabled = true;
if (awaresystem.find("Sifa") != std::string::npos)
is_sifa = true;
if (awaresystem.find("SeparateAcknowledge") != std::string::npos)
separate_acknowledge = true;
extract_value(AwareDelay, "AwareDelay", line, "");
AwareMinSpeed = 0.1 * Vmax; // domyślnie 10% Vmax
extract_value(AwareMinSpeed, "AwareMinSpeed", line, "");
extract_value(SoundSignalDelay, "SoundSignalDelay", line, "");
extract_value(EmergencyBrakeDelay, "EmergencyBrakeDelay", line, "");
extract_value(MaxHoldTime, "MaxHoldTime", line, "");
extract_value(radiostop_enabled, "RadioStop", line, "");
extract_value(MagnetLocation, "MagnetLocation", line, "");
extract_value(CabDependent, "CabDependent", line, "");
extract_value(AwareOffInShuntMode, "AwareOffInShuntMode", line, "");
}
// *****************************************************************************
// Q: 20160710
// zbicie czuwaka / SHP
// *****************************************************************************
// hunter-091012: rozbicie alarmow, dodanie testu czuwaka
void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP
{
// reset all, used by AI
SecuritySystem.acknowledge_press();
SecuritySystem.acknowledge_release();
SecuritySystem.cabsignal_reset();
}
// *************************************************************************************************
// Q: 20160711
// sprawdzanie stanu CA/SHP
// *************************************************************************************************
void TMoverParameters::SecuritySystemCheck(double dt)
{
bool isPower = Power24vIsAvailable || Power110vIsAvailable;
// the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457)
SecuritySystem.set_shunt_mode(ShuntMode);
SecuritySystem.update(dt, Vel, isPower, CabActive);
if (!Battery || !Radio || !RadioFuse)
{ // wyłączenie baterii deaktywuje sprzęt
RadiostopSwitch(false);
}
}
// *************************************************************************************************
// Q: 20160711
// włączenie / wyłączenie hamowania awaryjnego
// *************************************************************************************************
bool TMoverParameters::RadiostopSwitch(bool Switch)
{
bool EBS;
if (BrakeSystem != TBrakeSystem::Individual && BrakeCtrlPosNo > 0)
{
if (true == Switch && false == RadioStopFlag)
{
RadioStopFlag = Switch;
EBS = true;
}
else
{
if (Switch == false && std::abs(V) < 0.1)
{
// odblokowanie hamulca bezpieczenistwa tylko po zatrzymaniu
RadioStopFlag = Switch;
EBS = true;
}
else
{
EBS = false;
}
}
}
else
{
// nie ma hamulca bezpieczenstwa gdy nie ma hamulca zesp.
EBS = false;
}
return EBS;
}
+471
View File
@@ -0,0 +1,471 @@
/*
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/.
*/
// setting the vehicle up after reading its definition: the checks, the brake valves, the handles and the pipes
#include "stdafx.h"
#include "physics/mover.h"
#include "vehicle/DynObj.h"
#include "physics/oerlikonest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/Timer.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
#include "vehicle/fieldshunting.h"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <functional>
#include <limits>
#include <utility>
#include <vector>
#include "physics/mover/internal.h"
// *************************************************************************************************
// Q: 20160717
// *************************************************************************************************
bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/)
{
WriteLog("check locomotive parameters...");
bool OK = true;
AutoRelayFlag = AutoRelayType == 1;
if (NominalBatteryVoltage == 0.0)
{
BatteryStart = start_t::disabled;
}
Sand = SandCapacity;
// NOTE: for diesel-powered vehicles we automatically convert legacy "main" power source to more accurate "engine"
if (CompressorPower == 0 && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric))
{
CompressorPower = 3;
}
// for these engine types secondary controller positions index MotorParam table
if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) &&
ScndCtrlPosNo > MotorParametersArraySize)
{
WriteLog("SCPN=" + std::to_string(ScndCtrlPosNo) + " exceeds motor parameter table size, limited to " + std::to_string(MotorParametersArraySize));
ScndCtrlPosNo = MotorParametersArraySize;
}
// WriteLog("aa = " + AxleArangement + " " + std::string( Pos("o", AxleArangement)) );
if (contains(AxleArangement, "o") && EngineType == TEngineType::ElectricSeriesMotor)
{
// test poprawnosci ilosci osi indywidualnie napedzanych
OK = RList[1].Bn * RList[1].Mn == NPoweredAxles;
// WriteLogSS("aa ok", BoolToYN(OK));
}
if (BrakeSystem == TBrakeSystem::Individual && BrakeSubsystem != TBrakeSubSystem::ss_None)
OK = false; //!
if (BrakeVVolume == 0 && MaxBrakePress[3] > 0 && BrakeSystem != TBrakeSystem::Individual)
{
BrakeVVolume = MaxBrakePress[3] / (5.0 - MaxBrakePress[3]) * (BrakeCylRadius * BrakeCylRadius * BrakeCylDist * BrakeCylNo * M_PI) * 1000;
}
if (BrakeVVolume == 0.0)
{
BrakeVVolume = 0.01;
}
// WriteLog("BVV = " + FloatToStr(BrakeVVolume));
CreateBrakeValve();
CreateBrakeHandles();
CreateBrakePipes();
if (LightsPosNo > 0)
LightsPos = LightsDefPos;
// set default wiper switch position
wiperSwitchPos = WiperDefaultPos;
if (CompressorListPosNo > 0)
CompressorListPos = CompressorListDefPos;
// the genset of a dual-mode vehicle is a second source of the traction circuit of an induction motor vehicle
if (Genset.fitted() && (EngineType != TEngineType::ElectricInductionMotor || EnginePowerSource.SourceType != TPowerSource::CurrentCollector))
{
WriteLog("GensetPower ignored: a genset works only with EngineType=ElectricInductionMotor and EnginePower=CurrentCollector");
Genset = genset_device{};
}
// NOTE: legacy compatibility behaviour for vehicles without defined heating power source
if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined)
{
HeatingPowerSource.SourceType = TPowerSource::Main;
}
if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0)
{
HeatingPowerSource.SourceType = TPowerSource::PowerCable;
HeatingPowerSource.PowerType = TPowerType::ElectricPower;
}
// checking ready flag
// to dac potem do init
if (ReadyFlag) // gotowy do drogi
{
SetReadyToDepart();
}
else
{ // zahamowany}
SetBraked();
}
ActFlowSpeed = 0.0;
BrakeCtrlPosR = BrakeCtrlPos;
if (BrakeLocHandle == TBrakeHandle::Knorr)
LocalBrakePosA = 0.5;
Pipe->CreatePress(PipePress);
Pipe2->CreatePress(ScndPipePress);
Pipe->Act();
Pipe2->Act();
EqvtPipePress = PipePress;
Handle->Init(PipePress);
ComputeConstans();
if (LoadFlag > 0)
{
if (LoadAmount < MaxLoad * 0.45)
{
IncBrakeMult();
IncBrakeMult();
DecBrakeMult(); // TODO: przeinesiono do mover.cpp
if (LoadAmount < MaxLoad * 0.35)
DecBrakeMult();
}
else
{
IncBrakeMult(); // TODO: przeinesiono do mover.cpp
if (LoadAmount >= MaxLoad * 0.55)
IncBrakeMult();
}
}
// taki mini automat - powinno byc ladnie dobrze :)
BrakeDelayFlag = bdelay_P;
if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R))
BrakeDelayFlag = bdelay_G;
if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G))
BrakeDelayFlag = bdelay_R;
/*
// disabled, as test mode is used in specific situations and not really a default
if (BrakeOpModes & bom_PS)
BrakeOpModeFlag = bom_PS;
else
*/
BrakeOpModeFlag = bom_PN;
// yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)%
std::array<int, 8> const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2};
for (int b = 1; b < 4; b++)
{
if (BrakeDelay[b] == 0)
BrakeDelay[b] = DefBrakeTable[b];
BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0;
}
Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag);
/*
ScndPipePress = Compressor;
*/
// WriteLogSS("OK=", BoolTo10(OK));
// WriteLog("");
if (EIMCtrlType == 3)
{
for (auto idx = 0; idx < MainCtrlPosNo; ++idx)
{
if (UniCtrlList[idx].MaxCtrlVal > 0.0)
{
UniCtrlNoPowerPos = std::max(0, idx - 1);
break;
}
}
}
// security system
// by default place the magnet in the vehicle centre
if (SecuritySystem.MagnetLocation == 0)
{
SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5;
}
SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L);
return OK;
}
// the distributor valve of the vehicle's kind
void TMoverParameters::CreateBrakeValve()
{
switch (BrakeValve)
{
case TBrakeValve::W:
case TBrakeValve::K:
{
WriteLog("XBT W, K");
Hamulec = std::make_shared<TWest>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
if (MBPM < 2) // jesli przystawka wazaca
Hamulec->SetLP(0, MaxBrakePress[3], 0);
else
Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]);
break;
}
case TBrakeValve::KE:
{
WriteLog("XBT WKE");
Hamulec = std::make_shared<TKE>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
Hamulec->SetRM(RapidMult);
if (MBPM < 2) // jesli przystawka wazaca
Hamulec->SetLP(0, MaxBrakePress[3], 0);
else
Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]);
break;
}
case TBrakeValve::NESt3:
case TBrakeValve::ESt3:
case TBrakeValve::ESt3AL2:
case TBrakeValve::ESt4:
{
WriteLog("XBT NESt3, ESt3, ESt3AL2, ESt4");
Hamulec = std::make_shared<TNESt3>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
static_cast<TNESt3 *>(Hamulec.get())->SetSize(BrakeValveSize, BrakeValveParams);
if (MBPM < 2) // jesli przystawka wazaca
Hamulec->SetLP(0, MaxBrakePress[3], 0);
else
Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]);
break;
}
case TBrakeValve::LSt:
{
WriteLog("XBT LSt");
Hamulec = std::make_shared<TLSt>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
Hamulec->SetRM(RapidMult);
break;
}
case TBrakeValve::EStED:
{
WriteLog("XBT EStED");
Hamulec = std::make_shared<TEStED>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
Hamulec->SetRM(RapidMult);
if (MBPM < 2)
{
// jesli przystawka wazaca
Hamulec->SetLP(0, MaxBrakePress[3], 0);
}
else
{
Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]);
}
break;
}
case TBrakeValve::EP2:
{
WriteLog("XBT EP2");
Hamulec = std::make_shared<TEStEP2>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]);
break;
}
case TBrakeValve::EP1:
{
WriteLog("XBT EP1");
Hamulec = std::make_shared<TEStEP1>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]);
Hamulec->SetRM(RapidMult);
break;
}
case TBrakeValve::CV1:
{
WriteLog("XBT CV1");
Hamulec = std::make_shared<TCV1>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
break;
}
case TBrakeValve::CV1_L_TR:
{
WriteLog("XBT CV1_L_T");
Hamulec = std::make_shared<TCV1L_TR>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
break;
}
default:
Hamulec = std::make_shared<TBrake>(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA);
}
Hamulec->SetASBP(MaxBrakePress[4]);
Hamulec->SetRV(RapidVel);
}
// the driver's handle and the local brake handle of the vehicle's kinds
void TMoverParameters::CreateBrakeHandles()
{
switch (BrakeHandle)
{
using enum TBrakeHandle;
case FV4a:
Handle = std::make_shared<TFV4aM>();
break;
case MHZ_EN57:
case MHZ_K8P:
Handle = std::make_shared<TMHZ_EN57>();
break;
case FVel6:
Handle = std::make_shared<TFVel6>();
break;
case FVE408:
Handle = std::make_shared<TFVE408>();
break;
case testH:
Handle = std::make_shared<Ttest>();
break;
case M394:
Handle = std::make_shared<TM394>();
break;
case Knorr:
Handle = std::make_shared<TH14K1>();
break;
case St113:
Handle = std::make_shared<TSt113>();
break;
case MHZ_K5P:
Handle = std::make_shared<TMHZ_K5P>();
break;
case MHZ_6P:
Handle = std::make_shared<TMHZ_6P>();
break;
default:
Handle = std::make_shared<TDriverHandle>();
}
Handle->SetParams(Handle_AutomaticOverload, Handle_ManualOverload, Handle_GenericDoubleParameter1, Handle_GenericDoubleParameter2, Handle_OverloadMaxPressure, Handle_OverloadPressureDecrease);
switch (BrakeLocHandle)
{
case TBrakeHandle::FD1:
{
LocHandle = std::make_shared<TFD1>();
LocHandle->Init(MaxBrakePress[0]);
if (TrainType == train_type::emu)
{
dynamic_cast<TFD1 *>(LocHandle.get())->SetSpeed(3.5);
}
break;
}
case TBrakeHandle::Knorr:
{
LocHandle = std::make_shared<TH1405>();
LocHandle->Init(MaxBrakePress[0]);
break;
}
default:
LocHandle = std::make_shared<TDriverHandle>();
}
}
// the brake pipe, the main pipe and the spring brake's cylinder
void TMoverParameters::CreateBrakePipes()
{
if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy
Spg = 0.792;
else
Spg = 0.507;
// WriteLog("SPG = " + FloatToStr(Spg));
Pipe = std::make_shared<TReservoir>();
Pipe2 = std::make_shared<TReservoir>(); // zabezpieczenie, bo sie PG wywala... :(
Pipe->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); // dlugosc x przekroj x odejscia i takie tam
Pipe2->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1);
if (!SpringBrake.Cylinder)
{
SpringBrake.Cylinder = std::make_shared<TReservoir>();
SpringBrake.Cylinder->CreateCap(1);
}
}
// the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none
double TMoverParameters::InitialScndPipePress(double const HosePressure) const
{
if (VeselVolume > 0.0)
{
return CompressedVolume / VeselVolume;
}
if ((Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 || (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0)
{
return HosePressure;
}
return 0.0;
}
// the air and the controls of a vehicle ready to depart
void TMoverParameters::SetReadyToDepart()
{
WriteLog("Ready to depart");
CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0;
ScndPipePress = InitialScndPipePress(5.0);
PipePress = CntrlPipePress;
BrakePress = 0.0;
LocalBrakePosA = 0.0;
if (CabActive == 0)
BrakeCtrlPos = static_cast<int>(Handle->GetPos(bh_NP));
else
BrakeCtrlPos = static_cast<int>(Handle->GetPos(bh_RP));
/*
// NOTE: disabled and left up to the driver, if there's any
MainSwitch( false );
PantFront( true );
PantRear( true );
MainSwitch( true );
*/
DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno!
DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów
LimPipePress = CntrlPipePress;
Battery = BatteryStart != start_t::disabled;
}
// the air and the brakes of a vehicle standing braked
void TMoverParameters::SetBraked()
{
WriteLog("Braked");
Volume = BrakeVVolume * MaxBrakePress[3];
CompressedVolume = VeselVolume * MinCompressor * 0.55;
/*
ScndPipePress = 5.1;
*/
ScndPipePress = InitialScndPipePress(5.1);
PipePress = LowPipePress;
PipeBrakePress = MaxBrakePress[3] * 0.5;
BrakePress = MaxBrakePress[3] * 0.5;
LocalBrakePosA = 0.0;
BrakeCtrlPos = static_cast<int>(Handle->GetPos(bh_NP));
LimPipePress = LowPipePress;
if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true)
{
IncManualBrakeLevel(ManualBrakePosNo);
}
if (SpringBrake.MaxBrakeForce > 0.0)
{
SpringBrake.Activate = true;
}
}
File diff suppressed because it is too large Load Diff