mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-12-03 10:05:23 +01:00
ed8708c5e2
* feat(simulation): text format of simulation snapshots
A snapshot of a running simulation is a text file in the syntax of the scenery
files: entries of the form <type> <name> <key> <value> ... end<type>, the first
one a header which names the scenery. This is the text alone: entries, writer,
reader, the names of the things of a scenery, the plan of coupling changes and
the command line switches (--load-snapshot, --snapshot-at), in the core library
with unit tests. Nothing reads or writes a snapshot yet.
* feat(simulation): snapshot of time, weather, cells, switches and events (L1)
--snapshot-at <seconds> <file> writes a snapshot when the simulation has run
that long, --load-snapshot <file> puts one over the scenery once it has loaded,
before the first frame. This layer keeps the clock and the simulation timer,
the weather with the wind, the random engine, the memory cells, the switches,
the tracks an event can change and the ones made on the run, the traction
power sources, the event queue, the timers of the launchers and the lamps of
the signals.
While a snapshot is put back the event manager is suspended, so nothing in the
scenery reacts to it. Existing classes only get accessors for what was private
(the fraction of the second, launcher timers, the speed limit of a track, the
wind, the state of a power source, the event queue). Without the switches
nothing changes.
* feat(simulation): state of a vehicle's physics for snapshots (L3, core)
What TMoverParameters holds of a running vehicle, to and from an entry of a
snapshot: speed, load, controls, switches and relays, pantographs, doors,
engine and its cooling, the air of the pipes, of every reservoir of the brake
valve (with the flow it has yet to take in) and of the chambers of the driver's
valves, the vigilance device, the power circuits. In the core library, tested
on the real vehicle definitions: a
vehicle restored on a fresh one saves the same, and runs on next to the one it
was saved from.
The brake valves, the driver's valves and the vigilance device get accessors
for their private state (reservoirs(), latches(), pressures(), state()), a
reservoir one for the flow it has yet to take in; nothing else in the physics
changes. This comes before the vehicles of the scenery (L2), whose
speed and load are kept by it.
* feat(simulation): snapshot of vehicles and consists (L2)
Every vehicle is kept with the place of both its axles (track, distance,
direction, path of a switch, events still to set off), the way it faces, its
couplings with their flags, destination and, through its physics, speed and
load. Loaded, the vehicles are put straight where they were
(TTrackFollower::Place(), which trails no switch and fires no event), then
parted and joined until they are coupled as saved, whatever trainsets the
scenery made of them.
A vehicle of the snapshot the scenery does not have is skipped and reported,
one the snapshot does not know stays as the scenery made it, one which had left
the simulation is taken out again.
* feat(simulation): pantographs and passenger exchange in snapshots (L3)
What a vehicle keeps of its machinery beside its physics: the arms of the
pantographs as they stand under the wire, the time without voltage, the
passengers getting on and off, the lighting of the compartments, the headlight
toggles, the last force asked of the electrodynamic brake.
* feat(simulation): snapshot of the drivers and of the player's vehicle (L4)
A driver is kept with its orders and the one it is on, the name of its
timetable and its place in it, the consist it has, what it holds to (speeds of
signals and limits, the reason it stands, its timers and flags), its table of
what is ahead on the track with the point limits it has latched, its tables of
what the brake of the consist gives, and whether the AI drives. A driver who
had moved to another vehicle of its train is moved there.
A run loaded in ghost view (the test mode) is ready before its first frame, as
the run it goes on from was.
The snapshot also names the vehicle the player was in, which --load-snapshot
starts in unless -v says otherwise.
* feat(simulation): snapshotsave command, on [Ctrl]+[Shift]+[F9]
Writes a snapshot of the simulation to snapshots/<scenery>_<date>_<time>.snapshot
in the game folder. The command is the last one of the list, so the numbers of
the others stay.
* test: scenario cases which load a simulation snapshot and compare the run
A case with a "snapshot" section runs its scenery to a time, taking snapshots
on the way and at the end, then again from the first snapshot, and compares the
two ends: positions, speeds, pressures, couplings, cells, switches, drivers.
The snapshot saved right after loading has to be the one loaded.
tests/scenarios/snapshots.py reads the format and tells two snapshots apart.
The switches and the format are described in tests/scenarios/README.md.
* fix(simulation): a vehicle gone in the snapshot leaves its isolated sections
The scenery counts the axles of every vehicle in the isolated sections of
the tracks it puts it on. A vehicle the snapshot has as removed was only
taken off the list of its track, so its two axles stayed counted there and
the section never went free again: the next train on it went 4-6-4 axles
instead of 0-2-0, and its busy and free events never fired.
- A removed vehicle counts both axles out of the sections of their tracks,
is taken off the list of its track only if it's on it, and has no owner.
- The drivers a snapshot doesn't have are deleted as before, and no
vehicle keeps its owner pointing at one of them.
- The snapshot keeps the count of every isolated section and sets it after
the vehicles are placed: the vehicles a consist leaves behind as it goes
through a portal stay counted where they were, in the game too. A count
the placing gives other than the snapshot has is told in the log.
- A vehicle with two entries is placed once.
- TIsolated::axles() reads and sets the count.
- The harness compares the counts of the sections; a new case,
snapshot_td_portal_isolated, has a train leave through a portal from the
track of a section before the snapshot.
* fix(simulation): every value of a snapshot file is checked before it's used
A damaged or edited snapshot could put an index past a table, a count
which takes forever or a number out of the range of its type into the
simulation, and a file cut short was put back half way.
- Reading a value: a whole number has to be whole and fit its type (an
enum its underlying one), a float can't be past its largest value; what
doesn't fit is refused. Every refusal names the entry, the key and the
value, and goes to the log (errors.txt), up to 100 lines and a count.
- Ranges: coupler ends 0 or 1 and the flags of a coupling; couplings which
would close a ring of vehicles; the count of the points of a driver's
table and of its point limits (not past the keys of the entry), the
indices into the table (tablelast, semnext, semnextstop); the order
stack and its position, the timetable station, the driver's enums and
directions; the path, events and distance of an axle, facing and first
axle; the date and time; switch states, made track ends, crossing
segments, event siblings and times, launcher timers, the weather; the
load (amount, and a name which isn't a path); the whole numbers inside
number lists (flags of a table point, the stop of a coupler pair, the
track flags under a vehicle, the fuse count of a power source, the cab
of the vigilance device).
- The positions of the controllers are brought within the ranges of the
vehicle: master and secondary controller (set and actual), reverser,
cabs, light, compressor and wiper switches, brake handle, hand brake,
dimmer.
- A document with problems isn't loaded unless --load-snapshot-force says
so; a test run ends with the error code then. The header counts the
entries, so a file cut between two entries is found too. A file of a
newer version is a warning, not a problem.
- A snapshot is written to <file>.tmp and renamed over the file only when
the stream didn't fail.
- Unit tests of the reader on damaged input.
* feat(simulation): the pullee mode and the holding brake timer in snapshots
Of what #419 and #424 added to TMoverParameters, two are state: PulleeMode
(prepared for being hauled dead; the scenery sets it, PulleeModeSwitch()
can change it) and StopBrakeReleaseTimer (how long power has been asked
for, which lets the holding brake of a unit go after its delay). Both are
kept now, as "pulleemode" and "stopbrakereleasetimer". The others
(PressureSwitchBrakeCylinder, EmergencyBrakeMainOffPressure,
StopBrakeReleaseDelay) come from the vehicle definition and aren't.
* fix(simulation): the snapshot code without Sonar issues
No declaration shadows an enumerator, the variables used only by a
condition are declared in it, write_file takes its writer as a template,
the temporary file is a std::filesystem::path, the isolated sections are
looked up by a transparent hash, apply_couplings is split into helpers,
and the copies of the simulation's random engine are marked NOSONAR.
The test data has no http:// in it. No snapshot key or format changes.
* fix(brakes): TSt113 lists the control pressure once
TSt113::pressures() added CP on top of TH14K1::pressures(), which
already has it since #366 removed the CP of TSt113 that hid it. A
snapshot held the St113's control chamber twice. The second entry is
removed.
Tests: every driver's handle lists each pressure once, and the St113
pressures of an EN57 saved through a snapshot come back on a fresh one.
* fix(simulation): snapshots skip road traffic, refuse changed sceneries, keep misplaced vehicles apart
Cars of the road spawn points which a snapshot has on the road are no longer put back: the spawn point owns
them and the snapshot would leave them frozen on the track. They're counted in the log. The pooled cars keep
their AI drivers, which the snapshot used to delete.
A snapshot whose scenery fingerprint differs is refused unless --load-snapshot-force is given: tracks named
"#N" shift when a track is added. Each vehicle is checked against the x/y/z of its entry after placing. One
more than 1 m off, or one which can't be placed, goes back where the scenery put it, isn't coupled to the
placed vehicles, and keeps its scenery state and driver.
Couplings set from a snapshot keep to CompatibleCoupling, so no MU control between an electric and a diesel
loco (#520).
The snapshotsave key writes to snapshotsdir of eu07.ini (snapshots by default, ini only like screenshotsdir),
adds _2, _3... to a name that is taken, and shows where the file went.
* refactor(simulation): the snapshot reads and writes the private state of the vehicles through their own members
Since #552 the state of physics::Vehicle and of its parts is private, and since #531 the vehicle, the AI
and the cab live in other files under other names. The snapshot code is ported to that:
- the state of a vehicle's physics is saved and loaded by physics::Vehicle::SnapshotSave() and
SnapshotLoad() (physics/components/snapshot.cpp), with the tables of the variables in a nested
snapshot_members; capture_mover() and apply_mover() only hand it the entry. The parts with private
state (low voltage, line breaker, line contactors, protective relays, converter, air of the
pantographs, compressor, air supply) give a plain Snapshot of it and take it back
(TakeSnapshot(), RestoreSnapshot()); the rest goes through their queries and setters
- the keys, their order and the numbers in them are unchanged, so the snapshots written before load:
the fields that moved into the parts are mapped there (Mains to lineBreaker, PipePress to brakePipe,
BrakeCtrlPos to brakes, dizel_* to diesel, hydro_* to torqueConverter and retarder, eimv to
inductionMotor.state in the order of the old table, EngDmgFlag to equipmentFaults, ...)
- TDynamicObject: the machinery of a vehicle (sections, rail joints, the passenger exchange) is saved
by members of its own, as these are private now; MED_oldFED is the last ED demand of the consist's
brake blending (ConsistBrakeBlending::LastElectrodynamicDemand())
- TController: the driving flags are saved as the bits of iDrivigFlags they were, the running brake
test as the number of its stage, the uphill start and the braking shortfall from their structs;
StaticBrakeTest, which is gone, is written as 0 and not read
- the couplings take Coupling, CouplingSet and VehicleEnd; orders are DriverOrders
- the unit tests of the snapshot of a vehicle use the queries and the parts
* fix(simulation): carry the driver's coupling set in the snapshot as the bits of the set
iCoupler is a CouplingSet since 2098614f, which record::set()/get() can't take. It goes
through the converted values as a whole number, as the driving flags do: Bits() on save,
CouplingSet::FromBits() on load. The key and its values are the same as before.
* fix(simulation): a loaded snapshot counts the vehicles it left where they stand
apply_isolated() set every isolated section to the count of the snapshot, also where a
vehicle the load left at its scenery place (misplaced, forced load, road traffic not put
back) stands, or where the snapshot had it. The axles of those vehicles are now counted in
the sections they stand in and out of the ones the snapshot has them in, and the memory
cells of those sections say whether they are taken by that count.
An AI consist doesn't end on a vehicle the load left: the ends are then found along what is
coupled now, as CheckVehicles() finds them.
The player entry no longer writes the cab, which nothing read: the cab is the one the
vehicle has occupied (caboccupied of its entry).
* feat(simulation): the snapshot keeps a derailment and the brakes of a sleeping vehicle
A derailed vehicle came back on the rails. Its entry now keeps what derailed it (outcome,
cause, speed, the cause and side of the motion off the track, the acceleration, the
collision derailment) and the distance its criteria were last checked over; the
derailment the scenery and the test mode were told of (new_derailment()), so it isn't told
again; and with physics.derailment new the motion of the body off the track
(derail_motion::body::state()) with the timers of the vehicle off the track. The terrain
under it is gathered anew around it when it loads.
sleep_brakes, what a sleeping vehicle's brake force came from, is kept too.
All keys are new: an entry without them leaves the vehicle as the scenery made it, so files
written before still load. New scenario case snapshot_td_off_track.
* fix(simulation): the snapshot keeps the sanded start of an AI driver
#494 (in staging since the last runs of the snapshot cases) made a driver whose start
slipped keep sanding under power until the train is under way, and take the power down a
step at a time. Neither the flag nor the time of the last step down was kept, so on
linia61 the loaded run sanded one frame later than the run which went on and parted from
it 0.06 s after loading (suwnica2, 9 mm and 0.08 km/h at 600 s). Both are kept now
(sandedstart, sandedstarttime); an entry without them leaves the driver as it is.
* fix(simulation): the snapshot keeps a train running forked on a switch thrown under it
Staging's switch fork running (#496) gave the axles and the vehicles state of their own: the way of a
switch an axle ran onto (TTrackFollower::iPath, which it leaves the switch by after a throw), the ways it
remembers of the switches behind it (path_memory, read when the axle behind it comes onto one of them),
and per vehicle the switch its bogies or its coupled ends run forked on with whether that was told
(m_forkbogies, m_forkends). None of it was in a snapshot: a loaded train on a switch thrown under it
would have left it by the way it is set now and never derailed running forked.
- Place() sets the way of the switch from the path the axle is put on, as SetCurrentTrack() does, and
clears the facing entry the vehicle hasn't looked at (there is none between frames).
- A vehicle entry has the remembered ways of each axle, oldest first (axle0switch0, axle0way0...),
recorded again into an empty memory on load (path_memory::entries()), and the forked watches
(forkbogies, fork0, fork1 with their "told"). A name which isn't a switch is refused.
- New case snapshot_td_switch_thrown: the snapshot is taken while the second coach of
eu07_td_switch_thrown_facing_behind_derails runs forked and hasn't derailed yet; the loaded run derails
it the same way and the two files at 150 s are identical.
493 lines
23 KiB
C++
493 lines
23 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 and others
|
|
|
|
*/
|
|
|
|
#include "stdafx.h"
|
|
#include "world/TrkFoll.h"
|
|
|
|
#include "simulation/simulation.h"
|
|
#include "utilities/Globals.h"
|
|
#include "vehicle/DynObj.h"
|
|
#include "vehicle/Driver.h"
|
|
#include "utilities/Logs.h"
|
|
#include "physics/vehicle.h"
|
|
|
|
namespace {
|
|
|
|
// how far the start of a way across a crossroads can be from the end of the path an axle leaves, to be where the axle gets on
|
|
constexpr double cross_reach { 1.0 };
|
|
|
|
// number of the ways across a crossroads; each can be taken either way
|
|
int cross_count( TTrack const &Cross ) {
|
|
|
|
return Cross.SwitchExtension->iRoads == 4 ? 6 : 3;
|
|
}
|
|
|
|
// where the way of specified code starts, and the direction it leads in there. the code is the number of the way, 1..6,
|
|
// negative if the way is taken against its points
|
|
bool cross_start( TTrack const &Cross, int const Code, glm::dvec3 &Point, glm::dvec3 &Direction ) {
|
|
|
|
if( Code == 0 || std::abs( Code ) > cross_count( Cross ) ) { return false; }
|
|
auto const &segment { Cross.SwitchExtension->Segments[ std::abs( Code ) - 1 ] };
|
|
if( segment == nullptr ) { return false; }
|
|
Point = ( Code > 0 ? segment->FastGetPoint_0() : segment->FastGetPoint_1() );
|
|
Direction = ( Code > 0 ? segment->FastGetPoint( 0.05 ) : segment->FastGetPoint( 0.95 ) ) - Point;
|
|
return true;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
TTrackFollower::~TTrackFollower()
|
|
{
|
|
}
|
|
|
|
bool TTrackFollower::Init(TTrack *pTrack, TDynamicObject *NewOwner, double fDir)
|
|
{
|
|
fDirection = fDir;
|
|
Owner = NewOwner;
|
|
// the axle is put on the track, it doesn't come from the one it was on before
|
|
pCurrentSegment = nullptr;
|
|
SetCurrentTrack(pTrack, 0);
|
|
iEventFlag = 3; // na torze startowym również wykonać eventy 1/2
|
|
iEventallFlag = 3;
|
|
if (pCurrentSegment) // && (pCurrentSegment->GetLength()<fFirstDistance))
|
|
return false;
|
|
return true;
|
|
}
|
|
|
|
void TTrackFollower::Reset()
|
|
{
|
|
fCurrentDistance = 0.0;
|
|
fDirection = 1.0;
|
|
}
|
|
|
|
TTrack *TTrackFollower::TakeFacingEntry()
|
|
{
|
|
auto *const entry { m_facingentry };
|
|
m_facingentry = nullptr;
|
|
return entry;
|
|
}
|
|
|
|
int TTrackFollower::LeavingPath() const
|
|
{
|
|
if( pCurrentTrack == nullptr || pCurrentTrack->eType != tt_Switch || pCurrentTrack->SwitchExtension == nullptr ) {
|
|
return -1;
|
|
}
|
|
return switch_fork::leaving_path( iPath, pCurrentTrack->SwitchExtension->CurrentIndex );
|
|
}
|
|
|
|
int TTrackFollower::JoinedEnd(int const End) const
|
|
{
|
|
// the axle is on a track here (SetCurrentTrack() leaves it)
|
|
auto const &track { *pCurrentTrack };
|
|
if( track.eType == tt_Switch && track.SwitchExtension != nullptr ) {
|
|
if( auto const path { switch_fork::leaving_path( iPath, track.SwitchExtension->CurrentIndex ) }; path >= 0 ) {
|
|
// the switch was thrown under the axle: the end of its own way is joined to the next track
|
|
return End ? track.SwitchExtension->iNextDirection[ path ] : track.SwitchExtension->iPrevDirection[ path ];
|
|
}
|
|
}
|
|
return End ? track.iNextDirection : track.iPrevDirection;
|
|
}
|
|
|
|
TTrack * TTrackFollower::SetCurrentTrack(TTrack *pTrack, int end)
|
|
{ // przejechanie na inny odcinkek toru, z ewentualnym rozpruciem
|
|
auto facing { false }; // onto a switch from its points
|
|
if (pTrack)
|
|
switch (pTrack->eType)
|
|
{
|
|
case tt_Switch: // jeśli zwrotnica, to przekładamy ją, aby uzyskać dobry segment
|
|
{
|
|
if( pCurrentTrack == nullptr ) {
|
|
break;
|
|
}
|
|
int i = JoinedEnd( end );
|
|
if (i > 0) // jeżeli wjazd z ostrza
|
|
pTrack->SwitchForced(i >> 1, Owner); // to przełożenie zwrotnicy - rozprucie!
|
|
else
|
|
facing = true; // from the points: the way the switch is set to
|
|
}
|
|
break;
|
|
case tt_Cross: // skrzyżowanie trzeba tymczasowo przełączyć, aby wjechać na właściwy tor
|
|
{
|
|
iSegment = Owner->RouteWish(pTrack); // nr segmentu został ustalony podczas skanowania
|
|
// Ra 2014-08: aby ustalić dalszą trasę, należy zapytać AI - trasa jest ustalana podczas
|
|
// skanowania
|
|
// Ra 15-01: zapytanie AI nie wybiera segmentu - kolejny skanujący może przestawić
|
|
// pTrack->CrossSegment(end?pCurrentTrack->iNextDirection:pCurrentTrack->iPrevDirection,i);
|
|
// //ustawienie właściwego wskaźnika
|
|
// powinno zwracać kierunek do zapamiętania, bo segmenty mogą mieć różny kierunek
|
|
// if fDirection=(iSegment>0)?1.0:-1.0; //kierunek na tym segmencie jest ustalany
|
|
// bezpośrednio
|
|
if (iSegment == 0)
|
|
{ // to jest błędna sytuacja - generuje pętle zawracające za skrzyżowaniem - ustalić,
|
|
// kiedy powstaje!
|
|
iSegment = 1; // doraźna poprawka
|
|
}
|
|
// the way has to start where the axle gets on. the one the driver picked may not: the driver may have looked
|
|
// again since the other axle got on, the vehicle may have no driver of its own, or it may be going backwards
|
|
iSegment = CrossEntry( *pTrack, iSegment, end );
|
|
if ((end ? iSegment : -iSegment) < 0)
|
|
fDirection = -fDirection; // wtórna zmiana
|
|
pTrack->SwitchForced(abs(iSegment) - 1, nullptr); // wybór zapamiętanego segmentu
|
|
}
|
|
break;
|
|
}
|
|
if (!pTrack) {
|
|
// gdy nie ma toru w kierunku jazdy tworzenie toru wykolejącego na przedłużeniu pCurrentTrack
|
|
pTrack = pCurrentTrack->NullCreate(end);
|
|
if (!end) // jeśli dodana od strony zero, to zmiana kierunku
|
|
fDirection = -fDirection; // wtórna zmiana
|
|
}
|
|
else
|
|
{ // najpierw +1, później -1, aby odcinek izolowany wspólny dla tych torów nie wykrył zera
|
|
pTrack->AxleCounter(+1, Owner); // zajęcie nowego toru
|
|
if (pCurrentTrack)
|
|
pCurrentTrack->AxleCounter(-1, Owner); // opuszczenie tamtego toru
|
|
}
|
|
pCurrentTrack = pTrack;
|
|
pCurrentSegment = pCurrentTrack != nullptr ? pCurrentTrack->CurrentSegment() : nullptr;
|
|
// on a switch the axle keeps to the way it ran onto: a throw under it doesn't move it to the other one
|
|
iPath = -1;
|
|
if( pCurrentTrack != nullptr && pCurrentTrack->eType == tt_Switch && pCurrentTrack->SwitchExtension != nullptr ) {
|
|
iPath = ( pCurrentTrack->SwitchExtension->CurrentIndex & 1 );
|
|
m_paths.record( pCurrentTrack, iPath );
|
|
if( facing ) {
|
|
m_facingentry = pCurrentTrack;
|
|
}
|
|
}
|
|
if (!pCurrentTrack)
|
|
Error(Owner->physics->Name + " at NULL track");
|
|
return pCurrentTrack;
|
|
};
|
|
|
|
// picks the way across the crossroads (Cross) for the axle which gets on it by specified end of the path it's on. it's the way
|
|
// taken by another axle of the vehicle, or of a vehicle coupled to it, which is on the crossroads already; or the one the driver
|
|
// picked (Wish); or, if neither starts where the axle gets on, the one leading the most straight on of the ways which start there
|
|
int TTrackFollower::CrossEntry( TTrack const &Cross, int const Wish, int const End ) const {
|
|
|
|
if( pCurrentSegment == nullptr || Cross.SwitchExtension == nullptr ) { return Wish; }
|
|
|
|
auto const joint { End ? pCurrentSegment->FastGetPoint_1() : pCurrentSegment->FastGetPoint_0() };
|
|
auto const starts_here = [&]( int const Code ) {
|
|
glm::dvec3 point, direction;
|
|
return cross_start( Cross, Code, point, direction ) && glm::distance( point, joint ) < cross_reach; };
|
|
|
|
if( Owner != nullptr ) {
|
|
for( auto const *vehicle : { Owner, Owner->Prev(), Owner->Next() } ) {
|
|
if( vehicle == nullptr ) { continue; }
|
|
for( auto const *axle : { &vehicle->Axle0, &vehicle->Axle1 } ) {
|
|
if( axle == this || axle->pCurrentTrack != &Cross || axle->iSegment == 0 ) { continue; }
|
|
if( starts_here( axle->iSegment ) ) { return axle->iSegment; }
|
|
// a vehicle going back over the crossroads gets on the way at its other end
|
|
if( starts_here( -axle->iSegment ) ) { return -axle->iSegment; }
|
|
}
|
|
}
|
|
}
|
|
if( starts_here( Wish ) ) { return Wish; }
|
|
|
|
auto const incoming { joint - ( End ? pCurrentSegment->FastGetPoint( 0.95 ) : pCurrentSegment->FastGetPoint( 0.05 ) ) };
|
|
auto nearest { cross_reach };
|
|
for( int way = 1; way <= cross_count( Cross ); ++way ) {
|
|
for( auto const code : { way, -way } ) {
|
|
glm::dvec3 point, direction;
|
|
if( cross_start( Cross, code, point, direction ) ) {
|
|
nearest = std::min( nearest, glm::distance( point, joint ) );
|
|
}
|
|
}
|
|
}
|
|
if( nearest >= cross_reach ) {
|
|
// no way starts there, the crossroads isn't joined with the path; it's left the way it was
|
|
return Wish;
|
|
}
|
|
auto result { Wish };
|
|
auto straightest { -2.0 };
|
|
for( int way = 1; way <= cross_count( Cross ); ++way ) {
|
|
for( auto const code : { way, -way } ) {
|
|
glm::dvec3 point, direction;
|
|
if( false == cross_start( Cross, code, point, direction )
|
|
|| glm::distance( point, joint ) > nearest + 0.05 ) {
|
|
continue;
|
|
}
|
|
auto const straight {
|
|
glm::length2( incoming ) > 0.0 && glm::length2( direction ) > 0.0 ?
|
|
glm::dot( glm::normalize( incoming ), glm::normalize( direction ) ) :
|
|
-1.0 };
|
|
if( straight > straightest ) {
|
|
straightest = straight;
|
|
result = code;
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
bool TTrackFollower::Move(double fDistance, bool bPrimary)
|
|
{ // przesuwanie wózka po torach o odległość (fDistance), z wyzwoleniem eventów
|
|
// bPrimary=true - jest pierwszą osią w pojeździe, czyli generuje eventy i przepisuje pojazd
|
|
// Ra: zwraca false, jeśli pojazd ma być usunięty
|
|
auto const ismoving { /* ( std::abs( fDistance ) > 0.01 ) && */ ( Owner->GetVelocity() > 0.01 ) };
|
|
fDistance *= fDirection; // dystans mnożnony przez kierunek
|
|
double s; // roboczy dystans
|
|
double dir; // zapamiętany kierunek do sprawdzenia, czy się zmienił
|
|
bool bCanSkip; // czy przemieścić pojazd na inny tor
|
|
while (true) // pętla wychodzi, gdy przesunięcie wyjdzie zerowe
|
|
{ // pętla przesuwająca wózek przez kolejne tory, aż do trafienia w jakiś
|
|
if( pCurrentTrack == nullptr ) { return false; } // nie ma toru, to nie ma przesuwania
|
|
// TODO: refactor following block as track method
|
|
if( pCurrentTrack->m_events ) { // sumaryczna informacja o eventach
|
|
// omijamy cały ten blok, gdy tor nie ma on żadnych eventów (większość nie ma)
|
|
int const eventfilter { (
|
|
false == ismoving ? 0 : // only moving vehicles activate events type 1/2
|
|
false == bPrimary ? 0 : // only primary axle activates events type 1/2
|
|
Owner->ctOwner == nullptr ?
|
|
( fDistance > 0 ? 1 : -1 ) : // loose vehicle has no means to determine 'intended' direction so the filter does effectively nothing in such case
|
|
( fDirection > 0 ? 1 : -1 ) * Owner->ctOwner->Direction() * ( Owner->ctOwner->Vehicle()->DirectionGet() == Owner->DirectionGet() ? 1 : -1 ) ) };
|
|
|
|
if( false == ismoving ) {
|
|
//McZapkie-140602: wyzwalanie zdarzenia gdy pojazd stoi
|
|
if( Owner->Mechanik != nullptr
|
|
&& Owner->Mechanik->primary() ) {
|
|
// tylko dla jednego członu
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events0, Owner );
|
|
}
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events0all, Owner );
|
|
}
|
|
else if( fDistance < 0 && eventfilter < 0 ) {
|
|
// event1, eventall1
|
|
if( SetFlag( iEventFlag, -1 ) ) {
|
|
// zawsze zeruje flagę sprawdzenia, jak mechanik dosiądzie, to się nie wykona
|
|
if( Owner->Mechanik != nullptr
|
|
&& Owner->Mechanik->primary() ) {
|
|
// tylko dla jednego członu
|
|
// McZapkie-280503: wyzwalanie event tylko dla pojazdow z obsada
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events1, Owner );
|
|
}
|
|
}
|
|
if( SetFlag( iEventallFlag, -1 ) ) {
|
|
// McZapkie-280503: wyzwalanie eventall dla wszystkich pojazdow
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events1all, Owner );
|
|
}
|
|
}
|
|
else if( fDistance > 0 && eventfilter > 0 ) {
|
|
// event2, eventall2
|
|
if( SetFlag( iEventFlag, -2 ) ) {
|
|
// zawsze ustawia flagę sprawdzenia, jak mechanik dosiądzie, to się nie wykona
|
|
if( Owner->Mechanik != nullptr
|
|
&& Owner->Mechanik->primary() ) {
|
|
// tylko dla jednego członu
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events2, Owner );
|
|
}
|
|
}
|
|
if( SetFlag( iEventallFlag, -2 ) ) {
|
|
// sprawdza i zeruje na przyszłość, true jeśli zmieni z 2 na 0
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events2all, Owner );
|
|
}
|
|
}
|
|
}
|
|
if (!pCurrentSegment) // jeżeli nie ma powiązanego segmentu toru?
|
|
return false;
|
|
// if (fDistance==0.0) return true; //Ra: jak stoi, to chyba dalej nie ma co kombinować?
|
|
s = fCurrentDistance + fDistance; // doliczenie przesunięcia
|
|
// Ra: W Point2 toru może znajdować się "dziura", która zamieni energię kinetyczną
|
|
// ruchu wzdłużnego na energię potencjalną, zamieniającą się potem na energię
|
|
// sprężystości na amortyzatorach. Należałoby we wpisie toru umieścić współczynnik
|
|
// podziału energii kinetycznej.
|
|
// Współczynnik normalnie 1, z dziurą np. 0.99, a -1 będzie oznaczało 100% odbicia (kozioł).
|
|
// Albo w postaci kąta: normalnie 0°, a 180° oznacza 100% odbicia (cosinus powyższego).
|
|
/*
|
|
if (pCurrentTrack->eType==tt_Cross)
|
|
{//zjazdu ze skrzyżowania nie da się określić przez (iPrevDirection) i (iNextDirection)
|
|
//int segment=Owner->RouteWish(pCurrentTrack); //numer segmentu dla skrzyżowań
|
|
//pCurrentTrack->SwitchForced(abs(segment)-1,NULL); //tymczasowo ustawienie tego segmentu
|
|
//pCurrentSegment=pCurrentTrack->CurrentSegment(); //odświeżyć sobie wskaźnik segmentu
|
|
(?)
|
|
}
|
|
*/
|
|
if (s < 0)
|
|
{ // jeśli przekroczenie toru od strony Point1
|
|
bCanSkip = bPrimary && pCurrentTrack->CheckDynamicObject(Owner);
|
|
if( bCanSkip ) {
|
|
// tylko główna oś przenosi pojazd do innego toru
|
|
// zdejmujemy pojazd z dotychczasowego toru
|
|
Owner->MyTrack->RemoveDynamicObject( Owner );
|
|
}
|
|
dir = fDirection;
|
|
if (pCurrentTrack->eType == tt_Cross)
|
|
{
|
|
if (!SetCurrentTrack(pCurrentTrack->Connected(iSegment, fDirection), 0))
|
|
return false; // wyjście z błędem
|
|
}
|
|
else if (!SetCurrentTrack(pCurrentTrack->Connected(-1, fDirection, LeavingPath()), 0)) // ustawia fDirection
|
|
return false; // wyjście z błędem
|
|
if (dir == fDirection) //(pCurrentTrack->iPrevDirection)
|
|
{ // gdy kierunek bez zmiany (Point1->Point2)
|
|
fCurrentDistance = pCurrentSegment->GetLength();
|
|
fDistance = s;
|
|
}
|
|
else
|
|
{ // gdy zmiana kierunku toru (Point1->Point1)
|
|
fCurrentDistance = 0;
|
|
fDistance = -s;
|
|
}
|
|
if (bCanSkip)
|
|
{ // jak główna oś, to dodanie pojazdu do nowego toru
|
|
pCurrentTrack->AddDynamicObject(Owner);
|
|
iEventFlag = 3; // McZapkie-020602: umozliwienie uruchamiania event1,2 po zmianie toru
|
|
iEventallFlag = 3; // McZapkie-280503: jw, dla eventall1,2
|
|
if (!Owner->MyTrack)
|
|
return false;
|
|
}
|
|
continue;
|
|
}
|
|
else if (s > pCurrentSegment->GetLength())
|
|
{ // jeśli przekroczenie toru od strony Point2
|
|
bCanSkip = bPrimary && pCurrentTrack->CheckDynamicObject(Owner);
|
|
if (bCanSkip) // tylko główna oś przenosi pojazd do innego toru
|
|
Owner->MyTrack->RemoveDynamicObject(Owner); // zdejmujemy pojazd z dotychczasowego toru
|
|
fDistance = s - pCurrentSegment->GetLength();
|
|
dir = fDirection;
|
|
if (pCurrentTrack->eType == tt_Cross)
|
|
{
|
|
if (!SetCurrentTrack(pCurrentTrack->Connected(iSegment, fDirection), 1))
|
|
return false; // wyjście z błędem
|
|
}
|
|
else if (!SetCurrentTrack(pCurrentTrack->Connected(1, fDirection, LeavingPath()), 1)) // ustawia fDirection
|
|
return false; // wyjście z błędem
|
|
if (dir != fDirection) //(pCurrentTrack->iNextDirection)
|
|
{ // gdy zmiana kierunku toru (Point2->Point2)
|
|
fDistance = -fDistance; //(s-pCurrentSegment->GetLength());
|
|
fCurrentDistance = pCurrentSegment->GetLength();
|
|
}
|
|
else // gdy kierunek bez zmiany (Point2->Point1)
|
|
fCurrentDistance = 0;
|
|
if (bCanSkip)
|
|
{ // jak główna oś, to dodanie pojazdu do nowego toru
|
|
pCurrentTrack->AddDynamicObject(Owner);
|
|
iEventFlag = 3; // McZapkie-020602: umozliwienie uruchamiania event1,2 po zmianie toru
|
|
iEventallFlag = 3;
|
|
if (!Owner->MyTrack)
|
|
return false;
|
|
}
|
|
continue;
|
|
}
|
|
else
|
|
{ // gdy zostaje na tym samym torze (przesuwanie już nie zmienia toru)
|
|
if (bPrimary)
|
|
{ // tylko gdy początkowe ustawienie, dodajemy eventy stania do kolejki
|
|
if (Owner->physics->CabOccupied() != 0) {
|
|
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events1, Owner, -1.0 );
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events2, Owner, -1.0 );
|
|
}
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events1all, Owner, -1.0 );
|
|
pCurrentTrack->QueueEvents( pCurrentTrack->m_events2all, Owner, -1.0 );
|
|
}
|
|
fCurrentDistance = s;
|
|
return ComputatePosition(); // przeliczenie XYZ, true o ile nie wyjechał na NULL
|
|
}
|
|
}
|
|
};
|
|
|
|
int TTrackFollower::Path() const {
|
|
|
|
if( pCurrentTrack == nullptr || pCurrentTrack->SwitchExtension == nullptr ) { return 0; }
|
|
if( pCurrentTrack->eType == tt_Cross ) { return iSegment; }
|
|
if( pCurrentTrack->eType == tt_Switch ) { return pCurrentSegment == pCurrentTrack->SwitchExtension->Segments[ 1 ] ? 1 : 0; }
|
|
return 0;
|
|
}
|
|
|
|
bool TTrackFollower::Place( TTrack *Track, int const Path, double const Distance, double const Direction, int const Eventflags, int const Eventallflags ) {
|
|
|
|
if( Track == nullptr ) { return false; }
|
|
// the path of a switch the axle stands on may be other than the one the switch is set to, a crossing has several
|
|
auto segment { Track->CurrentSegment() };
|
|
auto crossingsegment { 0 };
|
|
if( Track->SwitchExtension != nullptr && ( Track->eType == tt_Switch || Track->eType == tt_Cross ) ) {
|
|
auto const index { Track->eType == tt_Switch ? ( Path & 1 ) : std::abs( Path ) - 1 };
|
|
if( index >= 0 && index < 6 && Track->SwitchExtension->Segments[ index ] != nullptr ) {
|
|
segment = Track->SwitchExtension->Segments[ index ];
|
|
crossingsegment = ( Track->eType == tt_Cross ? Path : 0 );
|
|
}
|
|
}
|
|
if( segment == nullptr ) { return false; }
|
|
|
|
if( Track != pCurrentTrack ) {
|
|
// najpierw +1, później -1, as in SetCurrentTrack()
|
|
Track->AxleCounter( +1, Owner );
|
|
if( pCurrentTrack != nullptr ) {
|
|
pCurrentTrack->AxleCounter( -1, Owner );
|
|
}
|
|
}
|
|
pCurrentTrack = Track;
|
|
pCurrentSegment = segment;
|
|
iSegment = crossingsegment;
|
|
// the way of a switch the axle keeps whichever way it's thrown, as SetCurrentTrack() sets it: the one it stands on.
|
|
// it ran onto no switch from its points that its vehicle has yet to look at
|
|
iPath = ( Track->eType == tt_Switch && Track->SwitchExtension != nullptr ?
|
|
( segment == Track->SwitchExtension->Segments[ 1 ] ? 1 : 0 ) :
|
|
-1 );
|
|
m_facingentry = nullptr;
|
|
fDirection = ( Direction < 0.0 ? -1.0 : 1.0 );
|
|
fCurrentDistance = std::clamp( Distance, 0.0, pCurrentSegment->GetLength() );
|
|
iEventFlag = Eventflags;
|
|
iEventallFlag = Eventallflags;
|
|
return ComputatePosition();
|
|
}
|
|
|
|
double TTrackFollower::RailPhase( double const Offset ) const {
|
|
|
|
return pCurrentTrack != nullptr ? pCurrentTrack->rail_phase( fCurrentDistance + fDirection * Offset ) : -1.0;
|
|
}
|
|
|
|
double TTrackFollower::BuckleCurvature( double const Base ) const {
|
|
|
|
return pCurrentTrack != nullptr ? pCurrentTrack->buckle_curvature( fCurrentDistance, Base ) : 0.0;
|
|
}
|
|
|
|
glm::dvec3 TTrackFollower::PathDirection( double const Reach ) const {
|
|
|
|
if( pCurrentSegment == nullptr ) {
|
|
return glm::dvec3 { 0.0 };
|
|
}
|
|
auto const length { pCurrentSegment->GetLength() };
|
|
glm::dvec3 ahead;
|
|
glm::dvec3 behind;
|
|
glm::vec3 rotation;
|
|
pCurrentSegment->RaPositionGet( std::clamp( fCurrentDistance + Reach, 0.0, length ), ahead, rotation );
|
|
pCurrentSegment->RaPositionGet( std::clamp( fCurrentDistance - Reach, 0.0, length ), behind, rotation );
|
|
glm::dvec3 const direction { ( ahead.x - behind.x ) * fDirection, 0.0, ( ahead.z - behind.z ) * fDirection };
|
|
auto const size { glm::length( direction ) };
|
|
return size > 1e-6 ? direction / size : glm::dvec3 { 0.0 };
|
|
}
|
|
|
|
bool TTrackFollower::ComputatePosition()
|
|
{ // ustalenie współrzędnych XYZ
|
|
if (pCurrentSegment) // o ile jest tor
|
|
{
|
|
pCurrentSegment->RaPositionGet(fCurrentDistance, pPosition, vAngles);
|
|
if (fDirection < 0) // kąty zależą jeszcze od zwrotu na torze
|
|
{ // kąty są w przedziale <-M_PI;M_PI>
|
|
vAngles.x = -vAngles.x; // przechyłka jest w przecinwą stronę
|
|
vAngles.y = -vAngles.y; // pochylenie jest w przecinwą stronę
|
|
vAngles.z +=
|
|
vAngles.z >= M_PI ? -M_PI : M_PI; // ale kierunek w planie jest obrócony o 180°
|
|
}
|
|
if (fOffsetH != 0.0)
|
|
{ // jeśli przesunięcie względem osi toru, to je doliczyć
|
|
}
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|