From da69df97b82730e91df99d5ac464bce15e43ffef Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 2 Dec 2026 11:03:00 +0100 Subject: [PATCH] feat(physics): flank collisions at switches, short of the fouling point Two vehicles on the rails beside each other at a switch, up to its fouling point, now meet by their bodies (physics.collisions new, the default; physics.collisions.flank no turns it off). Before, they passed through each other there, or, on the switch itself, the vehicle on the other way was taken for the one ahead and gave a phantom end-on hit. The neighbour search follows the ways of a switch: the way of the searcher's own axle, on the next switch the way joined to the track it comes from. A vehicle on the other way is skipped unless the two are in line end to end, their facing ends less than 2.2 m apart across so that a pair of buffers meets (flank::EndsMeet()). The flank contacts: the fouling zones of all rail switches are made once (the tracks along each way up to the fouling point, 3.50 m between the axes as found by fouling::find(), and 30 m past it); only a moving vehicle with an axle in a zone is checked against the vehicles on the other way of that switch. The footprints collide as for the vehicles off the track; the side of a body crushes at 250 kN, past 0.5 m and at an end at 2 MN, never more than stops the closing within the step. The force slows both along their rails and loads their wheels across: a vehicle with its end in the contact climbs at Nadal's limit held over the 2 m window of EN 14363, a body hit along its side only at three times the limit at once. It leaves the rails with the new derailment cause flank_collision (14). Pairs in line end to end stay with the collision of the ends. Tests: tests/unit/test_flank_contact.cpp (the neighbours on a 1:9 switch, the crush forces, Skierniewice 2023, a graze at 5 km/h, steps of 0.01 to 0.05 s); scenario cases eu07_td_switch_flank_foul, _foul_buffers and _clear on td.scn. The coach of eu07_td_crew_refused stood 0.6 m into the way of track 1 and is moved clear of the fouling point. --- CMakeLists.txt | 2 + blackbox_doc.md | 2 +- physics/components/collisions.cpp | 27 ++ physics/derailment.cpp | 1 + physics/derailment.h | 3 +- physics/vehicle.h | 4 + tests/scenarios/README.md | 15 + .../scenarios/cases/eu07_td_crew_refused.json | 4 +- .../cases/eu07_td_switch_flank_clear.json | 47 ++++ .../cases/eu07_td_switch_flank_foul.json | 47 ++++ .../eu07_td_switch_flank_foul_buffers.json | 47 ++++ tests/unit/test_derailment.cpp | 3 +- tests/unit/test_flank_contact.cpp | 260 ++++++++++++++++++ utilities/Globals.cpp | 7 + utilities/Globals.h | 3 + vehicle/DynObj.h | 25 +- vehicle/dynamic/consist.cpp | 24 +- vehicle/dynamic/flankzones.cpp | 207 ++++++++++++++ vehicle/dynamic/flankzones.h | 77 ++++++ vehicle/dynamic/neighbours.cpp | 31 ++- vehicle/dynamic/vehicletable.cpp | 230 ++++++++++++++++ vehicle/flankcontact.cpp | 181 ++++++++++++ vehicle/flankcontact.h | 128 +++++++++ 23 files changed, 1366 insertions(+), 9 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_switch_flank_clear.json create mode 100644 tests/scenarios/cases/eu07_td_switch_flank_foul.json create mode 100644 tests/scenarios/cases/eu07_td_switch_flank_foul_buffers.json create mode 100644 tests/unit/test_flank_contact.cpp create mode 100644 vehicle/dynamic/flankzones.cpp create mode 100644 vehicle/dynamic/flankzones.h create mode 100644 vehicle/flankcontact.cpp create mode 100644 vehicle/flankcontact.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 90b42cf1f..700662308 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -218,6 +218,7 @@ set(SOURCES "application/driverhints.cpp" "vehicle/dynamic/animations.cpp" "vehicle/dynamic/consist.cpp" +"vehicle/dynamic/flankzones.cpp" "vehicle/dynamic/couplers.cpp" "vehicle/dynamic/destinations.cpp" "vehicle/dynamic/lifecycle.cpp" @@ -828,6 +829,7 @@ set(CORE_SOURCES "physics/derailment.cpp" "physics/collision.cpp" "vehicle/derailmotion.cpp" +"vehicle/flankcontact.cpp" "world/TrackCheck.cpp" "world/SleeperPack.cpp" "world/switchfork.cpp" diff --git a/blackbox_doc.md b/blackbox_doc.md index c89823ee0..812bef66b 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -572,7 +572,7 @@ track: no offset, no roll, nothing travelled. | `f32` | roll [rad] of its body, to the left positive: about 1.57 on its side | | `f32` | distance [m] it went on the ground since it left the rails | | `u8` | 1 lying on its side, 0 upright | -| `u8` | what derailed it, finer: the code of the cause of the memory cell `__simulation.derailment` (tests/scenarios/README.md): 1 the flange climbed, 2 overturned, 3 the end of the track, 4 pulled off, 5 a collision (the legacy model), 6 a buckle, 7 overriding, 8 pushed off, 9 too fast in a curve (the legacy draw), 10 the gauge, 11 a track of another kind, 12 a trailed switch, 13 something else. In phases 0 and 1 too | +| `u8` | what derailed it, finer: the code of the cause of the memory cell `__simulation.derailment` (tests/scenarios/README.md): 1 the flange climbed, 2 overturned, 3 the end of the track, 4 pulled off, 5 a collision (the legacy model), 6 a buckle, 7 overriding, 8 pushed off, 9 too fast in a curve (the legacy draw), 10 the gauge, 11 a track of another kind, 12 a trailed switch, 13 something else, 14 a flank collision. In phases 0 and 1 too | | `str` | name of the track it derailed on, empty for a track without a name | The last two came later: a reader of an older file finds the record shorter. The finer cause is 0 when the diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 8204361d5..a7bff034a 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -928,6 +928,33 @@ bool physics::Vehicle::leaves_track() const false == OffTrack.active(); } +void physics::Vehicle::DerailFlank(int const Side, double const Acceleration, std::string const &Why) +{ + if (false == DamageFlag.Set(VehicleDamage::derailed)) + { + return; + } + // upright, the flange climbed the rail the push across took it over; physics.derailment new: off the track to that side + derailOutcome = derailment::outcome::off_rails; + derailCause = derail_motion::cause::pulled_off; + derailAcceleration = Acceleration; + derailSide = Side; + noteDerailment(derailment::reason::flank_collision); + eventFlag = true; + MainSwitch(false, range_t::local); + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrotValue = 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 flank collision, {}", Name, Why)); +} + void physics::Vehicle::pull_off(int const Side, double const Acceleration, std::string const &Why) { if (Global.derailment != global_settings::derailment_model::physical || false == DamageFlag.Set(VehicleDamage::derailed)) diff --git a/physics/derailment.cpp b/physics/derailment.cpp index 89ad5a0a3..31230551e 100644 --- a/physics/derailment.cpp +++ b/physics/derailment.cpp @@ -298,6 +298,7 @@ std::string_view reason_name(reason const Reason) { case reason::track_type: return "track_type"; case reason::trailed_switch: return "trailed_switch"; case reason::other: return "other"; + case reason::flank_collision: return "flank_collision"; } return "other"; } diff --git a/physics/derailment.h b/physics/derailment.h index f57a51fb5..6151c77f9 100644 --- a/physics/derailment.h +++ b/physics/derailment.h @@ -248,7 +248,8 @@ enum class reason : std::uint8_t { track_gauge = 10, // the gauge of the track doesn't fit the vehicle track_type = 11, // a track of another kind than the vehicle trailed_switch = 12, // it trailed through a switch with a movable nose set the other way - other = 13 // something else derailed it: a SetDamage command of a scenery + other = 13, // something else derailed it: a SetDamage command of a scenery + flank_collision = 14 // hit on the rails by the side or the corner of a vehicle on another track (physics.collisions new) }; // the name of the cause in the log and the memory cell, e.g. "end_of_track" std::string_view reason_name(reason Reason); diff --git a/physics/vehicle.h b/physics/vehicle.h index 95738ea54..6659b25d7 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -1206,6 +1206,10 @@ class Vehicle // physics.derailment new: a coupling of a vehicle off the track pulls this one off the rails sideways, to the Side // (1 the left of its front, -1 the right), with the lateral acceleration [m/s2] of the pull on it void pull_off(int Side, double Acceleration, std::string const &Why); + // physics.collisions new: hit on the rails by a vehicle on another track at a switch (vehicle/flankcontact.h), its + // wheels climbed the rail: it leaves the rails upright, with physics.derailment new sideways to the Side (1 the left of + // its front, -1 the right) with the lateral acceleration [m/s2] of the push, the reason told in the log + void DerailFlank(int Side, double Acceleration, std::string const &Why); // physics.collisions new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the // height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit collision::vehicle_kind collision_kind() const; diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index b60412e96..8c76d6c02 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -164,6 +164,7 @@ vehicle reads the cell of that vehicle, `:derailed`, not `__simulation. | 11 | `track_type` | a track of another kind (a road vehicle on rails, say) | | 12 | `trailed_switch` | it trailed through a switch with a movable nose set the other way | | 13 | `other` | something else set the derailment (a `SetDamage` command) | +| 14 | `flank_collision` | hit on the rails by the side or the corner of a vehicle on another track, at a switch or short of its fouling point (`physics.collisions new`) | The memory cell isn't made by the simulator because a node made at the start would take the random numbers of the scene and change every run of a scenery. `eu07_td_off_track_end_scenery_told` is an example. @@ -662,6 +663,20 @@ by the way the switch was set to then (the locomotive jumped 0.78 m off its trac split onto the two tracks with nothing in the log, and the AI traced its route through the switch as set (after the throw under the standing train through `tor1p`, track 1, while its head was on track 2). +The `eu07_td_switch_flank_*` cases (fragment `td_switch_thrown.scn` too) take two bdhpumn coaches standing on track 2 of +Stacja1 with their end towards `zwr01`, and the EU07 with three coaches running from the west line through `zwr01` set to +track 1 (`keyctrl02`) at about 25 km/h. Past the frog end of `zwr01` (z 370) the axes of the two tracks part by 0.114 m a +metre, from 1.93 m to the 3.50 m of the fouling point at z 384 (`physics.collisions new`, `physics.collisions.flank yes`): + +| case | where the end of the coaches stands | what happens | +|---|---|---| +| `eu07_td_switch_flank_foul_buffers` | z 368, 2 m short of the frog end: the ends 1.7 m apart across | a pair of buffers meets: the search on the switch keeps the two in line (`flank::EndsMeet()`), the collision of the ends takes them (collided at 24 km/h, both override); no flank contact | +| `eu07_td_switch_flank_foul` | z 375.5, 8 m short of the fouling point: the ends 2.55 m apart across, the bodies 0.4 m into each other | only the corners meet: `flank collision: ... hit ..._foul2 at 27 km/h, ..., corner to corner`, the coach struck derails (`flank_collision`), the first coach of the train sweeping past it too | +| `eu07_td_switch_flank_clear` | z 390, past the fouling point | the train passes, no flank contact; the zones are made (`flank contacts: the fouling zones of 2 switches`) | + +With `physics.collisions.flank no` the corner case gives a buffer crush of ends 2.55 m apart (both override), and the +bodies of the clear case are never looked at. + ### Cases on a mission of a scenery The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission diff --git a/tests/scenarios/cases/eu07_td_crew_refused.json b/tests/scenarios/cases/eu07_td_crew_refused.json index 4dc273e03..927103fe9 100644 --- a/tests/scenarios/cases/eu07_td_crew_refused.json +++ b/tests/scenarios/cases/eu07_td_crew_refused.json @@ -1,5 +1,5 @@ { - "description": "Crew events which must change nothing (eu07/maszyna#510): the run of eu07_td_timetable, with a coach standing on track 2, and crew events set off at the start and again at 10:36, on the run: a second driver for the locomotive (it has one), a driver for the coach (no cab), a cab which is none of 1, -1, 0, a driver taken off the coach (it has none) and a vehicle the scenery lacks. Each is refused in the log and the train runs its timetable to the stop at Przystanek.", + "description": "Crew events which must change nothing (eu07/maszyna#510): the run of eu07_td_timetable, with a coach standing on track 2 clear of the fouling point of zwr02 (its end at z 1384; with 30.0 m it stood 3 m from the frog end, 0.6 m into the way of track 1), and crew events set off at the start and again at 10:36, on the run: a second driver for the locomotive (it has one), a driver for the coach (no cab), a cab which is none of 1, -1, 0, a driver taken off the coach (it has none) and a vehicle the scenery lacks. Each is refused in the log and the train runs its timetable to the stop at Przystanek.", "base_scenery": "td.scn", "time": "10:34", "fragment": "td_crew.scn", @@ -8,7 +8,7 @@ "trainset td/rozklad tdo_n1734 0.0 0.1", "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", "endtrainset", - "trainset none tor2k 30.0 0.0", + "trainset none tor2k 45.0 0.0", "node -1 0 {{vehicle}}_coach dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", "endtrainset" ], diff --git a/tests/scenarios/cases/eu07_td_switch_flank_clear.json b/tests/scenarios/cases/eu07_td_switch_flank_clear.json new file mode 100644 index 000000000..146c38f26 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_flank_clear.json @@ -0,0 +1,47 @@ +{ + "description": "Flank collision at a switch, the control of eu07_td_switch_flank_foul (physics.collisions new): the two coaches stand on track 2 of Stacja1 on td.scn with the end of the last one at z 390, past the fouling point of zwr01 (where the axes of tracks 1 and 2 are 3.5 m apart, z 384). The EU07 with three coaches runs through zwr01 set to track 1 at about 25 km/h as there and passes them: no flank collision.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n25 75.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset", + "trainset none tor2p 73.5 0.0", + "node -1 0 {{vehicle}}_foul1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_foul2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl02 end", + "throw": "zwr01_1", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "tdo_n25": "event0 autotest_wake" + }, + "test_config": [ + "test.standstill 120" + ], + "duration": 150, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 15, + "within": 120 + }, + { + "type": "log_lacks", + "pattern": "flank collision: .* hit" + }, + { + "type": "log_contains", + "pattern": "flank contacts: the fouling zones of \\d+ switches" + } + ] +} \ No newline at end of file diff --git a/tests/scenarios/cases/eu07_td_switch_flank_foul.json b/tests/scenarios/cases/eu07_td_switch_flank_foul.json new file mode 100644 index 000000000..56acf7c58 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_flank_foul.json @@ -0,0 +1,47 @@ +{ + "description": "Flank collision at a switch (physics.collisions new): two coaches stand on track 2 of Stacja1 on td.scn with the end of the last one at z 375.5, 5.4 m past the frog end of zwr01 and 8 m short of its fouling point (z 384): there the axes of tracks 1 and 2 are 2.55 m apart, so the bodies overlap by some 0.4 m, but the ends are too far apart across for their buffers to meet. An EU07 with three coaches runs from the west line through zwr01 set to track 1 (keyctrl02) at about 25 km/h. The search along the track never finds the coaches (they are on the other way of the switch, and not in line with it); the corners have to meet: the log tells of a flank collision.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n25 75.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset", + "trainset none tor2p 59.0 0.0", + "node -1 0 {{vehicle}}_foul1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_foul2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl02 end", + "throw": "zwr01_1", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "tdo_n25": "event0 autotest_wake" + }, + "test_config": [ + "test.standstill 120" + ], + "duration": 150, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 15, + "within": 120 + }, + { + "type": "log_contains", + "pattern": "flank collision: .* hit .* at \\d+ km/h" + }, + { + "type": "log_lacks", + "pattern": "collided at|inside each other" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_flank_foul_buffers.json b/tests/scenarios/cases/eu07_td_switch_flank_foul_buffers.json new file mode 100644 index 000000000..b8440afb3 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_flank_foul_buffers.json @@ -0,0 +1,47 @@ +{ + "description": "Flank collision at a switch, ends in line (physics.collisions new): two coaches stand on track 2 of Stacja1 on td.scn with the end of the last one at z 368, 2 m short of the frog end of zwr01: there the axes of tracks 1 and 2 are some 1.7 m apart, so the end of the coach and the front of an EU07 running through zwr01 set to track 1 (keyctrl02) at about 25 km/h meet by a pair of their buffers. On the switch the search for the neighbours keeps them in line (flank::EndsMeet()): the collision of the ends takes them (collided, the ends crushed, overriding), not the flank contacts.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n25 75.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset", + "trainset none tor2p 51.5 0.0", + "node -1 0 {{vehicle}}_foul1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_foul2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl02 end", + "throw": "zwr01_1", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "tdo_n25": "event0 autotest_wake" + }, + "test_config": [ + "test.standstill 120" + ], + "duration": 150, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 15, + "within": 120 + }, + { + "type": "log_contains", + "pattern": "collided at \\d+ km/h" + }, + { + "type": "log_lacks", + "pattern": "flank collision: .* hit" + } + ] +} diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 9d68ffabd..cf6bf91f6 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -359,9 +359,10 @@ TEST_CASE("derailment: what the scenery and the test mode are told") { CHECK(static_cast(dr::reason::track_type) == 11); CHECK(static_cast(dr::reason::trailed_switch) == 12); CHECK(static_cast(dr::reason::other) == 13); + CHECK(static_cast(dr::reason::flank_collision) == 14); } SUBCASE("each cause has a name of one word") { - for (int code = 0; code <= 13; ++code) { + for (int code = 0; code <= 14; ++code) { auto const name{dr::reason_name(static_cast(code))}; CAPTURE(code); CHECK_FALSE(name.empty()); diff --git a/tests/unit/test_flank_contact.cpp b/tests/unit/test_flank_contact.cpp new file mode 100644 index 000000000..1e69fcf27 --- /dev/null +++ b/tests/unit/test_flank_contact.cpp @@ -0,0 +1,260 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle/flankcontact.h" +#include "vehicle/derailmotion.h" +#include "physics/derailment.h" + +#include +#include +#include +#include + +// two vehicles on the rails running into each other from the side at a switch, short of its fouling point (physics.collisions +// new): vehicle/flankcontact.h + +namespace dm = derail_motion; +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// to the left of the way along, level +glm::dvec3 leftOf(glm::dvec3 const &Front) { + return glm::dvec3{Front.z, 0.0, -Front.x}; +} + +// a vehicle on a straight track: where its middle is and the way it runs, its speed and how it brakes +struct runner { + glm::dvec3 start{0.0}; + glm::dvec3 way{0.0, 0.0, 1.0}; + double travelled{0.0}; // [m] along the way from the start + double speed{0.0}; // [m/s] + double braking{0.0}; // [m/s2], from the first contact on + double length{20.0}; + double width{2.9}; + double height{4.0}; + flank::Body body; + flank::Climb climb; + bool derailed{false}; + + glm::dvec3 position() const { return start + way * travelled; } + dm::footprint print() const { + dm::pose pose; + pose.position = position(); + pose.front = way; + pose.left = leftOf(way); + pose.up = glm::dvec3{0.0, 1.0, 0.0}; + return dm::footprint_of(pose, length, width, height); + } + flank::Body now() const { + auto result{body}; + result.print = print(); + result.guide = way; + result.speed = speed; + return result; + } +}; + +// the striking locomotive of Skierniewice: a unit of an ET41 (83.5 t, 12 t of it rotating), pushed on by its train of 1007 t +runner et41() { + runner result; + result.length = 15.93; + result.width = 2.9; + result.height = 4.34; + result.body.mass = 83.5e3 + 1007e3; + result.body.wheelMass = 83.5e3 - 12e3; + result.body.axles = 4; + result.body.pivots = 8.55; + return result; +} + +// a motor car of an EMU (57 t, 8 t of it rotating) in its train of some 125 t +runner emu() { + runner result; + result.length = 21.85; + result.width = 2.96; + result.height = 4.0; + result.body.mass = 125e3; + result.body.wheelMass = 57e3 - 8e3; + result.body.axles = 4; + result.body.pivots = 15.0; + return result; +} + +// a turnout of 1:9: the branch runs into the main track (along z, x 0) at the frog, z 0, from the left +glm::dvec3 const branch{glm::normalize(glm::dvec3{1.0, 0.0, 9.0})}; + +struct outcome { + bool contact{false}; + bool striker{false}; // derailed + bool struck{false}; + double depth{0.0}; // the most they overlapped by [m] + double where{0.0}; // [m] the striker travelled when it derailed + double ratio{0.0}; // the most Y / Q of the struck one +}; + +// the striker on the branch, its front Before [m] short of the frog, and the struck one on the main track passing it, both +// running towards z: stepped by Dt until 6 s, or the striker derails (from then on the motion off the track has them) +outcome run(runner Striker, runner Struck, double const Dt) { + outcome result; + auto braking{false}; + for (auto time{0.0}; time < 6.0 && false == result.striker; time += Dt) { + for (auto *vehicle : {&Striker, &Struck}) { + vehicle->travelled += vehicle->speed * Dt; + if (braking) { + vehicle->speed = std::max(0.0, vehicle->speed - vehicle->braking * Dt); + } + } + auto const hit{dm::collide(Striker.print(), Struck.print())}; + if (false == hit.has_value()) { + Striker.climb.Reset(); + Struck.climb.Reset(); + continue; + } + auto const striker{Striker.now()}; + auto const struck{Struck.now()}; + auto const response{flank::Respond(*hit, striker, struck, Dt)}; + if (response.force > 0.0) { + result.contact = true; + braking = true; + } + result.depth = std::max(result.depth, hit->depth); + result.ratio = std::max(result.ratio, response.second.ratio); + Striker.speed += response.first.along * Dt / striker.mass; + Struck.speed += response.second.along * Dt / struck.mass; + if (Striker.climb.Update(response.first, std::abs(Striker.speed) * Dt)) { + result.striker = true; + result.where = Striker.travelled; + } + result.struck = result.struck || Struck.climb.Update(response.second, std::abs(Struck.speed) * Dt); + } + return result; +} + +// Skierniewice: the striker at 25 km/h on the branch, its front 32 m short of the frog; the struck one at 53 km/h with its +// middle 43 m behind the frog, so that the corner of the striker meets it in its front half +outcome skierniewice(double const Dt) { + auto striker{et41()}; + striker.way = branch; + striker.start = -branch * (32.0 + 0.5 * striker.length); + striker.speed = 25.0 * kmh; + auto struck{emu()}; + struck.start = glm::dvec3{0.0, 0.0, -43.0}; + struck.speed = 53.0 * kmh; + return run(striker, struck, Dt); +} + +} // namespace + +TEST_CASE("flank contacts: on a switch the vehicles on its two ways beside each other aren't neighbours") { + // a turnout of 1:9 with a curve of 190 m: one vehicle on the straight way, the other on the curved one 15 m further on + auto const curved = [](double const Along) { + auto const angle{Along / 190.0}; + return std::pair{glm::dvec3{190.0 * (1.0 - std::cos(angle)), 0.0, 190.0 * std::sin(angle)}, glm::dvec3{std::sin(angle), 0.0, std::cos(angle)}}; + }; + flank::Placed straight{glm::dvec3{0.0, 0.0, 10.0}, glm::dvec3{0.0, 0.0, 1.0}, 20.0, 2.9}; + auto const [beside, besidefront]{curved(25.0)}; + flank::Placed other{beside, besidefront, 20.0, 2.9}; + SUBCASE("on the two ways side by side they pass each other") { + CHECK_FALSE(flank::EndsMeet(straight, other)); + CHECK(flank::PassesBy(0, 1, straight, other)); + CHECK(flank::PassesBy(1, 0, other, straight)); + } + SUBCASE("on the same way they are in line, one ahead of the other") { + CHECK_FALSE(flank::PassesBy(0, 0, straight, other)); + CHECK_FALSE(flank::PassesBy(1, 1, other, straight)); + } + SUBCASE("a way not known: as before, ahead") { + CHECK_FALSE(flank::PassesBy(-1, 1, straight, other)); + CHECK_FALSE(flank::PassesBy(0, -1, straight, other)); + } + SUBCASE("near the points the two ways run together: a vehicle on each, end to end, still meet by their ends") { + auto const [ahead, aheadfront]{curved(31.0)}; + flank::Placed next{ahead, aheadfront, 20.0, 2.9}; + CHECK(flank::EndsMeet(straight, next)); + CHECK_FALSE(flank::PassesBy(0, 1, straight, next)); + } + SUBCASE("ends 1.8 m apart across still meet by a pair of buffers, 2.5 m apart only by their corners") { + flank::Placed const buffers{glm::dvec3{1.8, 0.0, 30.5}, glm::dvec3{0.0, 0.0, 1.0}, 20.0, 2.9}; + flank::Placed const corners{glm::dvec3{2.5, 0.0, 30.5}, glm::dvec3{0.0, 0.0, -1.0}, 20.0, 2.9}; + CHECK(flank::EndsMeet(straight, buffers)); + CHECK(flank::EndsMeet(buffers, straight)); + CHECK_FALSE(flank::EndsMeet(straight, corners)); + CHECK_FALSE(flank::EndsMeet(corners, straight)); + } +} + +TEST_CASE("flank contacts: the side of a body gives way before its end does, and a graze pushes little") { + runner first{et41()}; + first.start = glm::dvec3{0.0}; + runner second{emu()}; + second.start = glm::dvec3{2.0, 0.0, 5.0}; + dm::contact hit; + hit.point = glm::dvec3{1.0, 0.0, 5.0}; + // across the second one: its side + hit.normal = glm::dvec3{1.0, 0.0, 0.0}; + hit.depth = 0.2; + CHECK(flank::CrushForce(hit, first.now(), second.now()) == doctest::Approx(flank::sideCrush)); + hit.depth = 0.02; + CHECK(flank::CrushForce(hit, first.now(), second.now()) == doctest::Approx(0.2 * flank::sideCrush)); + // past the side wall the floor takes more + hit.depth = 0.75; + CHECK(flank::CrushForce(hit, first.now(), second.now()) == doctest::Approx(0.5 * (flank::sideCrush + flank::endCrush))); + // along both: their ends + hit.normal = glm::dvec3{0.0, 0.0, 1.0}; + hit.depth = 0.2; + CHECK(flank::CrushForce(hit, first.now(), second.now()) == doctest::Approx(flank::endCrush)); + SUBCASE("two side by side on tracks too close together, neither closing in: no force") { + hit.normal = glm::dvec3{1.0, 0.0, 0.0}; + auto a{first.now()}; + auto b{second.now()}; + a.speed = 10.0; + b.speed = 20.0; + auto const response{flank::Respond(hit, a, b, 0.01)}; + CHECK(response.force == 0.0); + CHECK(response.first.ratio == 0.0); + } +} + +TEST_CASE("flank contacts: the corner that strikes derails, the train struck along its side stays on the rails (Skierniewice 2023)") { + auto const result{skierniewice(0.01)}; + MESSAGE(std::format("the striker derailed {:.2f} m on, the bodies overlapped by {:.2f} m, the struck one at Y/Q {:.2f} at most", result.where, result.depth, result.ratio)); + CHECK(result.contact); + CHECK(result.striker); + CHECK_FALSE(result.struck); + // at Nadal's limit held over the window, not at once, and before the side wall gave way to the floor + CHECK(result.ratio < 3.0 * dr::climbing_limit); + CHECK(result.depth < flank::sideDepth); +} + +TEST_CASE("flank contacts: a graze at 5 km/h, the driver braking, derails neither") { + auto striker{et41()}; + striker.way = branch; + striker.start = -branch * (32.0 + 0.5 * striker.length); + striker.speed = 5.0 * kmh; + striker.braking = 1.0; + auto struck{emu()}; + // standing foul with its middle at the corner of the striker as it comes + struck.start = glm::dvec3{0.0, 0.0, -29.0}; + auto const result{run(striker, struck, 0.01)}; + MESSAGE(std::format("overlapped by {:.2f} m, the struck one at Y/Q {:.2f} at most", result.depth, result.ratio)); + CHECK(result.contact); + CHECK_FALSE(result.striker); + CHECK_FALSE(result.struck); +} + +TEST_CASE("flank contacts: the same with a step of 0.01, 0.03 and 0.05 s") { + auto const reference{skierniewice(0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const result{skierniewice(dt)}; + CHECK(result.striker == reference.striker); + CHECK(result.struck == reference.struck); + // where it derails: within two steps of the striker (the step the contact is found in, the step the window is full + // in), and the overlap by as much as it closes in over them at 1:9 + auto const within{2.0 * 25.0 * kmh * dt + 0.05}; + CHECK(std::abs(result.where - reference.where) < within); + CHECK(std::abs(result.depth - reference.depth) < within / 9.0 + 0.01); + } +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 6f7749517..8bbbfecdd 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1092,6 +1092,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.collisions.flank") + { + ParseOne(Parser, collisions_flank, 1); + return true; + } + if (token == "physics.collisions") { // new: the crush of the ends past the buffers (physics/collision.h), old: the legacy rule, monitor: the legacy @@ -2602,6 +2608,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "physics.derailment.trustlimits", derailment_trust_limits ); export_as_text( Output, "physics.trackcheck", track_check ); export_as_text( Output, "physics.collisions", std::string{ name_of( collisions ) } ); + export_as_text( Output, "physics.collisions.flank", collisions_flank ); export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 34d79cf16..0e0196c56 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -394,6 +394,9 @@ struct global_settings { // (collision monitor:, once for a hit). the road vehicles of the traffic keep the legacy rule with any enum class collision_model { old, physical, monitor }; collision_model collisions = collision_model::physical; + // physics.collisions.flank: with physics.collisions new, the vehicles on the rails at a switch, short of its fouling point, + // meet by their sides (vehicle/flankcontact.h); no: they pass through each other there, as before + bool collisions_flank = true; // physics.trackcheck: the geometry of the rail tracks the criteria of derailment find suspicious, to the log once the // scenery loaded (trackcheck:, see world/TrackCheck.h) bool track_check = false; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index f63c3555a..a6cb6920c 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -666,7 +666,11 @@ private: std::string asModel; private: - TDynamicObject *ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine = false ) const; + // Path: on a switch, the way of it the search goes over (-1 not known, or not a switch): physics.collisions new, a vehicle + // on the other way beside this one isn't ahead of it (vehicle/flankcontact.h) + TDynamicObject *ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine = false, int const Path = -1 ) const; + // the way of the switch an axle of the vehicle is on, -1 off it or with its axles on both ways of it + int path_on( TTrack const *Switch ) const; void ABuCheckMyTrack(); // forked running (world/switchfork.h): a switch thrown under the train put two axles following each other on its // two ways. the vehicle whose axle came to the points after the throw keeps watch: of its two bogies, or of its end @@ -1038,6 +1042,9 @@ public: // physics.derailment new: the vehicle and the other one, one of them off the track, are in line, close enough // across to run into each other bool in_line_with( TDynamicObject const &Other ) const; + // physics.collisions new: on a switch the vehicle and the other one, on two ways of it, are beside each other, not + // one ahead of the other (vehicle/flankcontact.h, flank::PassesBy()) + bool passes_by( TDynamicObject const &Other, int const Path, int const OtherPath ) const; // locates potential collision source within specified range, scanning its route in specified direction. InLine: // physics.derailment new, the scan goes on past a vehicle off the track beside the line (or beside this one off it) auto find_vehicle( int const Direction, double const Range, bool const InLine = false ) const -> std::tuple; @@ -1120,6 +1127,8 @@ public: +class flank_zones; // vehicle/dynamic/flankzones.h + class vehicle_table : public basic_table { public: @@ -1173,6 +1182,17 @@ private: // what the bodies overlap by goes to the log every second void update_off_track_contacts( double const Deltatime ); + // physics.collisions new: the bodies of the vehicles on the rails at the switches, up to their fouling points, run into + // each other from the side (vehicle/flankcontact.h): the force of the contact along their rails and across them, the + // wheels of a vehicle pushed over the rail off it. looked at only for a vehicle moving with an axle in a fouling zone + void + update_flank_contacts( double const Deltatime ); + // the vehicle and those on the other way of the switch of a zone it is in: the pairs of update_flank_contacts() + void + gather_flank_pairs( TDynamicObject *Vehicle ); + // one pair of them in the update + void + flank_contact( TDynamicObject &First, TDynamicObject &Second, double const Deltatime ); double m_odometersavetimer { 0.0 }; // simulation time since the odometers were last saved // the most the bodies overlapped by, of the vehicles of update_off_track_contacts(), since it was logged last [m], and @@ -1185,6 +1205,9 @@ private: // the trains of the hoses of m_brakepipes, which change seldom: kept from one step to the next while they stay physics::hose_trains_cache m_hosetrains; std::vector> m_offtrackterrains; // of off_track_terrain() + // the fouling zones of the switches and the contacts going on, of update_flank_contacts(); the pairs of an update + std::shared_ptr m_flankzones; + std::vector> m_flankpairs; }; diff --git a/vehicle/dynamic/consist.cpp b/vehicle/dynamic/consist.cpp index c94fd4aed..2d1ca707c 100644 --- a/vehicle/dynamic/consist.cpp +++ b/vehicle/dynamic/consist.cpp @@ -59,6 +59,24 @@ http://mozilla.org/MPL/2.0/. +namespace { + +// the way of a switch a search running onto it from the track From goes over, by the end it runs onto it at (0: point 1, +// the points; 1: point 2, the frog end): the way joined to that track there. from the points both are, and the search +// takes the one the switch is set to. -1 off a switch +int entry_path( TTrack const *Track, TTrack const *From, int const Entry ) { + + if( Track == nullptr || Track->eType != tt_Switch || Track->SwitchExtension == nullptr ) { return -1; } + auto const first { Track->path_neighbour( 0, Entry ) == From }; + auto const second { Track->path_neighbour( 1, Entry ) == From }; + if( first != second ) { + return first ? 0 : 1; + } + return Track->SwitchExtension->CurrentIndex & 1; +} + +} // namespace + //--------------------------------------------------------------------------- TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, CouplingSet const cf) { // szukanie skrajnego połączonego pojazdu w pociagu @@ -349,7 +367,8 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance, bool c auto const mycoupler { NumberOf( initialdirection < 0 ? VehicleEnd::rear : VehicleEnd::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym auto foundcoupler { -1 }; // numer sprzęgu w znalezionym obiekcie (znaleziony wypełni) auto distance { 0.0 }; // przeskanowana odleglość; odległość do zawalidrogi - auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler, InLine ) }; // zaczynamy szukać na tym samym torze + // on a switch the way of it the axle is on + auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler, InLine, track != nullptr && track->eType == tt_Switch ? path_on( track ) : -1 ) }; // zaczynamy szukać na tym samym torze if( foundobject == nullptr ) { // jeśli nie ma na tym samym, szukamy po okolicy szukanie najblizszego toru z jakims obiektem @@ -360,6 +379,7 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance, bool c distance = RaTranslationGet(); // odległość osi od Point1 toru while (distance < Distance) { + auto const *from { track }; if (direction > 0) { // w kierunku Point2 toru if( track ? @@ -386,7 +406,7 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance, bool c } if (track) { // jesli jest kolejny odcinek toru - foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler, InLine); // przejrzenie pojazdów tego toru + foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler, InLine, entry_path( track, from, direction > 0 ? 0 : 1 ) ); // przejrzenie pojazdów tego toru if (foundobject) { break; } diff --git a/vehicle/dynamic/flankzones.cpp b/vehicle/dynamic/flankzones.cpp new file mode 100644 index 000000000..f310b6eea --- /dev/null +++ b/vehicle/dynamic/flankzones.cpp @@ -0,0 +1,207 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/dynamic/flankzones.h" + +#include +#include + +#include "editor/editorFouling.hpp" +#include "world/Segment.h" +#include "world/Track.h" + +namespace +{ + +// [m] along each way of a switch from its points its fouling point is looked for: past the frogs of the flattest turnouts +constexpr double traceLength{200.0}; +// [m] the zone goes on past the fouling point: a vehicle with an axle there reaches back over it with its end +constexpr double zoneMargin{30.0}; +// [m] between the points of the axis of a way +constexpr double sampleStep{1.0}; + +// the axis of a way of a switch from its points on, and the tracks it runs over with the distance to the start of each +struct walked +{ + std::vector points; + std::vector along; + std::vector> tracks; +}; + +// the points of the segment from the end the way runs onto it at (Forward: from its point 1), Done [m] the way had run before it +void sample(TSegment const &Segment, bool const Forward, double const Done, walked &Way) +{ + auto const length{Segment.GetLength()}; + auto at{Way.points.empty() ? 0.0 : sampleStep}; + while (true) + { + auto const distance{std::min(at, length)}; + glm::dvec3 point; + glm::vec3 rotation; + Segment.RaPositionGet(Forward ? distance : length - distance, point, rotation); + Way.points.push_back(point); + Way.along.push_back(Done + distance); + if (distance >= length || Done + distance >= traceLength) + { + return; + } + at += sampleStep; + } +} + +// the way a walk takes over a switch it runs onto from the track From at the End (0 its points, 1 the frog end): from the points +// the first one, from the frog end the one joined to that track +int way_onto(TTrack const &Switch, TTrack const *From, int const End) +{ + if (End == 1 && Switch.path_neighbour(1, 1) == From) + { + return 1; + } + return 0; +} + +walked walk(TTrack const &Switch, int const Path) +{ + walked result; + auto const *track{&Switch}; + auto path{Path}; + auto direction{1.0}; + auto done{0.0}; + for (int guard = 0; guard < 64 && track != nullptr && done < traceLength; ++guard) + { + auto const *segment{track->path_segment(path)}; + if (segment == nullptr || segment->GetLength() <= 0.0) + { + break; + } + result.tracks.emplace_back(track, done); + sample(*segment, direction > 0.0, done, result); + done += segment->GetLength(); + auto *next{track->Connected(direction > 0.0 ? 1 : -1, direction, track->eType == tt_Switch ? path : -1)}; + if (next == nullptr || next->eType == tt_Cross || (next->iCategoryFlag & 1) == 0) + { + break; + } + path = next->eType == tt_Switch ? way_onto(*next, track, direction > 0.0 ? 0 : 1) : 0; + track = next; + } + return result; +} + +// [m] along the way to the point of it nearest to the given one +double along_to(walked const &Way, glm::dvec3 const &Point) +{ + double distance; + std::size_t segment; + auto const foot{fouling::nearest_on(Way.points, Point, distance, segment)}; + if (segment >= Way.along.size()) + { + return Way.along.empty() ? 0.0 : Way.along.back(); + } + glm::dvec3 const offset{foot.x - Way.points[segment].x, 0.0, foot.z - Way.points[segment].z}; + return Way.along[segment] + glm::length(offset); +} + +} // namespace + +bool flank_zones::built_for(path_table const &Paths) +{ + if (false == m_built) + { + return false; + } + // the table only grows: the tracks added since the zones were made + auto const &tracks{Paths.sequence()}; + if (tracks.size() < m_trackcount) + { + return false; + } + for (auto index = m_trackcount; index < tracks.size(); ++index) + { + auto const *track{tracks[index]}; + if (track != nullptr && (track->iCategoryFlag & 1) != 0 && (track->iCategoryFlag & 0x80) == 0) + { + return false; + } + } + m_trackcount = tracks.size(); + return true; +} + +void flank_zones::build(path_table const &Paths) +{ + m_bytrack.clear(); + m_switches.clear(); + m_trackcount = Paths.sequence().size(); + m_built = true; + for (auto const *track : Paths.sequence()) + { + if (track == nullptr || track->eType != tt_Switch || track->SwitchExtension == nullptr || (track->iCategoryFlag & 1) == 0) + { + continue; + } + std::array const way{walk(*track, 0), walk(*track, 1)}; + auto &entry{m_switches[track]}; + ::fouling::place place; + auto const found{::fouling::find(way[0].points, way[1].points, ::fouling::kNominal, place)}; + for (int path = 0; path < 2; ++path) + { + auto const &trace{way[path]}; + entry.fouling[path] = found ? along_to(trace, path == 0 ? place.main : place.branch) : (trace.along.empty() ? 0.0 : trace.along.back()); + for (auto const &[on, start] : trace.tracks) + { + if (on != track && start < entry.fouling[path] + zoneMargin) + { + entry.tracks[path].push_back(on); + } + } + } + // a track on both ways (they meet again) is no zone of either: the vehicles on it are in line + for (int path = 0; path < 2; ++path) + { + std::erase_if(entry.tracks[path], [&entry, path](TTrack const *On) { return std::ranges::find(entry.tracks[1 - path], On) != entry.tracks[1 - path].end(); }); + } + m_bytrack[track].emplace_back(track, -1); + for (int path = 0; path < 2; ++path) + { + for (auto const *on : entry.tracks[path]) + { + m_bytrack[on].emplace_back(track, path); + } + } + } +} + +std::vector const *flank_zones::zones_of(TTrack const *Track) const +{ + auto const found{m_bytrack.find(Track)}; + return found != m_bytrack.end() ? &found->second : nullptr; +} + +std::vector const &flank_zones::tracks_of(TTrack const *Switch, int const Path) const +{ + static std::vector const none; + auto const found{m_switches.find(Switch)}; + if (found == m_switches.end() || Path < 0 || Path > 1) + { + return none; + } + return found->second.tracks[Path]; +} + +double flank_zones::fouling(TTrack const *Switch, int const Path) const +{ + auto const found{m_switches.find(Switch)}; + if (found == m_switches.end() || Path < 0 || Path > 1) + { + return 0.0; + } + return found->second.fouling[Path]; +} diff --git a/vehicle/dynamic/flankzones.h b/vehicle/dynamic/flankzones.h new file mode 100644 index 000000000..06ec89067 --- /dev/null +++ b/vehicle/dynamic/flankzones.h @@ -0,0 +1,77 @@ +/* +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/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "vehicle/flankcontact.h" + +class TTrack; +class TDynamicObject; +class path_table; + +// the fouling zones of the switches, for the flank contacts of vehicle_table::update_flank_contacts() (vehicle/flankcontact.h): +// for each switch of the rail tracks, the tracks along each of its ways from its points on, up to its fouling point (where the +// axes of the two ways are 3.50 m apart, editor/editorFouling.hpp) and a vehicle length past it. made once, from the +// scenery, the first time the contacts are looked for. a vehicle with an axle on none of these tracks is never looked at +class flank_zones +{ +public: + // a track of the zone of a switch: the switch and the way of it the track lies on; on the switch itself -1, the way is + // the one the axle is on + struct zone + { + TTrack const *track{nullptr}; + int path{-1}; + }; + // the fouling zones of all the switches of the tracks; again when a rail track was added (the editor). the tracks added on the + // run at the free ends of the tracks (TTrack::NullCreate(), flag 0x80) and the roads leave them as they are + void build(path_table const &Paths); + bool built_for(path_table const &Paths); + // the zones the track lies in, none for a track in none + std::vector const *zones_of(TTrack const *Track) const; + // the tracks of the zone of the switch along its way Path, past the switch + std::vector const &tracks_of(TTrack const *Switch, int Path) const; + // [m] from the points of the switch along its way to its fouling point + double fouling(TTrack const *Switch, int Path) const; + std::size_t switch_count() const { return m_switches.size(); } + + // two vehicles in a flank contact: the climbing of the wheels of each, and what the log tells when they part + struct contact + { + flank::Climb first; + flank::Climb second; + std::string names; // " and " + double depth{0.0}; // the most they overlapped by [m] + double force{0.0}; // [N] + double ratio1{0.0}; // the most Y / Q of each + double ratio2{0.0}; + bool seen{false}; // in the contact in this update + }; + // by the pair, the vehicles in the order of the table + std::map, contact> contacts; + +private: + struct ways + { + std::array, 2> tracks; + std::array fouling{0.0, 0.0}; + }; + std::unordered_map> m_bytrack; + std::unordered_map m_switches; + std::size_t m_trackcount{0}; + bool m_built{false}; +}; diff --git a/vehicle/dynamic/neighbours.cpp b/vehicle/dynamic/neighbours.cpp index 9d9d97945..f81c8508a 100644 --- a/vehicle/dynamic/neighbours.cpp +++ b/vehicle/dynamic/neighbours.cpp @@ -56,6 +56,7 @@ http://mozilla.org/MPL/2.0/. #include "application/application.h" #include "vehicle/Driver.h" #include "vehicle/dynamic/internal.h" +#include "vehicle/flankcontact.h" // ABu 29.01.05 koniec przeklejenia ************************************* @@ -209,7 +210,7 @@ void TDynamicObject::ABuCheckMyTrack() // Ra: w poniższej funkcji jest problem ze sprzęgami TDynamicObject * -TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine ) const +TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine, int const Path ) const { // Zwraca wskaźnik najbliższego obiektu znajdującego się // na torze w określonym kierunku, ale tylko wtedy, kiedy // obiekty mogą się zderzyć, tzn. nie mijają się. @@ -248,6 +249,8 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const } double objectposition; // robocza odległość od kolejnych pojazdów na danym odcinku + // physics.collisions new: on a switch the vehicles on its other way beside this one are left to the flank contacts + auto const byway { InLine && Path >= 0 && Track->eType == tt_Switch && Global.collisions == global_settings::collision_model::physical && Global.collisions_flank }; for( auto dynamic : Track->Dynamics ) { if( dynamic == this ) { continue; } // szukający się nie liczy @@ -255,6 +258,9 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const if( InLine && ( physics->OffTrack.active() || dynamic->physics->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { continue; } + if( byway && passes_by( *dynamic, Path, dynamic->path_on( Track ) ) ) { + continue; + } /* if( ( ( dynamic == PrevConnected ) && ( physics->Couplers[ physics::Vehicle::side::front ].CouplingFlag != Coupling::none ) ) || ( ( dynamic == NextConnected ) && ( physics->Couplers[ physics::Vehicle::side::rear ].CouplingFlag != Coupling::none ) ) ){ @@ -311,3 +317,26 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const Distance += distance; // doliczenie odległości przeszkody albo długości odcinka do przeskanowanej odległości return foundobject; } + +int +TDynamicObject::path_on( TTrack const *Switch ) const { + + auto path { -1 }; + for( auto const *axle : { &Axle0, &Axle1 } ) { + if( axle->GetTrack() != Switch || axle->GetPath() < 0 ) { continue; } + if( path >= 0 && path != axle->GetPath() ) { + // forked: on both ways + return -1; + } + path = axle->GetPath(); + } + return path; +} + +bool +TDynamicObject::passes_by( TDynamicObject const &Other, int const Path, int const OtherPath ) const { + + auto const placed = []( TDynamicObject const &Vehicle ) { + return flank::Placed { Vehicle.vPosition, Vehicle.VectorFront(), Vehicle.physics->Dim.L, Vehicle.physics->Dim.W > 0.5 ? Vehicle.physics->Dim.W : 3.0 }; }; + return flank::PassesBy( Path, OtherPath, placed( *this ), placed( Other ) ); +} diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 7942cef23..7a4b976dc 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -58,6 +58,8 @@ http://mozilla.org/MPL/2.0/. #include "application/application.h" #include "vehicle/Driver.h" #include "vehicle/dynamic/internal.h" +#include "vehicle/dynamic/flankzones.h" +#include "vehicle/flankcontact.h" namespace { @@ -328,6 +330,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { Timer::subsystem.vehicles_forces.stop(); update_off_track_contacts( totaltime ); + update_flank_contacts( totaltime ); Timer::subsystem.vehicles_update.start(); { @@ -557,6 +560,233 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { } } +namespace { + +// a vehicle on the rails of the flank contacts: enabled, on rails, not off them +bool on_rails( TDynamicObject const &Vehicle ) { + + return Vehicle.bEnabled + && TestFlag( Vehicle.physics->CategoryFlag, 1 ) + && ( false == Vehicle.physics->OffTrack.active() ); +} + +// coupled to each other, or the neighbours the search along the track found: their ends meet, not their sides +bool joined( TDynamicObject const &First, TDynamicObject const &Second ) { + + for( auto const end : VehicleEnds ) { + auto const &coupler { First.physics->Couplers[ end ] }; + if( coupler.Connected == Second.physics && coupler.CouplingFlag != Coupling::none ) { return true; } + if( First.physics->Neighbours[ end ].vehicle == &Second ) { return true; } + if( Second.physics->Neighbours[ end ].vehicle == &First ) { return true; } + } + return false; +} + +// two vehicles in line meeting by their buffers: the collision of their ends (collision.cpp) takes them, as in the search for +// the neighbours on a switch, also after it broke their couplers or lost them as neighbours +bool ends_meet( TDynamicObject const &First, TDynamicObject const &Second ) { + + auto const placed = []( TDynamicObject const &Vehicle ) { + return flank::Placed { Vehicle.GetPosition(), Vehicle.VectorFront(), Vehicle.physics->Dim.L, Vehicle.physics->Dim.W > 0.5 ? Vehicle.physics->Dim.W : 3.0 }; }; + return flank::EndsMeet( placed( First ), placed( Second ) ); +} + +// the vehicle in a flank contact +flank::Body flank_body( TDynamicObject const &Vehicle, derail_motion::footprint const &Print ) { + + auto const &physics { *Vehicle.physics }; + flank::Body body; + body.mass = physics.TotalMass(); + body.wheelMass = physics.TotalMass() - physics.Mred(); + body.axles = physics.NAxles() > 0 ? physics.NAxles() : 4; + body.pivots = physics.BDist(); + body.print = Print; + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + body.guide = length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 }; + body.speed = physics.V(); + return body; +} + +// the change of the speed along the rails by the force through the step +void push_along( TDynamicObject &Vehicle, double const Force, double const Deltatime ) { + + auto &physics { *Vehicle.physics }; + if( Force == 0.0 || physics.TotalMass() <= 0.0 ) { return; } + physics.SetV( physics.V() + Force * Deltatime / physics.TotalMass() ); +} + +// whether the wheels of the vehicle climbed the rail in the contact: then it leaves the rails +void climb_off( TDynamicObject &Vehicle, flank::Climb &Climb, flank::Load const &Load, double const Deltatime, std::string_view const Other ) { + + auto &physics { *Vehicle.physics }; + if( physics.DamageFlag.HasAll( VehicleDamage::derailed ) || false == Global.crash_damage || DebugModeFlag ) { + Climb.Reset(); + return; + } + auto const travel { std::abs( physics.V() ) * Deltatime }; + if( false == Climb.Update( Load, travel ) ) { return; } + auto const mass { physics.TotalMass() - physics.Mred() }; + auto const how { ( Load.corner && Load.ratio < 3.0 * derailment::climbing_limit ) ? std::format( ", the flange climbing over {:.2f} m", Climb.Distance() ) : std::string { ", at once" } }; + physics.DerailFlank( + Load.across >= 0.0 ? 1 : -1, + mass > 0.0 ? std::abs( Load.across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from {}, {:.0f} kN across{}", std::min( Load.ratio, 99.0 ), Other, std::abs( Load.across ) / 1000.0, how ) ); + Climb.Reset(); +} + +// which of the two hit the other: the one with its end in the contact, of two such or none the faster one +bool first_strikes( flank::Response const &Response, TDynamicObject const &First, TDynamicObject const &Second ) { + + if( Response.first.corner != Response.second.corner ) { + return Response.first.corner; + } + return std::abs( First.physics->V() ) >= std::abs( Second.physics->V() ); +} + +// how the two met, for the log +std::string_view meeting_of( flank::Response const &Response ) { + + if( Response.first.corner && Response.second.corner ) { return "corner to corner"; } + if( Response.first.corner || Response.second.corner ) { return "an end into a side"; } + return "side to side"; +} + +} // namespace + +void +vehicle_table::update_flank_contacts( double const Deltatime ) { + + if( Global.collisions != global_settings::collision_model::physical || false == Global.collisions_flank || Deltatime <= 0.0 ) { + return; + } + if( m_flankzones == nullptr ) { + m_flankzones = std::make_shared(); + } + if( false == m_flankzones->built_for( simulation::Paths ) ) { + auto const started { off_track_clock::now() }; + m_flankzones->build( simulation::Paths ); + WriteLog( std::format( "flank contacts: the fouling zones of {} switches, made in {:.0f} ms", m_flankzones->switch_count(), vehicle_dynamic::seconds_since( started ) * 1000.0 ) ); + } + // the moving vehicles with an axle in a fouling zone, with those on the other way of its switch: most have none + m_flankpairs.clear(); + for( auto *vehicle : m_items ) { + if( on_rails( *vehicle ) && std::abs( vehicle->physics->V() ) > 0.01 ) { + gather_flank_pairs( vehicle ); + } + } + auto &contacts { m_flankzones->contacts }; + if( m_flankpairs.empty() && contacts.empty() ) { + return; + } + // each pair once, in the order of the table: the same in every run + std::unordered_map places; + for( std::size_t place = 0; place < m_items.size(); ++place ) { + places.emplace( m_items[ place ], place ); + } + for( auto &pair : m_flankpairs ) { + if( places[ pair.second ] < places[ pair.first ] ) { + std::swap( pair.first, pair.second ); + } + } + std::ranges::sort( m_flankpairs, [ &places ]( auto const &Left, auto const &Right ) { + return std::pair { places[ Left.first ], places[ Left.second ] } < std::pair { places[ Right.first ], places[ Right.second ] }; } ); + auto const repeated { std::ranges::unique( m_flankpairs ) }; + m_flankpairs.erase( repeated.begin(), repeated.end() ); + for( auto &entry : contacts ) { + entry.second.seen = false; + } + for( auto const &[ first, second ] : m_flankpairs ) { + flank_contact( *first, *second, Deltatime ); + } + // the contacts which ended: told in the log + std::erase_if( contacts, []( auto const &Entry ) { + auto const &contact { Entry.second }; + if( contact.seen ) { return false; } + WriteLog( std::format( + "flank collision: {} apart again, overlapped by up to {:.2f} m, {:.0f} kN at most, Y/Q up to {:.2f} / {:.2f}", + contact.names, contact.depth, contact.force / 1000.0, std::min( contact.ratio1, 99.0 ), std::min( contact.ratio2, 99.0 ) ) ); + return true; } ); +} + +void +vehicle_table::gather_flank_pairs( TDynamicObject *Vehicle ) { + + for( auto const *axle : { &Vehicle->Axle0, &Vehicle->Axle1 } ) { + auto const *zones { m_flankzones->zones_of( axle->GetTrack() ) }; + if( zones == nullptr ) { continue; } + for( auto const &zone : *zones ) { + // the way of the switch the vehicle is on: of its track, on the switch of its axle + auto const way { zone.path >= 0 ? zone.path : axle->GetPath() }; + if( way < 0 ) { continue; } + // the vehicles on the switch on the other way, and on the tracks of the other way + for( auto *other : zone.track->Dynamics ) { + if( other != Vehicle && other->path_on( zone.track ) != way ) { + m_flankpairs.emplace_back( Vehicle, other ); + } + } + for( auto const *track : m_flankzones->tracks_of( zone.track, 1 - way ) ) { + for( auto *other : track->Dynamics ) { + if( other != Vehicle ) { + m_flankpairs.emplace_back( Vehicle, other ); + } + } + } + } + } +} + +void +vehicle_table::flank_contact( TDynamicObject &First, TDynamicObject &Second, double const Deltatime ) { + + if( false == on_rails( First ) || false == on_rails( Second ) || joined( First, Second ) || ends_meet( First, Second ) ) { + return; + } + // the bounding circles first + auto const apart { Second.GetPosition() - First.GetPosition() }; + auto const reach { 0.5 * ( First.physics->Dim.L + Second.physics->Dim.L ) + std::max( First.physics->Dim.W, Second.physics->Dim.W ) + 1.0 }; + if( glm::length( glm::dvec3 { apart.x, 0.0, apart.z } ) > reach ) { + return; + } + auto const print { footprint_of( First ) }; + auto const otherprint { footprint_of( Second ) }; + auto const hit { derail_motion::collide( print, otherprint ) }; + if( false == hit.has_value() ) { + return; + } + auto const firstbody { flank_body( First, print ) }; + auto const secondbody { flank_body( Second, otherprint ) }; + auto const response { flank::Respond( *hit, firstbody, secondbody, Deltatime ) }; + auto &contacts { m_flankzones->contacts }; + auto const key { std::pair { &First, &Second } }; + auto found { contacts.find( key ) }; + if( found == contacts.end() ) { + if( response.force <= 0.0 ) { + // side by side without closing in: placed so by the scenery, or tracks too close together. nothing to tell + return; + } + auto const strikes { first_strikes( response, First, Second ) }; + auto const &striker { strikes ? First : Second }; + auto const &struck { strikes ? Second : First }; + auto const relative { glm::length( secondbody.guide * secondbody.speed - firstbody.guide * firstbody.speed ) }; + WriteLog( std::format( + "flank collision: {} hit {} at {:.0f} km/h, {:.0f} km/h between them, closing in at {:.1f} km/h, {}", + striker.physics->Name, struck.physics->Name, std::abs( striker.physics->V() ) * 3.6, relative * 3.6, response.closing * 3.6, meeting_of( response ) ) ); + found = contacts.try_emplace( key ).first; + found->second.names = std::format( "{} and {}", First.physics->Name, Second.physics->Name ); + } + auto &contact { found->second }; + contact.seen = true; + contact.depth = std::max( contact.depth, hit->depth ); + contact.force = std::max( contact.force, response.force ); + contact.ratio1 = std::max( contact.ratio1, response.first.ratio ); + contact.ratio2 = std::max( contact.ratio2, response.second.ratio ); + push_along( First, response.first.along, Deltatime ); + push_along( Second, response.second.along, Deltatime ); + climb_off( First, contact.first, response.first, Deltatime, Second.physics->Name ); + climb_off( Second, contact.second, response.second, Deltatime, First.physics->Name ); +} + std::shared_ptr vehicle_table::off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ) { diff --git a/vehicle/flankcontact.cpp b/vehicle/flankcontact.cpp new file mode 100644 index 000000000..3a3720d86 --- /dev/null +++ b/vehicle/flankcontact.cpp @@ -0,0 +1,181 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/flankcontact.h" + +#include +#include + +namespace flank +{ + +namespace +{ + +glm::dvec3 levelUnit(glm::dvec3 const &Vector) +{ + glm::dvec3 const level{Vector.x, 0.0, Vector.z}; + auto const length{glm::length(level)}; + return length > 1e-9 ? level / length : glm::dvec3{0.0, 0.0, 1.0}; +} + +// to the left of the way along, level +glm::dvec3 leftOf(glm::dvec3 const &Guide) +{ + return glm::dvec3{Guide.z, 0.0, -Guide.x}; +} + +// the inverse of the mass a body on the rails moves with the way of the direction: along its rails only +double inverseMass(Body const &Vehicle, glm::dvec3 const &Direction) +{ + if (Vehicle.mass <= 0.0) + { + return 0.0; + } + auto const along{glm::dot(Direction, Vehicle.guide)}; + return along * along / Vehicle.mass; +} + +// how far along the body from its middle the point is [m] +double alongOf(Body const &Vehicle, glm::dvec3 const &Point) +{ + glm::dvec3 const offset{Point.x - Vehicle.print.centre.x, 0.0, Point.z - Vehicle.print.centre.z}; + return glm::dot(offset, Vehicle.print.axis); +} + +// the force [N] the face of the body the contact pushes in gives way at: its end crushes at once, its side at the side crush +// until the overlap goes past the side wall, then up to the crush of an end over as much again +double faceForce(Body const &Vehicle, glm::dvec3 const &Normal, double const Depth) +{ + if (std::abs(glm::dot(Normal, Vehicle.print.axis)) >= std::sqrt(0.5)) + { + return endCrush; + } + if (Depth <= sideDepth) + { + return sideCrush; + } + return std::lerp(sideCrush, endCrush, std::min((Depth - sideDepth) / sideDepth, 1.0)); +} + +// the force along and across the rails of the body, and what it does to its wheels +Load loadOf(Body const &Vehicle, glm::dvec3 const &Force, glm::dvec3 const &Point) +{ + Load result; + result.along = glm::dot(Force, Vehicle.guide); + result.across = glm::dot(Force, leftOf(Vehicle.guide)); + auto const along{alongOf(Vehicle, Point)}; + result.corner = std::abs(along) >= Vehicle.print.half_length - cornerReach; + result.ratio = ClimbRatio(Vehicle, result.across, along); + return result; +} + +} // namespace + +bool EndsMeet(Placed const &First, Placed const &Second) +{ + auto const front{levelUnit(First.front)}; + auto const otherfront{levelUnit(Second.front)}; + glm::dvec3 const apart{Second.position.x - First.position.x, 0.0, Second.position.z - First.position.z}; + // the end of each that faces the other + auto const end{front * (glm::dot(apart, front) >= 0.0 ? 0.5 * First.length : -0.5 * First.length)}; + auto const otherend{apart + otherfront * (glm::dot(apart, otherfront) <= 0.0 ? 0.5 * Second.length : -0.5 * Second.length)}; + auto const between{otherend - end}; + auto const inLine{std::abs(glm::dot(between, leftOf(front))) < bufferReach && std::abs(glm::dot(between, leftOf(otherfront))) < bufferReach}; + return inLine && std::abs(glm::dot(apart, front)) >= 0.5 * (First.length + Second.length) - endReach; +} + +bool PassesBy(int const Path, int const OtherPath, Placed const &First, Placed const &Second) +{ + if (Path < 0 || OtherPath < 0 || Path == OtherPath) + { + return false; + } + return false == EndsMeet(First, Second); +} + +double EndShare(double const Along, double const Pivots) +{ + if (Pivots <= 1e-3) + { + return 1.0; + } + return 0.5 + std::abs(Along) / Pivots; +} + +double ClimbRatio(Body const &Vehicle, double const Across, double const Along) +{ + auto const axles{static_cast(std::max(Vehicle.axles, 2))}; + auto const wheelload{Vehicle.wheelMass * derailment::gravity / (2.0 * axles)}; + if (wheelload <= 0.0) + { + return 0.0; + } + // the push of that end is taken by the axles under it, half of them, each by its flanging wheel + auto const pivots{Vehicle.pivots > 0.0 ? Vehicle.pivots : Vehicle.print.half_length}; + auto const lateral{EndShare(Along, pivots) * std::abs(Across) / std::max(0.5 * axles, 1.0)}; + return lateral / wheelload; +} + +double CrushForce(derail_motion::contact const &Contact, Body const &First, Body const &Second) +{ + auto const weaker{std::min(faceForce(First, Contact.normal, Contact.depth), faceForce(Second, Contact.normal, Contact.depth))}; + return weaker * std::min(std::max(Contact.depth, 0.0) / crushRamp, 1.0); +} + +Response Respond(derail_motion::contact const &Contact, Body const &First, Body const &Second, double const Dt) +{ + Response result; + auto const normal{levelUnit(Contact.normal)}; + auto const relative{Second.guide * Second.speed - First.guide * First.speed}; + auto const closing{-glm::dot(relative, normal)}; + if (closing <= 0.0 || Dt <= 0.0 || Contact.depth <= 0.0) + { + // parting, or sliding along each other only: a crushed side doesn't spring back + result.first = loadOf(First, glm::dvec3{0.0}, Contact.point); + result.second = loadOf(Second, glm::dvec3{0.0}, Contact.point); + return result; + } + result.closing = closing; + // no more than stops the closing within the step, the bodies don't bounce off each other + auto const inverse{inverseMass(First, normal) + inverseMass(Second, normal)}; + auto force{CrushForce(Contact, First, Second)}; + if (inverse > 0.0) + { + force = std::min(force, closing / (inverse * Dt)); + } + result.force = force; + glm::dvec3 onSecond{normal * force}; + // the friction of the sides sliding along each other, no more than stops the sliding within the step + auto const sliding{relative + normal * closing}; + if (auto const slide{glm::length(sliding)}; slide > 1e-6) + { + auto const way{sliding / slide}; + auto const slideinverse{inverseMass(First, way) + inverseMass(Second, way)}; + auto friction{derail_motion::contact_friction * force}; + if (slideinverse > 0.0) + { + friction = std::min(friction, slide / (slideinverse * Dt)); + } + onSecond -= way * friction; + } + result.first = loadOf(First, -onSecond, Contact.point); + result.second = loadOf(Second, onSecond, Contact.point); + return result; +} + +bool Climb::Update(Load const &Pushed, double const Travel) +{ + auto const climbs{Pushed.corner && Pushed.ratio >= derailment::climbing_limit}; + auto const climbed{m_window.update(climbs, Travel)}; + return climbed || Pushed.ratio >= 3.0 * derailment::climbing_limit; +} + +} // namespace flank diff --git a/vehicle/flankcontact.h b/vehicle/flankcontact.h new file mode 100644 index 000000000..94828e23c --- /dev/null +++ b/vehicle/flankcontact.h @@ -0,0 +1,128 @@ +/* +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/. +*/ + +#pragma once + +#include + +#include "physics/derailment.h" +#include "vehicle/derailmotion.h" + +// flank (side) contacts of two vehicles on the rails (physics.collisions new), at a switch and on its tracks up to the fouling +// point (W 17), where the tracks are too close for two vehicles to pass. the search of the neighbours along the track meets the +// vehicles in line with each other only; two on the two ways of a switch, or on the two tracks beyond it, meet here by their +// bodies, the footprints of derail_motion::collide(). +// +// the contact: neither vehicle leaves its rails, so what gives is the body. the side of a body hit by the end (the corner) of +// another one crushes at a low force (sideCrush), deeper in, past its side wall, the floor takes up to the force an end crushes at +// (endCrush); an end hit squarely crushes at endCrush at once. the force rises over the first crushRamp of the overlap, so a graze +// pushes little, and it is no more than stops the two closing in within the step: the bodies don't bounce off each other. the +// force is the same whatever the step, as the overlap and the distance travelled are. +// +// what it does to each vehicle: along its rails it slows it down or speeds it up (with the friction of the sides sliding along +// each other), across them it loads its wheels. a vehicle whose end (corner) is in the contact is turned by the push across it: +// its leading wheels run at an angle to the rail and the flange climbs at Nadal's limit, held over the window of EN 14363, or at +// three times that at once. a body hit along its side moves across bodily, its wheels square to the rail: only three times the +// limit at once takes it off. so the corner that strikes derails and the train struck along its side stays on the rails with its +// side torn: Skierniewice 2023 (PKBWK 6/2024, an ET41 with 1007 t at 25 km/h into the side of an EMU at 53 km/h, the locomotive +// derailed and tipped, the EMU stayed on) and Bromsgrove 2020 (RAIB 14/2020, a train at 137 km/h along a locomotive standing foul, +// it stayed on the rails) +namespace flank +{ + +// ---- the neighbours on a switch (TDynamicObject::ABuFindObject()) + +// how far the ends of two vehicles in line go into each other and are still ends meeting [m]: their buffers and the crush of +// both ends +inline constexpr double endReach{2.0}; +// how far apart across the ends of two vehicles can be and still meet by their buffers [m]: 1.75 m between the middles of the +// two buffers of an end, and the width of a buffer head (0.45 m). further apart only their corners meet +inline constexpr double bufferReach{2.2}; + +// a vehicle where it stands: the middle, the way its front faces (level), its length over the buffers and its width +struct Placed +{ + glm::dvec3 position{0.0}; + glm::dvec3 front{0.0, 0.0, 1.0}; + double length{20.0}; + double width{3.0}; +}; +// whether the two meet by their ends: the ends facing each other off each other by less than bufferReach across (so their +// buffers meet), and apart along the first by about their half lengths. side by side they don't, whichever way they go, and +// neither do two ends meeting only by their corners +bool EndsMeet(Placed const &First, Placed const &Second); +// whether the search of the neighbours of the first vehicle, going over a switch by its way Path, goes past the second one, +// which has its axle there on its way OtherPath: on another way and beside it, not ahead of it. a way not known (-1) is any one +bool PassesBy(int Path, int OtherPath, Placed const &First, Placed const &Second); + +// ---- the contact + +// [N] the side of a body pushed in by the end of another one, as far as its side wall goes (sideDepth [m]). no standard gives a +// load across a body (EN 12663 and EN 15227 have none): set so that a coach of 40-50 t hit at its middle keeps its wheels below +// Nadal's limit, as the struck trains of Skierniewice and Bromsgrove did +inline constexpr double sideCrush{0.25e6}; +inline constexpr double sideDepth{0.5}; +// [N] an end crushed, and the floor of a body behind its side wall: the plateau of the crush of collision.cpp +inline constexpr double endCrush{2.0e6}; +// [m] of the overlap the force rises over +inline constexpr double crushRamp{0.1}; +// [m] from an end the contact is at that end: the corner of the body +inline constexpr double cornerReach{1.5}; + +// a vehicle on the rails in a contact +struct Body +{ + double mass{0.0}; // all of it [kg], for the force along its rails + double wheelMass{0.0}; // on the wheels, without the rotating masses [kg], for the load of a wheel + int axles{4}; + double pivots{0.0}; // the distance of the bogie pivots, of the outer axles without bogies [m] + derail_motion::footprint print; + glm::dvec3 guide{0.0, 0.0, 1.0}; // along its rails, level, the way its front faces + double speed{0.0}; // along the guide [m/s] +}; +// what the contact does to one of the two +struct Load +{ + double along{0.0}; // the force along its rails [N], along its guide positive + double across{0.0}; // across them [N], to the left of its guide positive + double ratio{0.0}; // Y / Q of the wheel the push across loads most + bool corner{false}; // the contact at its end: it is turned by the push and climbs at Nadal's limit +}; +struct Response +{ + double force{0.0}; // pressing the two apart [N] + double closing{0.0}; // the speed they close in at across the contact [m/s], none when parting + Load first; + Load second; +}; +// the force of the contact over the step of Dt [s]: the two apart along the normal of the contact (out of the first into the +// second), and the friction of the sides sliding along each other +Response Respond(derail_motion::contact const &Contact, Body const &First, Body const &Second, double Dt); +// the force [N] the faces of the two give way at, with the overlap Depth [m]: the weaker one +double CrushForce(derail_motion::contact const &Contact, Body const &First, Body const &Second); +// the share of a push across a body at Along [m] from its middle that the end nearer to it takes: rigid, on its two bogies +double EndShare(double Along, double Pivots); +// the Y / Q of the wheel of that end pushed across with the force [N] +double ClimbRatio(Body const &Vehicle, double Across, double Along); + +// whether the wheels of a vehicle in the contact climbed the rail, step by step +class Climb +{ +public: + // true once they did: Y / Q at the climbing limit held over the window of EN 14363 by a vehicle with its end in the + // contact, as it rolled Travel [m] in the step; or three times the limit at once, by any + bool Update(Load const &Pushed, double Travel); + void Reset() { m_window.reset(); } + double Distance() const { return m_window.distance(); } + +private: + derailment::stretch m_window; +}; + +} // namespace flank