18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 10:05:23 +01:00
Files
maszyna/vehicle/dynamic/movement.cpp
jerrrrycho 2a63ddd1a9 fix(derailment): a vehicle derailed running forked slides along the track of its leading axle
With its bogies on the two ways of a switch, the line between its axles
is a chord across the two tracks, and the bed of the off-track motion lay
between them. track_front() and track_bed() now take the leading axle by
the sign of V while the bogies run forked (m_forkbogies, the axles not on
one way): its PathDirection() is the line, its position the point of the
bed. off_track_offset() is measured from that point too. Without a fork
nothing changes: the bed is between the axles as before.

same_way() moves to vehicle_dynamic (vehicle/dynamic/internal.h) for this.
2026-12-01 17:27:31 +01:00

496 lines
20 KiB
C++

/*
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/.
*/
/*
MaSzyna EU07 locomotive simulator
Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others
*/
// moving a vehicle along its track, its axles and its bogies
#include "stdafx.h"
#include "vehicle/DynObj.h"
#include "physics/vehicle.h"
#include "vehicle/lightsprogrammer.h"
#include "simulation/simulation.h"
#include "simulation/blackboxrecorder.h"
#include "rendering/lightarray.h"
#include "vehicle/Camera.h"
#include "vehicle/Train.h"
#include "vehicle/odometer.h"
#include "vehicle/pulleemode.h"
#include "vehicle/Driver.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <format>
#include <random>
#include <iterator>
#include <numbers>
#include <optional>
#include <string_view>
#include <unordered_set>
#include <utility>
#include <vector>
#include "utilities/Globals.h"
#include "utilities/Timer.h"
#include "utilities/workerpool.h"
#include "utilities/Logs.h"
#include "utilities/glmHelpers.h"
#include "Console.h"
#include "world/Traction.h"
#include "audio/sound.h"
#include "model/MdlMngr.h"
#include "model/Model3d.h"
#include "vehicle/doorwings.h"
#include "rendering/renderer.h"
#include "editor/editorTerrainStreamer.hpp"
#include "application/uitranscripts.h"
#include "input/messaging.h"
#include "application/application.h"
#include "vehicle/Driver.h"
#include "vehicle/dynamic/internal.h"
void TDynamicObject::FastMove(double fDistance)
{
physics->SetMoveLength(physics->MoveLength() + fDistance);
}
void TDynamicObject::Move(double fDistance)
{
if( physics->OffTrack.active() ) {
// physics.derailment new: off the track it goes on the ground
move_off_track( fDistance );
return;
}
move_axles( fDistance );
// a switch thrown under the train: did the axles that ran onto it take the way of those ahead of them
watch_fork_entries( fDistance );
if( fDistance != 0.0 || m_offtrackplaced ) // nie liczyć ponownie, jeśli stoi
{ // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach
// (also once the vehicle off the track is back on the rails)
m_offtrackplaced = false;
place_by_axles();
// the vehicle running forked, with its place and heading known
update_forks();
}
}
void TDynamicObject::move_axles(double fDistance)
{ // przesuwanie pojazdu po
// trajektorii polega na
// przesuwaniu poszczególnych osi
// Ra: wartość prędkości 2km/h ma ograniczyć aktywację eventów w przypadku
// drgań
if (Axle0.GetTrack() == Axle1.GetTrack()) // przed przesunięciem
{ // powiązanie pojazdu z osią można zmienić tylko wtedy, gdy skrajne osie są
// na tym samym torze
if (physics->Vel >
2) //|[km/h]| nie ma sensu zmiana osi, jesli pojazd drga na postoju
iAxleFirst = physics->V() >= 0.0 ?
1 :
0; //[m/s] ?1:0 - aktywna druga oś w kierunku jazdy
// aktualnie eventy aktywuje druga oś, żeby AI nie wyłączało sobie semafora
// za szybko
}
if (fDistance > 0.0)
{ // gdy ruch w stronę sprzęgu 0, doliczyć korektę do osi 1
bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu
bEnabled &= Axle1.Move(fDistance /*-fAdjustment*/, iAxleFirst != 0); // oś z tyłu pojazdu
}
else if (fDistance < 0.0)
{ // gdy ruch w stronę sprzęgu 1, doliczyć korektę do osi 0
bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza
bEnabled &= Axle0.Move(fDistance /*-fAdjustment*/, iAxleFirst == 0); // oś z przodu pojazdu
}
else // gf: bez wywolania Move na postoju nie ma event0
{
bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza
bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu
}
}
void TDynamicObject::place_by_axles()
{ // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach
vPosition = 0.5 * (Axle1.pPosition + Axle0.pPosition); //środek między skrajnymi osiami
vFront = Axle0.pPosition - Axle1.pPosition; // wektor pomiędzy skrajnymi osiami
// Ra 2F1J: to nie jest stabilne (powoduje rzucanie taborem) i wymaga
// dopracowania
fAdjustment = glm::length(vFront) - fAxleDist; // na łuku będzie ujemny
// if (fabs(fAdjustment)>0.02) //jeśli jest zbyt dużo, to rozłożyć na kilka przeliczeń (wygasza drgania?)
//{//parę centymetrów trzeba by już skorygować; te błędy mogą się też
// generować na ostrych łukach
// fAdjustment*=0.5; //w jednym kroku korygowany jest ułamek błędu
//}
// else
// fAdjustment=0.0;
vFront = glm::normalize(vFront); // kierunek ustawienia pojazdu (wektor jednostkowy)
vLeft = glm::normalize(glm::cross(glm::dvec3(vWorldUp), vFront)); // wektor poziomy w lewo,
// normalizacja potrzebna z powodu pochylenia (vFront)
vUp = glm::cross(vFront, vLeft); // wektor w górę, będzie jednostkowy
modelRot.z = atan2(-vFront.x, vFront.z); // kąt obrotu pojazdu [rad]; z ABuBogies()
auto const roll { Roll() }; // suma przechyłek
if (roll != 0.0)
{ // wyznaczanie przechylenia tylko jeśli jest przechyłka
// można by pobrać wektory normalne z toru...
mMatrix = glm::rotate(glm::dmat4(1.0), roll * 0.5, vFront); // ta macierz jest potrzebna głównie do wyświetlania // obrót wzdłuż osi o przechyłkę
vUp = glm::dvec3(mMatrix * glm::dvec4(vUp, 0.0)); // wektor w górę pojazdu (przekręcenie na przechyłce)
// vLeft=mMatrix*DynamicObject->vLeft;
// vUp=CrossProduct(vFront,vLeft); //wektor w górę
// vLeft=Normalize(CrossProduct(vWorldUp,vFront)); //wektor w lewo
vLeft = glm::normalize(glm::cross(vUp, vFront)); // wektor w lewo
// vUp=CrossProduct(vFront,vLeft); //wektor w górę
}
mMatrix = BasisChange(vLeft, vUp, vFront); // to też można by od razu policzyć, ale potrzebne jest do wyświetlania // przesuwanie jest jednak rzadziej niż renderowanie
mMatrix = glm::inverse(mMatrix); // wyliczenie macierzy dla pojazdu (potrzebna tylko do wyświetlania?)
// if (physics->CategoryFlag&2)
{ // przesunięcia są używane po wyrzuceniu pociągu z toru
vPosition.x += physics->OffsetTrackH() * vLeft.x; // dodanie przesunięcia w bok
vPosition.z += physics->OffsetTrackH() * vLeft.z; // vLeft jest wektorem poprzecznym
// if () na przechyłce będzie dodatkowo zmiana wysokości samochodu
vPosition.y += physics->OffsetTrackV(); // te offsety są liczone przez the physics
}
// obliczanie pozycji sprzęgów do liczenia zderzeń
auto dir = 0.5 * physics->Dim.L * vFront; // wektor sprzęgu
vCoulpler[VehicleEnd::front] = vPosition + dir; // współrzędne sprzęgu na początku
vCoulpler[VehicleEnd::rear] = vPosition - dir; // współrzędne sprzęgu na końcu
// bCameraNear=
// if (bCameraNear) //jeśli istotne są szczegóły (blisko kamery)
{ // przeliczenie cienia
TTrack *t0 = Axle0.GetTrack(); // już po przesunięciu
TTrack *t1 = Axle1.GetTrack();
if (t0->eEnvironment == e_flat && t1->eEnvironment == e_flat) // może być e_bridge...
fShade = 0.0; // standardowe oświetlenie
else
{ // jeżeli te tory mają niestandardowy stopień zacienienia
// (e_canyon, e_tunnel)
if (t0->eEnvironment == t1->eEnvironment)
{
switch (t0->eEnvironment)
{ // typ zmiany oświetlenia
case e_canyon:
fShade = 0.65f;
break; // zacienienie w kanionie
case e_tunnel:
fShade = 0.20f;
break; // zacienienie w tunelu
}
}
else // dwa różne
{ // liczymy proporcję
double d = Axle0.GetTranslation(); // aktualne położenie na torze
if (Axle0.GetDirection() < 0)
d = t0->Length() - d; // od drugiej strony liczona długość
d /= fAxleDist; // rozsataw osi procentowe znajdowanie się na torze
float shadefrom = 1.0f, shadeto = 1.0f;
// NOTE, TODO: calculating brightness level is used enough times to warrant encapsulation into a function
switch( t0->eEnvironment ) {
case e_canyon: { shadeto = 0.65f; break; }
case e_tunnel: { shadeto = 0.2f; break; }
default: {break; }
}
switch( t1->eEnvironment ) {
case e_canyon: { shadefrom = 0.65f; break; }
case e_tunnel: { shadefrom = 0.2f; break; }
default: {break; }
}
fShade = std::lerp( shadefrom, shadeto, static_cast<float>( d ) );
/*
switch (t0->eEnvironment)
{ // typ zmiany oświetlenia - zakładam, że
// drugi tor ma e_flat
case e_canyon:
fShade = (d * 0.65) + (1.0 - d);
break; // zacienienie w kanionie
case e_tunnel:
fShade = (d * 0.20) + (1.0 - d);
break; // zacienienie w tunelu
}
switch (t1->eEnvironment)
{ // typ zmiany oświetlenia - zakładam, że
// pierwszy tor ma e_flat
case e_canyon:
fShade = d + (1.0 - d) * 0.65;
break; // zacienienie w kanionie
case e_tunnel:
fShade = d + (1.0 - d) * 0.20;
break; // zacienienie w tunelu
}
*/
}
}
}
}
bool TDynamicObject::UpdateForce(double dt)
{
if (!bEnabled)
return false;
if( dt > 0 ) {
// wywalenie WS zależy od ustawienia kierunku
physics->ComputeTotalForce( dt );
}
return true;
}
glm::dvec3 TDynamicObject::get_future_movement() const
{
return m_future_movement;
}
void TDynamicObject::move_set(double distance)
{
TDynamicObject *d = this;
while( d ) {
d->Move( distance * d->DirectionGet() );
d = d->Next(); // pozostałe też
}
d = Prev();
while( d ) {
d->Move( distance * d->DirectionGet() );
d = d->Prev(); // w drugą stronę też
}
}
bool TDynamicObject::FastUpdate(double dt)
{
if (dt == 0.0)
return true; // Ra: pauza
double dDOMoveLen;
if (!physics->PhysicActivation())
return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba
if (!bEnabled)
return false;
// NOTE: coordinate system swap
// TODO: replace with regular glm vectors
TLocation const l {
-vPosition.x,
vPosition.z,
vPosition.y };
TRotation const r {
0.0,
0.0,
modelRot.z };
// McZapkie: parametry powinny byc pobierane z toru
// ts.R=MyTrack->fRadius;
// ts.Len= std::max(physics->BDist(),physics->ADist());
// ts.dHtrack=Axle1.pPosition.y-Axle0.pPosition.y;
// ts.dHrail=((Axle1.GetRoll())+(Axle0.GetRoll()))*0.5f;
// tp.Width=MyTrack->fTrackWidth;
// McZapkie-250202
// tp.friction= MyTrack->fFriction;
// tp.CategoryFlag= MyTrack->iCategoryFlag&15;
// tp.DamageFlag=MyTrack->iDamageFlag;
// tp.QualityFlag=MyTrack->iQualityFlag;
dDOMoveLen = physics->FastComputeMovement(dt, ts, tp, l, r); // ,ts,tp,tmpTraction);
// Move(dDOMoveLen);
// ResetdMoveLen();
FastMove(dDOMoveLen);
if( physics->LoadStatus() ) {
LoadUpdate(); // zmiana modelu ładunku
}
update_exchange( dt );
return true; // Ra: chyba tak?
}
// calculates distance between event-starting axle and front of the vehicle
double
TDynamicObject::tracing_offset() const {
auto const axletoend{ ( GetLength() - fAxleDist ) * 0.5 };
return iAxleFirst ? axletoend : axletoend + iDirection * fAxleDist;
}
// TODO: compute and cache radius during vehicle initialization
double
TDynamicObject::radius() const {
glm::vec3 diagonal(
static_cast<float>( physics->Dim.L ),
static_cast<float>( physics->Dim.H ),
static_cast<float>( physics->Dim.W ) );
return glm::length( diagonal ) * 0.5f;
}
TTrackFollower const *TDynamicObject::coupled_axle( VehicleEnd const End ) const {
auto const &coupler { physics->Couplers[ End ] };
auto const *other { physics->Neighbours[ End ].vehicle };
if( other == nullptr
|| coupler.Connected != other->physics
|| false == coupler.CouplingFlag.HasAll( Coupling::coupler ) ) {
return nullptr;
}
return ( coupler.ConnectedEnd() == VehicleEnd::front ? &other->Axle0 : &other->Axle1 );
}
namespace {
// the axle ran onto the Switch from its points; the way the axle ahead of it took over the switch: its own way if it is
// on the switch, the one it remembers if it is past it
std::optional<int> path_ahead( TTrackFollower const &Ahead, TTrack const *Switch ) {
return ( Ahead.GetTrack() == Switch ? std::optional<int>{ Ahead.GetPath() } : Ahead.PathOf( Switch ) );
}
std::string switch_name( TTrack const *Switch ) {
return ( Switch != nullptr ? Switch->name() : std::string{ "(none)" } );
}
} // namespace
bool vehicle_dynamic::same_way( TTrackFollower const &One, TTrackFollower const &Other ) {
return One.GetTrack() == Other.GetTrack() && One.GetPath() == Other.GetPath();
}
void TDynamicObject::watch_fork_entries( double const Distance ) {
auto *const frontentry { Axle0.TakeFacingEntry() };
auto *const rearentry { Axle1.TakeFacingEntry() };
if( Distance == 0.0
|| ( frontentry == nullptr && rearentry == nullptr ) ) {
return;
}
// moving towards coupler 0 the front axle leads, and the vehicle coupled there is ahead of it
auto const forwards { Distance > 0.0 };
auto const &leading { forwards ? Axle0 : Axle1 };
auto const &trailing { forwards ? Axle1 : Axle0 };
auto *const leadingentry { forwards ? frontentry : rearentry };
auto *const trailingentry { forwards ? rearentry : frontentry };
if( trailingentry != nullptr ) {
auto const ahead { path_ahead( leading, trailingentry ) };
if( switch_fork::forked( trailing.GetPath(), ahead ) ) {
m_forkbogies = { trailingentry, false };
WriteLog(
"Switch \"" + switch_name( trailingentry ) + "\" thrown under " + physics->Name
+ ": running forked, its " + ( forwards ? "rear" : "front" ) + " bogie took way " + std::to_string( trailing.GetPath() )
+ ", the " + ( forwards ? "front" : "rear" ) + " one way " + std::to_string( *ahead ) );
}
}
if( leadingentry != nullptr ) {
auto const end { forwards ? VehicleEnd::front : VehicleEnd::rear };
if( auto const *other { coupled_axle( end ) }; other != nullptr ) {
auto const ahead { path_ahead( *other, leadingentry ) };
if( switch_fork::forked( leading.GetPath(), ahead ) ) {
m_forkends[ end ] = { leadingentry, false };
WriteLog(
"Switch \"" + switch_name( leadingentry ) + "\" thrown under " + physics->Name
+ ": running forked, it took way " + std::to_string( leading.GetPath() )
+ ", " + physics->Neighbours[ end ].vehicle->physics->Name + " coupled at its " + ( end == VehicleEnd::front ? "front" : "rear" )
+ " way " + std::to_string( *ahead ) );
}
}
}
}
void TDynamicObject::update_forks() {
if( m_forkbogies.Switch == nullptr
&& m_forkends[ VehicleEnd::front ].Switch == nullptr
&& m_forkends[ VehicleEnd::rear ].Switch == nullptr ) {
return;
}
auto const sideof = [ this ]( glm::dvec3 const &Vector ) {
return ( glm::dot( Vector, vLeft ) >= 0.0 ? 1 : -1 ); };
// the bogies on the two ways: the body between them turns them under it
if( m_forkbogies.Switch != nullptr ) {
if( vehicle_dynamic::same_way( Axle0, Axle1 ) ) {
m_forkbogies = {};
}
else if( false == m_forkbogies.told ) {
auto const front { switch_fork::turn( Axle0.vAngles.z, modelRot.z ) };
auto const rear { switch_fork::turn( Axle1.vAngles.z, modelRot.z ) };
// the tightest curve the vehicle is built for, by its definition
auto const tightest { physics->Rmin() > 0.0 ? physics->Rmin() : switch_fork::minimum_curve };
auto const state { switch_fork::bogies( front, rear, fAxleDist, tightest ) };
if( state.past() ) {
// the side the bogie turned farther heads to, along the way of the vehicle
auto const frontfarther { std::abs( front ) >= std::abs( rear ) };
auto const heading { frontfarther ? Axle0.vAngles.z : Axle1.vAngles.z };
glm::dvec3 track { -std::sin( heading ), 0.0, std::cos( heading ) };
if( glm::dot( track, vFront ) < 0.0 ) {
track = -track;
}
fork_past(
m_forkbogies, sideof( track ),
std::format(
"its bogies on the two ways of switch \"{}\": the {} one turned {:.1f} deg under the body, more than the {:.1f} deg of bogies {:.1f} m apart"
" in a {:.0f} m curve (the other bogie {:.2f} m off the line of its track), at {:.0f} km/h",
switch_name( m_forkbogies.Switch ), frontfarther ? "front" : "rear",
glm::degrees( state.value ), glm::degrees( state.limit ), fAxleDist, tightest,
fAxleDist * std::sin( state.value ), physics->Vel ) );
}
}
}
// the coupled vehicles on the two ways: their ends part sideways
for( auto const end : VehicleEnds ) {
auto &watch { m_forkends[ end ] };
if( watch.Switch == nullptr ) {
continue;
}
auto const *otheraxle { coupled_axle( end ) };
auto const &ownaxle { end == VehicleEnd::front ? Axle0 : Axle1 };
if( otheraxle == nullptr
|| vehicle_dynamic::same_way( ownaxle, *otheraxle ) ) {
watch = {};
continue;
}
if( watch.told ) {
continue;
}
auto const *other { physics->Neighbours[ end ].vehicle };
auto const otherend { physics->Couplers[ end ].ConnectedEnd() };
auto const &own { vCoulpler[ end ] };
auto const &theirs { other->vCoulpler[ otherend ] };
auto const state { switch_fork::coupling( switch_fork::end_offset( own.x, own.z, modelRot.z, theirs.x, theirs.z, other->modelRot.z ) ) };
if( state.past() ) {
fork_past(
watch, sideof( own - theirs ),
std::format(
"it and {} coupled at its {} end on the two ways of switch \"{}\": the ends {:.2f} m apart sideways, more than the {:.2f} m of the buffer heads,"
" at {:.0f} km/h",
other->physics->Name, end == VehicleEnd::front ? "front" : "rear", switch_name( watch.Switch ), state.value, state.limit, physics->Vel ) );
}
}
}
void TDynamicObject::fork_past( fork_watch &Watch, int const Side, std::string const &Why ) {
if( physics->DamageFlag.HasAll( VehicleDamage::derailed )
|| false == TestFlag( physics->CategoryFlag, 1 )
|| DebugModeFlag ) {
return;
}
switch( Global.derailment ) {
case global_settings::derailment_model::physical: {
Watch.told = true;
physics->derail_forked( Side, Why );
break;
}
case global_settings::derailment_model::monitor: {
// the vehicle runs on forked, as it did before; the log tells what physics.derailment new does
Watch.told = true;
WriteLog( "derailment monitor: " + physics->Name + " derailed running forked, " + Why );
break;
}
default: {
// old, off: forked running as it is
break;
}
}
}