From 633b97d21c248b0f3498d4b4b15f52b346fa6a22 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 04:47:02 +0100 Subject: [PATCH 01/59] test(scenarios): cases on a mission of a scenery, slow and xfail marks, --seed A case can now run one of the base scenery's own missions among its traffic: - vehicle: the train under test is a vehicle of the base scenery (with strip_trainsets false), the fragment becomes optional, - replace: literal replacements in the base scenery, e.g. another locomotive on a mission, - physicslog false: no physicslogs and no black box, for a scenery with dozens of AI trains; the case then has the result of the test mode and the log checks only, - on such a case the runner doesn't wait for physicslog rows nor give up on a bad vehicle of the scenery, and removes the physicslogs the other trains wrote; with file.binary.terrain no in ini it leaves no geometry cache behind, - slow: skipped by the default sweep, run by name or with --slow, - xfail: a known, reported failure is XFAIL and keeps the run green, a pass is XPASS and fails it, - --seed: the seed of the simulator's random numbers for a run, for bugs that show up sometimes. The couples check takes vehicle names in any case (the simulator reads them in lower case), and the physicslog is no longer read four times a second once it has rows. --- tests/scenarios/README.md | 85 ++++++++++++++++++++++++++--- tests/scenarios/run.py | 111 +++++++++++++++++++++++++++++--------- 2 files changed, 166 insertions(+), 30 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index ea5ebc89b..736e8639a 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -135,13 +135,23 @@ Python 3.10+, no extra packages. Options: `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command line options. - name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`. -- `-j N` runs N cases at once. Each case prints its results when it is done. All 19 cases - take about 30 s with `-j 4`, loading included. +- `-j N` runs N cases at once. Each case prints its results when it is done. The 19 cases + that aren't `slow` take about 30 s with `-j 4` and 2 minutes one at a time, loading included. - `--watch` runs a case the old way, in a visible window in real time (or faster with `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For watching what a case does. +- `--slow` runs the cases marked `slow` too. Without it, and with no cases named, they are + skipped (and listed): each is a whole mission on a big scenery and takes many minutes. A + slow case named on the command line always runs. Run them one at a time (`-j 1`): each + simulator loads a whole scenery, and the ones with physicslog on collect every physicslog + written in the game dir meanwhile. +- `--seed N` (a number or a word) runs the cases with another seed of the simulator's random + numbers (`randomseed`) than the fixed one of the test mode, for a bug that shows up only + sometimes: run the case with a few seeds. -Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`, +Exit code is 0 when every case passed, or failed as its `xfail` mark says it does (`XFAIL` in +the summary); a case marked `xfail` that passes (`XPASS`) fails the run, so that the mark gets +removed. Logs of each run (`log.txt`, `errors.txt`, `stdout.txt`, the physicslogs of the vehicle and of other trains of the case, the black box as `autotest_.blackbox`) are moved to `tests/scenarios/out//`. @@ -171,7 +181,17 @@ The lead vehicle is named `autotest_`, so every case has its own physicslo files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt` geometry cache of them) stay in the game's `scenery/` dir; the cache is dropped when the base scenery is newer, and after a run cut short (`wall_timeout`, `error`, a crash, or killed by run.py), -which could have been writing it. +which could have been writing it. A case with `file.binary.terrain no` in its `ini` has no cache +written, and one left by an earlier run is removed. + +A case with `vehicle` runs a train of the base scenery under its own name: its physicslog is +`physicslog/.dat` (one of that name already in the game dir is replaced), and with the +physicslogs on, every train of the scenery writes one, over any of the same name; those written +during the run are deleted after it. Don't run such a case along with another one in the same game dir. + +Apart from these the game dir loses its `log.txt` and `errors.txt`, those of the last game +session: the simulator deletes them at every start, before it knows that the run's log goes +to `logs/`. ## Writing a case @@ -180,13 +200,18 @@ which could have been writing it. | key | meaning | | --- | --- | | `base_scenery` | scenery file in the game's `scenery/` dir | -| `strip_trainsets` | drop the base scenery's trainsets (default `true`) | +| `strip_trainsets` | drop the base scenery's trainsets (default `true`); `false` keeps them, for a case on one of the scenery's own missions (below) | +| `vehicle` | the train under test is this vehicle of the base scenery (its node name), instead of the `autotest_` one of the fragment: `test.vehicle`, the physicslog checked and `{{vehicle}}` are this one. With `strip_trainsets` `false` | +| `replace` | literal replacements in the text of the base scenery, a list of `[old, new]`, e.g. to put another locomotive on a mission; an `old` the scenery doesn't have is an error | +| `physicslog` | `false` turns the physicslogs (and the black box) off for the run: on a scenery with dozens of AI trains each of them would write 3-4 kB per second of simulation into the game dir. Such a case has the result of the test mode and the log checks only (default `true`) | +| `slow` | `true` marks a case that takes many minutes: skipped unless named or run with `--slow` | +| `xfail` | marks a case that fails because of a known, reported bug, with the reference and the reason as its text, e.g. `"eu07/maszyna#524: the AI never couples"`. Its failure is reported as `XFAIL` and doesn't fail the run; when it passes (`XPASS`) the run fails until the mark is removed | | `time` | replace the scenery start time, `HH:MM` | | `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail | | `track_events` | lines added to tracks of the base scenery, by track name, e.g. `{ "tor1k": "event0 test_pass" }`; only tracks in the scenery file itself, not in its includes | | `test_config` | lines of a `config` block added to the scenery, e.g. `["test.timeout 90"]`; the block always has `test.vehicle` with the case's lead vehicle, so only its train counts for the pass and the standstill | | `ini` | extra `eu07.ini` lines for the run, after the common ones of the runner's `-ini` file, e.g. `["crashdamage yes"]` | -| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) | +| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire). Optional when the case keeps the scenery's trainsets | | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | | `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | | `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | @@ -230,6 +255,54 @@ couple and neither shows up: the black box has to have the last car of the stand writes nothing to the log when couplers catch). Nothing reports a result, so both end on the 60 s test timeout. +### Cases on a mission of a scenery + +The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission +of a scenery of the game, among its own traffic: `strip_trainsets` `false`, `vehicle` the +mission's own locomotive or unit, every train driven by AI as always in the test mode. They are +`slow`, have `physicslog` `false` unless a check needs the black box, and `file.binary.terrain no` +in `ini`, so that no geometry cache of the copied scenery (hundreds of MB for these) is written +into the game dir. What they add to the scenery: + +- nothing, when standing too long is the bug: `test.standstill` is set above the longest wait + the mission has, and the run ends with `duration` (`baltyk_skm1_*`), +- `mission_state_probe.scn`: these sceneries steer each station with a state cell per train + (text and two values, e.g. `deb_tme222158_stat` = `a 6 *`: the route of step 6 is set). The + probe is a loop of two events that looks at the cell `vars.cell` every 5 s and reports the + pass once it holds `vars.state` (a `memcompare`: `* 6 *`, `d * *`), with `vars.reason` as the + text. No fail event: a train that never gets there ends the test with the standstill or the + timeout. A periodic event launcher wouldn't do, the simulator polls those near the camera only, +- events named `:event0`, `:event1`, `:event2` or `:eventall1`...: the simulator binds an + event with such a name to the track by itself, so a fragment can hang events on tracks that + live in the scenery's includes, where `track_events` doesn't reach (`wrzosy_pxe336080_couple.scn`). + The name must not be one the scenery has already: a second event of the same name replaces the first. + +A train whose trainset has velocity 0 has a driver that sleeps in `Wait_for_orders` when nobody +is in the cab: the player would drive it, so the fragment has to give the orders the player's +hands stand for, with `PutValues` from an event the vehicle itself sets off (`event0` of the +track it stands on). The first of them must not be the one to couple (`Shunt -2 -3`): a driver +whose first order is `Connect` never releases the hand brake a cold locomotive starts with. The +mission trains of velocity 0.1 wait for their signal and need nothing. + +The cases and what they showed on master of 2026-11-11: + +| case | report | result | +| --- | --- | --- | +| `wrzosy_pxe336080_couples` | #524 | passes: ordered to, the locomotive couples to the rake (`couples`, 262 s) and takes it out of the depot (696 s). The scenery itself gives no such order | +| `baltyk_skm1_roj55324_shunting_signal` | #525 | passes, with four seeds: the unit on the siding is let into the platforms 4 minutes after the start, once the shunter beside it has done its first moves, and leaves at 10:42 | +| `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34 | +| `l053_poranek_tme222158_debica` | #421 | `xfail`: the train is never let into Debica, the station jams 4 minutes after the start: the AI of EP07-338'16 passes the shunting signal Tm4 at stop at 29 km/h and stops 20 m beyond the checkpoint the station waits for it at | +| `l053_poranek_tme222158_debica_et21` | #421 | `xfail`: with an ET21, as in the report, the locomotive stops for good at Debica Towarowa: running round the wagons it stands on the headshunt 20 m past the end of the overhead wire, and its driver never gets out of `Prepare_engine` | +| `l053_poludnie_roj32134_debica` | #506 | passes: both trains run and the unit ends at Debica after 6134 s; no train in its way | + +In the L053 sceneries the test mode logs a signal passed at danger for several shunting +locomotives within minutes, so these cases have `test.fail_if_stop_overran no`. + +The simulation ran at 15 times real time on Baltyk and at 5-8 times on L053 (with another +build going on on the machine) with the physicslogs off, and at 3-4 times on Wrzosy with them +on (250 drivers, the road vehicles included: 740 MB of physicslogs in 900 s), after 30-150 s of +loading. + Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 51fdc3c66..cd05866ec 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -77,7 +77,7 @@ width 1280 height 720 inactivepause no soundenabled no -physicslog yes +physicslog {physicslog} multiplelogs yes timespeed {timespeed} """ @@ -156,7 +156,12 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s text = set_track_friction(text, case["track_friction"]) if "track_events" in case: text = add_track_events(text, case["track_events"]) - fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") + for old, new in case.get("replace", []): + if old not in text: + sys.exit(f"replace: the base scenery has no {old!r}") + text = text.replace(old, new) + # a case on a mission of the base scenery may have nothing to add but its test_config + fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") if "fragment" in case else "" # vars first: {{vehicle}} inside a var's value gets filled in the second pass fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"}) fragment = fill_vars(fragment, {"vehicle": vehicle}) @@ -328,7 +333,7 @@ class RunResult: def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path, - duration: float | None, timeout: float, watch: bool, say) -> RunResult: + duration: float | None, timeout: float, watch: bool, say, expect_rows: bool = True) -> RunResult: """Runs the simulator on the scenery. In test mode it quits by itself and the exit code is the result; with watch it runs in a window and gets closed after `duration`.""" physicslog.unlink(missing_ok=True) @@ -351,7 +356,9 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog while True: time.sleep(0.25) # at timespeed 20 that is 5 s of simulation wall = time.monotonic() - started - result.rows = read_physicslog(physicslog) + # the whole file is read each time: in test mode, once there are rows, only for the progress line + if watch or not result.rows or wall - last_report >= 15: + result.rows = read_physicslog(physicslog) sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0 if wall - last_report >= 15: v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0 @@ -366,7 +373,10 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog if wall > timeout + (0 if watch else KILL_GRACE): result.failure = f"timed out after {wall:.0f}s before {duration}s of simulation" break - if not result.rows: + # not for a case with physicslog off, which has no rows to wait for, nor for one on a mission of the + # base scenery: a big scenery loads for minutes, and a bad vehicle among its decorations isn't the + # case's (a missing test vehicle ends the test mode with `error` by itself) + if expect_rows and not result.rows: result.logs = find_logs(game_dir, scenery, since) fatal = [l.strip() for l in read_text(result.logs.get("errors")).splitlines() if any(k in l for k in FATAL_LOG_LINES)] @@ -579,11 +589,12 @@ LOG_CHECKS = { def check_couples(box, vehicle, other): """The two vehicles couple in the run and stay coupled to its end; coupled from the start doesn't count.""" - numbers = {name: number for number, name in box.vehicles.items()} - unknown = [name for name in (vehicle, other) if name not in numbers] + # the simulator reads the names of a scenery in lower case, whatever the scenery (or the case) writes + numbers = {name.lower(): number for number, name in box.vehicles.items()} + unknown = [name for name in (vehicle, other) if name.lower() not in numbers] if unknown: return False, f"the black box has no vehicle {' nor '.join(unknown)}" - pair = {numbers[vehicle], numbers[other]} + pair = {numbers[vehicle.lower()], numbers[other.lower()]} # of the two vehicles of a coupling the one with the lower number tells it, each change of that coupler # under the same vehicle and side: the record which coupled the two, for as long as they stay coupled made, parted = {}, None @@ -637,21 +648,51 @@ def describe_exit(code: int | None) -> str: return f"{code} ({name})" if name else f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)" -def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say) -> bool: - case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) +def load_case(name: str) -> dict: + return json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) + + +def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, seed: str | None = None) -> str: + """Runs the case and returns PASS or FAIL; for a case marked `xfail` (a known, reported bug) XFAIL + when it fails as expected, and XPASS when it passes, which means the mark has to go.""" + case = load_case(name) + ok = _run_case(name, case, exe, game_dir, timespeed, watch, say, seed) + if "xfail" not in case or watch: + return "PASS" if ok else "FAIL" + if ok: + say(f" XPASS the case passes although it is marked xfail ({case['xfail']}): remove the mark") + return "XPASS" + say(f" XFAIL fails as expected: {case['xfail']}") + return "XFAIL" + + +def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, + seed: str | None = None) -> bool: say(f"\n=== {name}: {case.get('description', '')}") out = OUT_DIR / name shutil.rmtree(out, ignore_errors=True) out.mkdir(parents=True) - # the lead vehicle is named after the case, so parallel runs never share a physicslog - vehicle = f"autotest_{name}" + # the lead vehicle is named after the case, so parallel runs never share a physicslog. a case on a + # mission of the base scenery (strip_trainsets false) names one of the scenery's own vehicles instead + own_vehicle = "vehicle" in case + vehicle = case.get("vehicle", f"autotest_{name}") + # a long run on a scenery with dozens of AI trains would write a physicslog for each of them into the + # game dir (3-4 kB per second of simulation and train); such a case turns them off and relies on the + # result of the test mode and on the log + with_physicslog = case.get("physicslog", True) + needs_physicslog = [c["type"] for c in case.get("checks", []) if c["type"] not in LOG_CHECKS] + if not with_physicslog and (watch or needs_physicslog): + sys.exit(f"{name}: with physicslog off a case can have log checks only ({', '.join(LOG_CHECKS)}), " + "and can't run with --watch") scenery = build_scenery(case, game_dir, name, vehicle) ini = out / "autotest.ini" - # the case's own settings go last, over the common ones - ini.write_text(TEST_INI.format(timespeed=timespeed) + "".join(line + "\n" for line in case.get("ini", [])), - encoding="ascii") + # the case's own settings go last, over the common ones; then the seed of this run of the suite, if any + settings = [*case.get("ini", []), *([f"randomseed {seed}"] if seed else [])] + ini.write_text(TEST_INI.format(timespeed=timespeed, physicslog="yes" if with_physicslog else "no") + + "".join(line + "\n" for line in settings), encoding="ascii") physicslog = game_dir / "physicslog" / f"{vehicle}.dat" + started = time.time() - 1 duration = float(case["duration"]) if "duration" in case else None # a case that only records `duration` seconds ends on the test timeout; one that says @@ -662,7 +703,11 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool if watch and duration is None: sys.exit(f"{name}: --watch needs a case with duration") result = run_simulator(exe, game_dir, scenery, ini, physicslog, - duration, float(case.get("timeout", 600)), watch, say) + duration, float(case.get("timeout", 600)), watch, say, + expect_rows=with_physicslog and not own_vehicle) + # a case that asked for no geometry cache (file.binary.terrain no) leaves none of an earlier run behind + if any(line.split()[:2] == ["file.binary.terrain", "no"] for line in case.get("ini", [])): + scenery_cache(game_dir, name).unlink(missing_ok=True) # the logs are ours alone (named after the case scenery), move them out of the game dir for kind, path in result.logs.items(): @@ -672,6 +717,13 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool # other trains of the case with a driver, named _, log too for other in physicslog.parent.glob(f"*_{vehicle}.dat"): shutil.move(other, out / other.name) + # on a mission of the base scenery every train with a driver logs under its own name, the road vehicles + # too (250 files and 740 MB after 900 s of Wrzosy): the ones written in this run are removed, nothing + # checks them (so such a case can't share the game dir with another run at the time) + if own_vehicle and with_physicslog: + for other in physicslog.parent.glob("*.dat"): + if other.stat().st_mtime >= started: + other.unlink() # the black box is named after the case scenery too if result.blackbox: result.blackbox = Path(shutil.move(result.blackbox, out / f"{vehicle}.blackbox")) @@ -701,7 +753,7 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool if result.failure: say(f" FAIL {result.failure}") ok = False - if not result.rows and case.get("checks"): + if not result.rows and needs_physicslog: if not result.failure: say(f" FAIL no physicslog for '{vehicle}'") return False @@ -751,6 +803,10 @@ def main() -> int: help="with --watch: simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 1)") ap.add_argument("-j", "--jobs", type=int, default=1, help="cases run at once, each in a simulator of its own (default 1)") + ap.add_argument("--seed", help="seed of the simulator's random numbers for this run (randomseed), a number or a " + "word; the default is the fixed one of the test mode. For bugs that show up only sometimes") + ap.add_argument("--slow", action="store_true", + help="with no cases named: run the ones marked slow too (they are skipped otherwise)") args = ap.parse_args() if not args.game_dir: @@ -763,6 +819,12 @@ def main() -> int: missing = [n for n in names if not (CASES_DIR / f"{n}.json").exists()] if missing: sys.exit("no such case: " + ", ".join(missing)) + # a case marked slow (a whole mission on a big scenery, many minutes) runs when named, or with --slow + if not args.cases and not args.slow: + slow = [n for n in names if load_case(n).get("slow")] + if slow: + names = [n for n in names if n not in slow] + print(f"skipped {len(slow)} slow case(s), run them by name or with --slow: {', '.join(slow)}") started = time.monotonic() results = {} @@ -770,7 +832,7 @@ def main() -> int: def say(line, progress=False): print(line, flush=True) for n in names: - results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say) + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) else: # each case prints its block when it is done, so parallel output does not interleave def job(n): @@ -778,20 +840,21 @@ def main() -> int: def say(line, progress=False): if not progress: lines.append(line) - ok = run_case(n, exe, game_dir, args.timespeed, args.watch, say) - return n, ok, lines + status = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) + return n, status, lines with ThreadPoolExecutor(max_workers=args.jobs) as pool: for n in names: print(f"started {n}", flush=True) for fut in as_completed([pool.submit(job, n) for n in names]): - n, ok, lines = fut.result() + n, status, lines = fut.result() print("\n".join(lines), flush=True) - results[n] = ok + results[n] = status print(f"\n=== summary ({time.monotonic() - started:.0f}s)") for n in names: - print(f" {'PASS' if results[n] else 'FAIL'} {n}") - return 0 if all(results.values()) else 1 + print(f" {results[n]:5} {n}") + # a known failure keeps the suite green; one that stopped failing doesn't, so that its mark gets removed + return 0 if all(status in ("PASS", "XFAIL") for status in results.values()) else 1 if __name__ == "__main__": From ca23831bb2b783ec9c2eb7178a3bc90f60d1eb16 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 04:47:03 +0100 Subject: [PATCH 02/59] test(scenarios): cases from the reports eu07/maszyna#421, #506, #524, #525 Six slow cases, each a mission of a scenery of the game with every train driven by AI: - wrzosy_pxe336080_couples (#524): the locomotive, given the orders the player's hands stand for, couples to the rake in the Wolica depot and takes it out. Passes. - baltyk_skm1_roj55324_shunting_signal, baltyk_skm1_roj55321_departure (#525): the unit on the siding gets its shunting signal once the shunter beside it has moved, the one in the platform leaves on time. Pass, with 4 and 3 seeds. - l053_poranek_tme222158_debica (#421): xfail, the train is never let into Debica: the AI of another locomotive passes the shunting signal Tm4 at stop and the station waits for it for good. - l053_poranek_tme222158_debica_et21 (#421, with the ET21 of the report): xfail, the ET21 stops past the end of the overhead wire at Debica Towarowa and its driver never restarts it. - l053_poludnie_roj32134_debica (#506): both trains of the mission run and end at Debica. Passes. --- .../cases/baltyk_skm1_roj55321_departure.json | 18 +++++++++ .../baltyk_skm1_roj55324_shunting_signal.json | 18 +++++++++ .../cases/l053_poludnie_roj32134_debica.json | 24 ++++++++++++ .../cases/l053_poranek_tme222158_debica.json | 31 +++++++++++++++ .../l053_poranek_tme222158_debica_et21.json | 37 ++++++++++++++++++ tests/scenarios/cases/mission_state_probe.scn | 13 +++++++ .../cases/wrzosy_pxe336080_couple.scn | 39 +++++++++++++++++++ .../cases/wrzosy_pxe336080_couples.json | 26 +++++++++++++ 8 files changed, 206 insertions(+) create mode 100644 tests/scenarios/cases/baltyk_skm1_roj55321_departure.json create mode 100644 tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json create mode 100644 tests/scenarios/cases/l053_poludnie_roj32134_debica.json create mode 100644 tests/scenarios/cases/l053_poranek_tme222158_debica.json create mode 100644 tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json create mode 100644 tests/scenarios/cases/mission_state_probe.scn create mode 100644 tests/scenarios/cases/wrzosy_pxe336080_couple.scn create mode 100644 tests/scenarios/cases/wrzosy_pxe336080_couples.json diff --git a/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json new file mode 100644 index 000000000..98b9c8119 --- /dev/null +++ b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json @@ -0,0 +1,18 @@ +{ + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts in the platform of Baltyk Glowny (EN71-014ra, ROJ55321, departure 10:34): the exit signal has to clear and the unit has to leave. Standing for 10 minutes ends the test as standstill.", + "base_scenery": "baltyk_skm1.scn", + "strip_trainsets": false, + "vehicle": "EN71-014ra", + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.standstill 600", + "test.fail_if_stop_overran no" + ], + "duration": 900, + "expect": "timeout", + "timeout": 900 +} diff --git a/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json new file mode 100644 index 000000000..a8fa0e7cc --- /dev/null +++ b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json @@ -0,0 +1,18 @@ +{ + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts on the siding of Baltyk Towarowy next to the shunter (EN90-009A, ROJ55324): the station lets the unit into the platforms once its shunter 6Dg-1244, on the track beside it, has done its first moves (4 minutes after the start), and out to Alakowice at 10:42. A shunter that gets stuck leaves the unit at the shunting signal for good: standing for 15 minutes ends the test as standstill.", + "base_scenery": "baltyk_skm1.scn", + "strip_trainsets": false, + "vehicle": "EN90-009A", + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.standstill 900", + "test.fail_if_stop_overran no" + ], + "duration": 1800, + "expect": "timeout", + "timeout": 900 +} diff --git a/tests/scenarios/cases/l053_poludnie_roj32134_debica.json b/tests/scenarios/cases/l053_poludnie_roj32134_debica.json new file mode 100644 index 000000000..7ed64bf96 --- /dev/null +++ b/tests/scenarios/cases/l053_poludnie_roj32134_debica.json @@ -0,0 +1,24 @@ +{ + "description": "eu07/maszyna#506, L053 poludnie, ROJ23133 Debica - Rudawa and ROJ32134 back (EN57-1797ra): the unit runs both trains among the scenery's traffic and ends at Debica (the station's state cell of ROJ32134 says done).", + "base_scenery": "l053_poludnie.scn", + "strip_trainsets": false, + "vehicle": "EN57-1797ra", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_roj32134_stat", + "state": "d * *", + "reason": "roj32134_ended_at_debica" + }, + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 7200", + "test.standstill 1500", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600 +} diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json new file mode 100644 index 000000000..bad10aee4 --- /dev/null +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -0,0 +1,31 @@ +{ + "description": "eu07/maszyna#421, L053 poranek, TME222158: the locomotive brings the wagons with steel coils from Debica Towarowa to Debica, uncouples (Shunt 0 0 from the scenery), shunts on the Ms2 signals while the station's SM42 takes the wagons away, couples to its next train and gets the exit signal to Sandomierz (step 6 of the station's state cell).", + "base_scenery": "l053_poranek.scn", + "strip_trainsets": false, + "vehicle": "ET22-654", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_tme222158_stat", + "state": "* 6 *", + "reason": "tme222158_got_the_exit_signal_at_debica" + }, + "slow": true, + "xfail": "eu07/maszyna#421 is not reached: with every train driven by AI Debica jams 4 minutes after the start, the AI of EP07-338'16 passes the shunting signal Tm4 at stop at 29 km/h and stops 20 m beyond the checkpoint before it (tor1834:event0), so RPE23113 never reports there and TME222158 is never let into the station", + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 6000", + "test.standstill 2100", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600, + "checks": [ + { + "type": "log_contains", + "pattern": "Uncoupling \\[ET22-654\\]: uncoupled" + } + ] +} diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json new file mode 100644 index 000000000..49c1ba3c2 --- /dev/null +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -0,0 +1,37 @@ +{ + "description": "eu07/maszyna#421 as reported in 2021, with an ET21 on TME222158 (the scenery has an ET22 there now): the same run as l053_poranek_tme222158_debica, the locomotive of the mission replaced.", + "base_scenery": "l053_poranek.scn", + "strip_trainsets": false, + "replace": [ + [ + "node -1 0 ET22-654 dynamic pkp\\et22_v3 201E-654 201E -1 headdriver 3 0 enddynamic", + "node -1 0 ET21-367 dynamic pkp\\et21_v2 ET21-367 3e2 -1 headdriver 3 0 enddynamic" + ] + ], + "vehicle": "ET21-367", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_tme222158_stat", + "state": "* 6 *", + "reason": "tme222158_got_the_exit_signal_at_debica" + }, + "slow": true, + "xfail": "eu07/maszyna#421: the ET21 stands for good at Debica Towarowa with the shunting signal at Ms2. Running round the wagons it stops on the headshunt 20 m past the end of the overhead wire (the wire ends at z 4804 over tor2466, the locomotive stands at z 4786), loses power, and its driver never gets out of Prepare_engine; the ET22 the scenery has there now gets through", + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 6000", + "test.standstill 2100", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600, + "checks": [ + { + "type": "log_contains", + "pattern": "Uncoupling \\[ET21-367\\]: uncoupled" + } + ] +} diff --git a/tests/scenarios/cases/mission_state_probe.scn b/tests/scenarios/cases/mission_state_probe.scn new file mode 100644 index 000000000..fd158dab3 --- /dev/null +++ b/tests/scenarios/cases/mission_state_probe.scn @@ -0,0 +1,13 @@ +// added by tests/scenarios/run.py to a scenery that keeps its own trainsets (strip_trainsets false): the +// case tests one of the scenery's missions, with every train driven by AI. +// the sceneries of this kind steer their stations with state cells, one per train (text and two values, +// e.g. "a 6 *": the route of step 6 is set for the train, "d * *": the train is done at this station). +// the probe looks at the cell {{cell}} every 5 s from the start on and reports the pass once it holds +// {{state}}. no fail event: a train that never gets there ends the test with the standstill or the +// timeout of the test mode. +// the two events calling each other are the loop these sceneries use themselves (e.g. bal_obsluga_stacji); +// an event with "onstart" in its name is queued when the scenery starts. +event onstart_autotest_probe multiple 30 none autotest_probe endevent +event autotest_probe multiple 0 {{cell}} autotest_pass else autotest_probe_wait condition memcompare {{state}} endevent +event autotest_probe_wait multiple 5 none autotest_probe endevent +event autotest_pass UpdateValues 0 __test.result {{reason}} 1 * endevent diff --git a/tests/scenarios/cases/wrzosy_pxe336080_couple.scn b/tests/scenarios/cases/wrzosy_pxe336080_couple.scn new file mode 100644 index 000000000..c0d504d57 --- /dev/null +++ b/tests/scenarios/cases/wrzosy_pxe336080_couple.scn @@ -0,0 +1,39 @@ +// added by tests/scenarios/run.py to wrzosy_pxe336080.scn, which keeps its own trainsets: the mission of +// eu07/maszyna#524. EU07-234 runs light from final_2t839 through the Wolica depot to the rake of 12 coaches +// pxe_1 .. pxe_12 (linia053_wrzosy/pxe336080_dekoracje.scm, "trainset none woa_odst009 304 0"), has to +// couple to it and take it out of the depot. +// +// the scenery gives the locomotive no order at all: its trainset has velocity 0, so with nobody in the cab +// its driver sleeps in Wait_for_orders, and nothing in the scenery tells it to couple, the player does that +// by hand. the two orders the player's hands stand for are given here. +// +// 1. a minute after the start (the scenery sets the way and the shunting signals at 50-55 s): shunt, as +// the signals say (Shunt -1 0). PutValues goes to the vehicle that set the event off, so it hangs on +// event0 of the track the locomotive stands on (the three its 16 m may reach); event0 comes again and +// again while it stands there, the cell lets the order through once. +// the first order is not the one to couple, on purpose: a driver whose first order is Connect never +// releases the hand brake the locomotive starts with, and pulls against it for good (CheckVehicles() +// leaves AutoRewident() out for Connect). +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event final_2t838:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event final_2t839:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event final_2t840:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// 2. on the last track before the rake, in the direction the locomotive comes from (event2 of +// woa_lokom007, some 35-45 m short of the first coach): couple to the consist standing ahead with the +// coupler and the brake hose (3), turn round and wait for the shunting signal. it is the order these +// sceneries give their AI shunters (dos_sm42_przypnij). +event woa_lokom007:event2 PutValues 0 none 0 0 0 Shunt -2 -3 endevent + +// 330 s after the locomotive ran over lok_woa005 towards the rake the scenery sets the way out +// (lok_woa005:event2 -> PXE_gotowy -> pxe_manewry_ruszaj), coupled or not. it leads back over lok_woa005, +// towards its point 1. every vehicle going that way is counted (eventall1); the locomotive alone makes 1, +// so the second vehicle is a coach of the rake, coupled and pulled. the test ends there, with the train +// still moving (test.no_movement_before_pass no). +node -1 0 autotest_left memcell 0 0 0 left 0 0 none endmemcell +event lok_woa005:eventall1 multiple 0 none autotest_count autotest_judge endevent +event autotest_count AddValues 0 autotest_left * 1 0 endevent +event autotest_judge multiple 0 autotest_left autotest_pass condition memcompare * 2 * endevent +event autotest_pass UpdateValues 0 __test.result the_rake_left_the_depot_behind_the_locomotive 1 * endevent diff --git a/tests/scenarios/cases/wrzosy_pxe336080_couples.json b/tests/scenarios/cases/wrzosy_pxe336080_couples.json new file mode 100644 index 000000000..11d385871 --- /dev/null +++ b/tests/scenarios/cases/wrzosy_pxe336080_couples.json @@ -0,0 +1,26 @@ +{ + "description": "eu07/maszyna#524, Wrzosy PXE336080: EU07-234 runs light to the rake of 12 coaches in the Wolica depot, gets the order to couple (the player's hand, the scenery gives none), has to couple to the first coach and leave the depot with the rake behind it.", + "base_scenery": "wrzosy_pxe336080.scn", + "strip_trainsets": false, + "vehicle": "EU07-234", + "fragment": "wrzosy_pxe336080_couple.scn", + "slow": true, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 1800", + "test.standstill 900", + "test.fail_if_stop_overran no", + "test.no_movement_before_pass no" + ], + "expect": "pass", + "timeout": 1200, + "checks": [ + { + "type": "couples", + "vehicle": "EU07-234", + "other": "pxe_1" + } + ] +} From c5676629132eed0358c5f95fe5ef3f83ea79b641 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 05:26:57 +0100 Subject: [PATCH 03/59] fix(ai): release the hand brake when the first order is Connect CheckVehicles() ran the inspector (AutoRewident(), which also releases the hand and spring brakes of the AI's train) only under Shunt, Loose_shunt, Obey_train and Bank. A locomotive loaded cold (trainset velocity 0) starts with its hand brake on; when the first order it drives under is Connect (Shunt x,y with a coupler, e.g. Shunt -2 -3 after Prepare_engine), it pulled against the hand brake for good and never reached the wagons. The inspector now also runs under Connect, except for the look the AI takes at the moment it couples (CheckVehicles(Connect)): the wagons just coupled keep their hand brakes until the order after the coupling looks at the new train, as before, so those to be left standing again (Shunt x,-y) stay braked. Wagons not yet coupled are never touched: AutoRewident() goes over the vehicles coupled to the AI's train only. The rule is brake_setting::inspects_train(), with a unit test. --- tests/unit/test_brake_setting.cpp | 23 +++++++++++++++++++++++ vehicle/Driver.cpp | 2 +- vehicle/brakesetting.cpp | 4 ++++ vehicle/brakesetting.h | 9 +++++++++ 4 files changed, 37 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index 5034bf3c5..39b0e2117 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -474,6 +474,29 @@ TEST_CASE("brake setting: a bank engine's run counts as a train, shunting doesn' CHECK(false == brake_setting::is_cut_out(car.mover())); } +TEST_CASE("brake setting: the AI looks at its train under the orders it drives it under, Connect included") { + CHECK(brake_setting::inspects_train(Shunt, false)); + CHECK(brake_setting::inspects_train(Loose_shunt, false)); + CHECK(brake_setting::inspects_train(Obey_train, false)); + CHECK(brake_setting::inspects_train(Bank, false)); + // the run up to the wagons: a locomotive standing cold has its hand brake to release first + CHECK(brake_setting::inspects_train(Connect, false)); + CHECK(brake_setting::inspects_train(Connect | Change_direction, false)); + // but not at the coupling: the wagons just coupled wait for the next order, which may leave some of them + CHECK(false == brake_setting::inspects_train(Connect, true)); + CHECK(false == brake_setting::inspects_train(Connect | Change_direction, true)); + // a train run with a coupling on it is still a train run + CHECK(brake_setting::inspects_train(Obey_train | Connect, true)); + CHECK(brake_setting::inspects_train(Shunt, true)); + // standing, starting or stopping the engine, turning round, uncoupling: nothing to look at + CHECK(false == brake_setting::inspects_train(Wait_for_orders, false)); + CHECK(false == brake_setting::inspects_train(Prepare_engine, false)); + CHECK(false == brake_setting::inspects_train(Release_engine, false)); + CHECK(false == brake_setting::inspects_train(Change_direction, false)); + CHECK(false == brake_setting::inspects_train(Disconnect, false)); + CHECK(false == brake_setting::inspects_train(Jump_to_first_order, false)); +} + TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of an LSt kept") { // the inspector sets R+Mg (Cw-1 §18.2), the bits of R and Mg together: the valves test the bit of R, not // the whole setting, so the high stage of R at speed stays on with Mg. the EU07's LSt given an Mg here diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb74344bf..ce41ee780 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2876,7 +2876,7 @@ bool TController::CheckVehicles(TOrders user) = 0; } - if( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) { + if( brake_setting::inspects_train( OrderCurrentGet(), user == Connect ) ) { // nastawianie hamulca do jazdy pociągowej AutoRewident(); /* diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index ceffe3180..918da3d02 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -177,6 +177,10 @@ bool runs_as_train(int const Orders) { return (Orders & (Obey_train | Bank)) != 0; } +bool inspects_train(int const Orders, bool const Coupled) { + return (Orders & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 || ((Orders & Connect) != 0 && false == Coupled); +} + bool at_standstill(double const Velocity) { return std::abs(Velocity) < EU07_AI_MOVEMENT; } diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index cb7ad5225..e3e5b4974 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -65,6 +65,15 @@ std::vector choose(std::vector const &Consist, bool Train); // train run too (with the braking of a train). Orders is the order of the AI (TOrders) bool runs_as_train(int Orders); +// the AI has the inspector look at its train (TController::AutoRewident(): the brake settings, and the hand and +// spring brakes of the train released) under the orders it drives the train under: shunting, loose shunting, the +// train run, banking, and the run up to the wagons to couple to (Connect), which a locomotive left standing cold, +// with its hand brake on, would make pulling against it. Coupled: the look the AI takes at the moment it couples +// (CheckVehicles(Connect)); Connect doesn't count for it, so the wagons just coupled keep their hand brakes until +// the order after the coupling looks at the new train, as before: those of them to be left standing again +// (Shunt x,-y) stay braked. Orders is the order of the AI (TOrders) +bool inspects_train(int Orders, bool Coupled); + // the train stands for the inspector: slower than the AI takes for a deliberate movement (EU07_AI_MOVEMENT). // the AI looks at the train while it still creeps to a stop (at a W4, or switching from shunting to the train // run), so a stricter threshold would miss those checks; a train really on the run (an order changed mid-run) From ea4409042b47743a1a876f21066cadd7c80226ba Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 05:26:57 +0100 Subject: [PATCH 04/59] test(scenarios): a cold EU07 couples to coaches as its first order eu07_td_cold_connect: an EU07 with a hand brake (4E-ZEZ_GREY) stands cold on td.scn with two coaches 45 m ahead; event0 of its track gives it Shunt -1 3 once. It has to start the engine, couple (Connect is the first order it drives under) and push the coaches onto tor1k. Before the fix it stands pulling against its hand brake and the case ends as a standstill. --- tests/scenarios/README.md | 9 ++++++ .../scenarios/cases/eu07_td_cold_connect.json | 28 +++++++++++++++++++ tests/scenarios/cases/td_cold_connect.scn | 28 +++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 tests/scenarios/cases/eu07_td_cold_connect.json create mode 100644 tests/scenarios/cases/td_cold_connect.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index ea5ebc89b..71c29cbd8 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -230,6 +230,15 @@ couple and neither shows up: the black box has to have the last car of the stand writes nothing to the log when couplers catch). Nothing reports a result, so both end on the 60 s test timeout. +`eu07_td_cold_connect` (fragment `td_cold_connect.scn`) has an EU07 with a hand brake +(`4E-ZEZ_GREY`; the plain `4e` has none) standing cold on track 1 of Stacja1 (trainset velocity 0, +so it starts with the hand brake on) and two coaches standing 45 m ahead of it. Its driver sleeps +until `event0` of its track gives it, once, `Shunt -1 3`: start the engine, couple to the consist +ahead (Connect, the first order it drives under), go on shunting. It passes when the first coach, +pushed, runs onto `tor1k` (`eventall2`), with the train still moving, and the black box has the +locomotive coupled to the coaches (it couples about 70 s after the start). A driver that leaves its +hand brake on under Connect pulls against it for good and the case ends as a standstill after 300 s. + Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of diff --git a/tests/scenarios/cases/eu07_td_cold_connect.json b/tests/scenarios/cases/eu07_td_cold_connect.json new file mode 100644 index 000000000..26c975861 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_cold_connect.json @@ -0,0 +1,28 @@ +{ + "description": "EU07 with a hand brake (4E-ZEZ_GREY) on td.scn, standing cold with the hand brake on, gets the order to couple to the two coaches standing 45 m ahead (Shunt -1 3): after starting the engine it has to release its hand brake, run up to the coaches, couple and push them on. Connect is the first order the AI drives under.", + "base_scenery": "td.scn", + "fragment": "td_cold_connect.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4E-ZEZ-234 4E-ZEZ_GREY", + "rake": [ + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "tdo_n1725": "event0 autotest_wake", + "tor1k": "eventall2 autotest_pass" + }, + "test_config": [ + "test.timeout 900", + "test.standstill 300", + "test.no_movement_before_pass no" + ], + "expect": "pass", + "timeout": 900, + "checks": [ + { "type": "couples", "vehicle": "{{vehicle}}", "other": "{{vehicle}}_c2" }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/td_cold_connect.scn b/tests/scenarios/cases/td_cold_connect.scn new file mode 100644 index 000000000..3ea9306c6 --- /dev/null +++ b/tests/scenarios/cases/td_cold_connect.scn @@ -0,0 +1,28 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// on the straight track 1 of Stacja1: a locomotive with an AI driver stands cold (trainset velocity 0, so +// it starts "Braked": hand brake on, battery off, pantographs down) on tdo_n1725, its front 60 m past +// point 1 of the track, facing point 2; the rake (vars.rake) stands, braked as well and with nobody in it, +// on tdo_n1734 ahead of it, its front 60 m past point 1 of that track, some 45 m in front of the +// locomotive (two coaches of 26.4 m). +trainset none tdo_n1725 60.0 0.0 +node -1 0 {{vehicle}} dynamic {{locomotive}} 0 headdriver 0 0 enddynamic +endtrainset + +trainset none tdo_n1734 60.0 0.0 +{{rake}} +endtrainset + +// a driver of a standing trainset sleeps on Wait_for_orders until something wakes it. event0 of the +// locomotive's track (the case's track_events) runs while it stands there and gives it, once (the memory +// cell), the order a scenery gives a shunter to couple: Shunt -1 3, couple to the consist standing ahead +// with the coupler and the brake hose and go on shunting. the engine is cold, so the AI starts it +// first: its orders are Prepare_engine, Connect, Shunt, and Connect is the first one it drives under. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 3 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// the rake, pushed by the locomotive, runs onto tor1k (40 m ahead of its first coach) towards its +// point 2: eventall2 of tor1k (the case's track_events) passes the test, which ends there with the train +// still moving (test.no_movement_before_pass no), 100 m short of the exit signal at the end of tor1k. +event autotest_pass UpdateValues 0 __test.result the_rake_was_coupled_and_pushed 1 * endevent From 2cd646dbb6ed4552b8c161d35b4b430b2edd6e9e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 06:59:56 +0100 Subject: [PATCH 05/59] test(scenarios): the L053 poranek cases look for the uncoupling under the lower-case name the log writes --- tests/scenarios/cases/l053_poranek_tme222158_debica.json | 2 +- tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json index bad10aee4..6fbc141e7 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -25,7 +25,7 @@ "checks": [ { "type": "log_contains", - "pattern": "Uncoupling \\[ET22-654\\]: uncoupled" + "pattern": "Uncoupling \\[et22-654\\]: uncoupled" } ] } diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json index 49c1ba3c2..4f169fea7 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -31,7 +31,7 @@ "checks": [ { "type": "log_contains", - "pattern": "Uncoupling \\[ET21-367\\]: uncoupled" + "pattern": "Uncoupling \\[et21-367\\]: uncoupled" } ] } From 59a9df6aa383ed95faf9885336579c257c16d063 Mon Sep 17 00:00:00 2001 From: maj00r Date: Thu, 12 Nov 2026 20:59:16 +0100 Subject: [PATCH 06/59] fix(ci): build the Linux game with libcurl, so the editor can download maps The Linux job never installed libcurl's headers, so find_package(CURL QUIET) missed it and the game was built without EU07_WITH_CURL: the editor showed "no http client in this build" instead of the orthophoto, the terrain model and the topo map. bundle_runtime_libs.cmake copies libcurl and its dependencies next to the game with the other bundled libraries. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build_bin.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 41c2c35f0..041eea4f0 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -231,6 +231,7 @@ jobs: libluajit-5.1-dev \ libserialport-dev \ libsndfile1-dev \ + libcurl4-openssl-dev \ xorg-dev \ libxkbcommon-dev \ libwayland-dev \ From acda6562cd798c05275699d14ff546cfbcaed46d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 15:23:01 +0100 Subject: [PATCH 07/59] fix(scripting): sandbox the scenery Lua scripts like the Lua screens The scenery scripts (lua in the .scn) ran in a state with all of LuaJIT's libraries (io, os, ffi, debug, require, load*), loaded with luaL_dofile from any path, '..' and absolute ones included, and their errors in event handlers went through an unprotected lua_call. - scripting/luasandbox.{h,cpp}: what the Lua states share: the safe library set (moved from lua_program::open_libraries), loading a text-only chunk (moved from load_chunk), reading a script from a folder through the screens' path check (regular file, at most 16 MB), running it under pcall, and a clock-only os table (time, clock, difftime, date with the C89 conversions; MSVC's strftime ends the program on an unknown one). - lua.cpp: the scenery state gets the safe set and the clock; interpret() takes the scenery folder and the file and logs a refused or failing script with its file name; event handlers run under pcall and are logged with the event name; the scriptapi functions check their string argument (luaL_checkstring) instead of making a std::string from NULL; a memcell table without str updates the text to "" instead of from NULL. - luaprogram.cpp: calls the shared helpers, no change for the screens. - eu07.ini lua.fulllibraries (default no) gives trusted sceneries all libraries back. Documented in script_screens_doc.md. - tests/unit/test_lua_sandbox.cpp: 8 cases for the shared sandbox. --- CMakeLists.txt | 3 +- script_screens_doc.md | 22 +++ scripting/lua.cpp | 64 ++++--- scripting/lua.h | 5 +- scripting/luaprogram.cpp | 32 +--- scripting/luasandbox.cpp | 167 +++++++++++++++++ scripting/luasandbox.h | 49 +++++ simulation/simulationstateserializer.cpp | 3 +- tests/unit/CMakeLists.txt | 2 +- tests/unit/test_lua_sandbox.cpp | 218 +++++++++++++++++++++++ utilities/Globals.cpp | 9 + utilities/Globals.h | 1 + 12 files changed, 520 insertions(+), 55 deletions(-) create mode 100644 scripting/luasandbox.cpp create mode 100644 scripting/luasandbox.h create mode 100644 tests/unit/test_lua_sandbox.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..1b73b0805 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -384,7 +384,8 @@ endif() if (WITH_LUA) set(DEFINITIONS ${DEFINITIONS} "WITH_LUA") - set(SOURCES ${SOURCES} "scripting/lua.cpp") + # the scenery scripts (lua.cpp) and the Lua screens (luaprogram.cpp) share the sandbox of luasandbox.cpp + set(SOURCES ${SOURCES} "scripting/lua.cpp" "scripting/luasandbox.cpp") endif() # the script screens (scripting/scriptscreens.cpp), with the Lua and the WebAssembly runtime when they're built diff --git a/script_screens_doc.md b/script_screens_doc.md index 52ccc9ced..09a4c2638 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -208,3 +208,25 @@ clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry -o ekran.wasm ekran.c Any language that compiles to WebAssembly works the same way (Rust `wasm32-unknown-unknown`, Zig, AssemblyScript), as long as the module imports nothing but the `eu07` functions above. + +## Scenery scripts + +A scenery runs a Lua script with `lua ` in its `.scn`, while the scenery loads. The script registers events +and works with memcells, tracks and vehicles through the table `eu07.events` (`event_create`, `event_dispatch`, +`memcell_update`, `writelog` and the rest, see `scripting/lua.cpp`). It shares the sandbox of the Lua screens: + +- the file is a path relative to the scenery folder (`scenery/`), and stays inside it: no `..`, no drive, no leading + `/`. It is text, of at most 16 MB; precompiled code is not loaded; +- the script gets the base library, `table`, `string`, `math` and `bit`, and of `os` only the clock: `os.time`, + `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no + `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; +- a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on + loading. An event handler that fails is logged with the name of the event, and the simulation goes on. + +A script written for the earlier full libraries stops at the first call to one of them (`attempt to index global +'io' (a nil value)` in the log). For a scenery you trust, `eu07.ini` can give the scripts all of LuaJIT's libraries +again: + +| key | default | meaning | +|---------------------|---------|------------------------------------------------------------------------------------------| +| `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 14ecbb75d..0854579d9 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -5,6 +5,7 @@ #include "world/MemCell.h" #include "vehicle/Driver.h" #include "simulation/simulation.h" +#include "scripting/luasandbox.h" lua::lua() { @@ -12,7 +13,10 @@ lua::lua() if (!state) throw std::runtime_error("cannot create lua state"); lua_atpanic(state, atpanic); - luaL_openlibs(state); + // sandboxed as the script screens are: no io, ffi, debug, require or load*, and of os only the clock. + // lua.fulllibraries in eu07.ini opens the rest when the scenery loads its first script (interpret()) + lua_sandbox::open_safe_libraries(state); + lua_sandbox::open_clock_library(state); static constexpr luaL_Reg api[] = { @@ -51,21 +55,29 @@ lua::~lua() std::string lua::get_error() const { - return lua_tostring(state, -1); + auto const *error = lua_tostring(state, -1); + return error ? error : "unknown error"; } -void lua::interpret(const std::string& file) const +void lua::interpret(const std::string &folder, const std::string &file) { - if (luaL_dofile(state, file.c_str())) { - std::string str = lua_tostring(state, -1); - ErrorLog("lua: Runtime error: " + str, logtype::lua); + if (Global.lua_fulllibraries && !full_libraries) { + // all of LuaJIT's libraries, as before the sandbox: the scripts may then reach files, programs and ffi + luaL_openlibs(state); + full_libraries = true; + WriteLog("lua: lua.fulllibraries is on, the scenery scripts run with all libraries (io, os, ffi, require...)", logtype::lua); + } + // a relative path inside the scenery folder, a file of text, run in protected mode: a script that fails stops + // there, and the scenery goes on loading + if (auto const error = lua_sandbox::run_script_file(state, folder, file)) { + ErrorLog("lua: " + *error, logtype::lua); } } int lua::atpanic(lua_State *s) { - std::string err = lua_tostring(s, -1); - ErrorLog("lua: Runtime error: " + err, logtype::lua); + auto const *err = lua_tostring(s, -1); + ErrorLog(std::string("lua: Runtime error: ") + (err ? err : "unknown error"), logtype::lua); return 0; } @@ -81,7 +93,12 @@ void lua::dispatch_event(lua_State *L, const int handler, basic_event *event, co lua_rawgeti(L, LUA_REGISTRYINDEX, handler); lua_pushlightuserdata(L, event); lua_pushlightuserdata(L, const_cast(activator)); - lua_call(L, 2, 0); + // in protected mode: a handler that fails is logged, and the simulation goes on + if (lua_pcall(L, 2, 0, 0) != 0) { + auto const *error = lua_tostring(L, -1); + ErrorLog("lua: event " + (event ? event->m_name : std::string("?")) + ": " + (error ? error : "unknown error"), logtype::lua); + lua_pop(L, 1); + } } void lua::push_memcell_values(lua_State *L, const TMemCell *mc) @@ -103,7 +120,8 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) // For negative indices, we need to account for the extra item that is the key name/value extracted from the table. if (idx < 0) idx--; - memcell_values mc{nullptr, 0.0, 0.0}; + // no text in the table is an empty one: the memcell and the vehicle take the text as a string + memcell_values mc{"", 0.0, 0.0}; lua_pushstring(L, "str"); lua_gettable(L, idx); if (lua_isstring(L, -1)) @@ -124,7 +142,7 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) int lua::scriptapi_event_create(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); double delay = lua_tonumber(L, 2); double randomdelay = lua_tonumber(L, 3); lua_pushvalue(L, 4); @@ -144,7 +162,7 @@ int lua::scriptapi_event_create(lua_State *L) int lua::scriptapi_event_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) { @@ -157,7 +175,7 @@ int lua::scriptapi_event_find(lua_State *L) int lua::scriptapi_event_exists(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); lua_pushboolean(L, foundevent != nullptr); return 1; @@ -186,7 +204,7 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); auto *activator = static_cast(lua_touserdata(L, 2)); double delay = lua_tonumber(L, 3); basic_event *foundevent = simulation::Events.FindEvent(name); @@ -199,7 +217,7 @@ int lua::scriptapi_event_dispatch_n(lua_State *L) int lua::scriptapi_track_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -223,7 +241,7 @@ int lua::scriptapi_track_isoccupied(lua_State *L) int lua::scriptapi_track_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -236,7 +254,7 @@ int lua::scriptapi_track_isoccupied_n(lua_State *L) int lua::scriptapi_isolated_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -260,7 +278,7 @@ int lua::scriptapi_isolated_isoccupied(lua_State *L) int lua::scriptapi_isolated_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -298,7 +316,7 @@ int lua::scriptapi_dynobj_putvalues(lua_State *L) int lua::scriptapi_memcell_find(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); if (mc) { @@ -318,7 +336,7 @@ int lua::scriptapi_memcell_read(lua_State *L) int lua::scriptapi_memcell_read_n(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); push_memcell_values(L, mc); if (!mc) @@ -338,7 +356,7 @@ int lua::scriptapi_memcell_update(lua_State *L) int lua::scriptapi_memcell_update_n(lua_State *L) { - std::string mstr = lua_tostring(L, 1); + std::string mstr = luaL_checkstring(L, 1); auto [str, num1, num2] = get_memcell_values(L, 2); TMemCell *mc = simulation::Memory.find(mstr); if (mc) @@ -359,14 +377,14 @@ int lua::scriptapi_random(lua_State *L) int lua::scriptapi_writelog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); WriteLog("lua: log: " + txt, logtype::lua); return 0; } int lua::scriptapi_writeerrorlog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); ErrorLog("lua: log: " + txt, logtype::lua); return 0; } diff --git a/scripting/lua.h b/scripting/lua.h index 07d729264..8663103df 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -10,6 +10,7 @@ struct memcell_values { const char *str; double num1; double num2; }; class lua { lua_State *state; + bool full_libraries = false; // lua.fulllibraries: all of LuaJIT's libraries opened static int atpanic(lua_State *s); @@ -41,7 +42,9 @@ public: ~lua(); std::string get_error() const; - void interpret(const std::string& file) const; + // runs the script file, a relative path inside folder (the scenery folder), sandboxed (scripting/luasandbox.h). + // a script that can't be read or fails is logged + void interpret(const std::string &folder, const std::string &file); static void unref(lua_State *L, int ref); static void dispatch_event(lua_State *L, int handler, basic_event *event, const TDynamicObject *activator); static void push_memcell_values(lua_State *L, const TMemCell *mc); diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 36d95d271..07fe89a4b 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreenprogram.h" #include "scripting/scriptscreendrawing.h" #include "scripting/scriptscreenkernels.h" +#include "scripting/luasandbox.h" #include "utilities/Logs.h" #include "utilities/dictionary.h" @@ -411,12 +412,7 @@ int api_read_file(lua_State *L) // loads a script as text: precompiled code is refused. leaves the chunk, or an error message, on the stack bool load_chunk(lua_State *L, std::string_view const Code, std::string const &Name) { - if (false == Code.empty() && Code.front() == '\x1b') - { - lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); - return false; - } - return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); + return lua_sandbox::load_text_chunk(L, Code, Name); } // eu07.include(path): runs another script below the script's folder and returns what it returns @@ -724,30 +720,10 @@ void push_state(lua_State *L, dictionary_source const &Input) } } -void open_library(lua_State *L, lua_CFunction Open, char const *Name) -{ - lua_pushcfunction(L, Open); - lua_pushstring(L, Name); - lua_call(L, 1, 0); -} - void lua_program::open_libraries() { - open_library(m_state, luaopen_base, ""); - open_library(m_state, luaopen_table, LUA_TABLIBNAME); - open_library(m_state, luaopen_string, LUA_STRLIBNAME); - open_library(m_state, luaopen_math, LUA_MATHLIBNAME); - open_library(m_state, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) - { - lua_pushnil(m_state); - lua_setglobal(m_state, name); - } - lua_getglobal(m_state, LUA_STRLIBNAME); - lua_pushnil(m_state); - lua_setfield(m_state, -2, "dump"); - lua_pop(m_state, 1); + // base, table, string, math and bit, without what reaches files or loads code + lua_sandbox::open_safe_libraries(m_state); } void lua_program::register_api() diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp new file mode 100644 index 000000000..8d80cdebf --- /dev/null +++ b/scripting/luasandbox.cpp @@ -0,0 +1,167 @@ +/* +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 "scripting/luasandbox.h" + +#include "scripting/scriptscreenrules.h" + +#include +#include +#include + +namespace lua_sandbox +{ + +namespace +{ + +void open_library(lua_State *L, lua_CFunction Open, char const *Name) +{ + lua_pushcfunction(L, Open); + lua_pushstring(L, Name); + lua_call(L, 1, 0); +} + +// the conversions of strftime in C89, which every C library knows. LuaJIT hands each one to strftime on its own +constexpr std::string_view date_conversions{"aAbBcdHIjmMpSUwWxXyYZ%"}; + +// os.date(format, time), the library's own (the upvalue) for a format of known conversions only: the Microsoft +// C library ends the program on one it doesn't know ("%Q", "%#") +int api_date(lua_State *L) +{ + std::size_t length{0}; + auto const *format{luaL_optlstring(L, 1, "%c", &length)}; + std::string_view const text{format, length}; + for (std::size_t idx = 0; idx + 1 < text.size(); ++idx) + { + if (text[idx] != '%') + { + continue; + } + ++idx; + if (date_conversions.find(text[idx]) == std::string_view::npos) + { + return luaL_error(L, "os.date: unknown conversion '%%%c'", text[idx]); + } + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +} // namespace + +void open_safe_libraries(lua_State *L) +{ + open_library(L, luaopen_base, ""); + open_library(L, luaopen_table, LUA_TABLIBNAME); + open_library(L, luaopen_string, LUA_STRLIBNAME); + open_library(L, luaopen_math, LUA_MATHLIBNAME); + open_library(L, luaopen_bit, LUA_BITLIBNAME); + // what reaches files or loads code + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) + { + lua_pushnil(L); + lua_setglobal(L, name); + } + lua_getglobal(L, LUA_STRLIBNAME); + lua_pushnil(L); + lua_setfield(L, -2, "dump"); + lua_pop(L, 1); +} + +void open_clock_library(lua_State *L) +{ + // the whole library, of which a new table takes what only reads the clock + open_library(L, luaopen_os, LUA_OSLIBNAME); + lua_getglobal(L, LUA_OSLIBNAME); + lua_newtable(L); + for (auto const *name : {"time", "clock", "difftime"}) + { + lua_getfield(L, -2, name); + lua_setfield(L, -2, name); + } + lua_getfield(L, -2, "date"); + lua_pushcclosure(L, api_date, 1); + lua_setfield(L, -2, "date"); + // the new table in place of the library: the global, and the one the libraries know as loaded, which + // luaL_openlibs fills up again rather than make a new global + lua_pushvalue(L, -1); + lua_setglobal(L, LUA_OSLIBNAME); + lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_pushvalue(L, -2); + lua_setfield(L, -2, LUA_OSLIBNAME); + // _LOADED, the new table, the library + lua_pop(L, 3); +} + +bool load_text_chunk(lua_State *L, std::string_view const Code, std::string const &Name) +{ + if (false == Code.empty() && Code.front() == '\x1b') + { + lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); + return false; + } + return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); +} + +std::optional read_script_file(std::string const &Folder, std::string_view const Path) +{ + if (false == script_screens::is_safe_relative_path(Path)) + { + return std::nullopt; + } + // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens + // its files + std::filesystem::path const path{Folder + std::string{Path}}; + std::error_code error; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > max_script_file) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; + if (false == file.is_open()) + { + return std::nullopt; + } + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view const Path) +{ + auto const name{Folder + std::string{Path}}; + auto const code{read_script_file(Folder, Path)}; + if (false == code.has_value()) + { + return name + ": not found, not a file, larger than " + std::to_string(max_script_file) + + " bytes, or outside the folder (an absolute path, a drive or '..')"; + } + if (false == load_text_chunk(L, *code, name) || 0 != lua_pcall(L, 0, 0, 0)) + { + std::size_t length{0}; + auto const *message{lua_tolstring(L, -1, &length)}; + std::string result{message != nullptr ? std::string{message, length} : name + ": unknown error"}; + lua_pop(L, 1); + return result; + } + return std::nullopt; +} + +} // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h new file mode 100644 index 000000000..abdd21933 --- /dev/null +++ b/scripting/luasandbox.h @@ -0,0 +1,49 @@ +/* +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 + +// what the Lua states of the game share to run scripts sandboxed: the scenery scripts (scripting/lua.cpp, lua in the +// .scn) and the script screens (scripting/luaprogram.cpp). a sandboxed script reaches no files, no other programs, no +// ffi and no debug library, and loads no code of its own: no require, dofile, load or precompiled chunks + +#include + +#include +#include +#include +#include + +namespace lua_sandbox +{ + +// the largest script file a scenery loads +constexpr std::uintmax_t max_script_file{16 * 1024 * 1024}; + +// the libraries a sandboxed script gets: base, table, string, math and bit, without dofile, loadfile, load, +// loadstring, module, require and string.dump +void open_safe_libraries(lua_State *L); + +// the os table with only what reads the clock: os.time, os.clock, os.difftime and os.date, the last refusing the +// conversions the C library doesn't know (the Microsoft one ends the program on them) +void open_clock_library(lua_State *L); + +// loads Code as text, under the name Name: precompiled code is refused. leaves the chunk, or an error message, on the +// stack +bool load_text_chunk(lua_State *L, std::string_view Code, std::string const &Name); + +// the file Path of Folder, when Path is a relative path inside Folder (no '..', no drive, no leading separator) and +// names a regular file of at most max_script_file bytes. nothing otherwise +std::optional read_script_file(std::string const &Folder, std::string_view Path); + +// reads the script Path of Folder (as read_script_file), loads it as text and runs it in protected mode. nothing when +// it ran, otherwise why it didn't +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view Path); + +} // namespace lua_sandbox diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 9d1e94869..c39870600 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -405,7 +405,8 @@ void state_serializer::deserialize_lua( cParser &Input, scene::scratch_data &Scr std::string file; Input >> file; #ifdef WITH_LUA - simulation::Lua.interpret(Global.asCurrentSceneryPath + file); + // the file is relative to the scenery folder, and stays inside it + simulation::Lua.interpret(Global.asCurrentSceneryPath, file); #else ErrorLog(file + ": lua scripts not supported in this build."); #endif diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index c1ad98f35..e24db024f 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -39,7 +39,7 @@ target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_core) # the script screen host, tested with the real runtimes (test_script_screen_host.cpp) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/scriptscreens.cpp") if (WITH_LUA) - target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") + target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/scripting/luasandbox.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") endif() if (WITH_WASM) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/wasmprogram.cpp") diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp new file mode 100644 index 000000000..f23cb0406 --- /dev/null +++ b/tests/unit/test_lua_sandbox.cpp @@ -0,0 +1,218 @@ +#include "stdafx.h" +#include "doctest.h" + +// the sandbox the Lua states of the game share (scripting/luasandbox.cpp): the scenery scripts (lua in the .scn, +// scripting/lua.cpp) and the script screens (scripting/luaprogram.cpp, tested with the screens in +// test_script_screen_host.cpp). a script gets base, table, string, math and bit, and of os only the clock; it reaches +// no files, no programs, no ffi, loads no code of its own and no precompiled chunk, and a scenery reads its scripts +// only from its own folder + +#ifdef WITH_LUA + +#include "scripting/luasandbox.h" +#include "scratch.h" + +#include +#include +#include +#include + +namespace { + +// a state with the libraries of the scenery scripts +class sandboxed_state { + public: + sandboxed_state() : m_state{luaL_newstate()} { + lua_sandbox::open_safe_libraries(m_state); + lua_sandbox::open_clock_library(m_state); + } + ~sandboxed_state() { lua_close(m_state); } + sandboxed_state(sandboxed_state const &) = delete; + sandboxed_state &operator=(sandboxed_state const &) = delete; + + lua_State *get() const { return m_state; } + + // runs the code, which returns one value, and gives that value as text ("nil", "true", a number, a string), or + // "error: " and the message + std::string run(std::string_view const Code) const { + auto const top{lua_gettop(m_state)}; + std::string result; + if (false == lua_sandbox::load_text_chunk(m_state, Code, "test") || 0 != lua_pcall(m_state, 0, 1, 0)) { + result = std::string{"error: "} + lua_tostring(m_state, -1); + } else if (lua_isnil(m_state, -1)) { + result = "nil"; + } else if (lua_isboolean(m_state, -1)) { + result = lua_toboolean(m_state, -1) ? "true" : "false"; + } else { + auto const *text{lua_tostring(m_state, -1)}; + result = text != nullptr ? text : "?"; + } + lua_settop(m_state, top); + return result; + } + + private: + lua_State *m_state; +}; + +bool contains(std::string_view const Text, std::string_view const Part) { + return Text.find(Part) != std::string_view::npos; +} + +} // namespace + +TEST_CASE("lua sandbox: no library that reaches files, programs, ffi or the debugger, and nothing that loads code") { + sandboxed_state const lua; + for (auto const *name : {"io", "ffi", "debug", "package", "jit", "require", "module", "dofile", "loadfile", "load", "loadstring", + "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", + "os.setlocale"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return {}", name)) == "nil"); + } + // what the scripts did with them fails, as a Lua error + CHECK(contains(lua.run("return io.open('eu07.ini')"), "attempt to index global 'io' (a nil value)")); + CHECK(contains(lua.run("return os.execute('cmd')"), "attempt to call field 'execute' (a nil value)")); + CHECK(contains(lua.run("return require('ffi')"), "attempt to call global 'require' (a nil value)")); +} + +TEST_CASE("lua sandbox: the libraries a script gets work") { + sandboxed_state const lua; + CHECK(lua.run("return math.floor(2.5) + #string.rep('a', 3) + bit.band(7, 4) + #table.concat({ 'a', 'b' })") == "11"); + CHECK(lua.run("return ('%d-%s'):format(7, 'x')") == "7-x"); + CHECK(lua.run("local ok, error = pcall(function() error('boom') end) return (not ok) and error:find('boom') ~= nil") == "true"); + CHECK(lua.run("local n = 0 for _, v in ipairs({ 1, 2, 3 }) do n = n + v end return n") == "6"); + CHECK(lua.run("return tostring(tonumber('12') + select('#', 1, 2))") == "14"); +} + +TEST_CASE("lua sandbox: os reads the clock, and nothing else") { + sandboxed_state const lua; + CHECK(lua.run("return type(os.time()) == 'number' and os.time() > 0") == "true"); + CHECK(lua.run("return type(os.clock()) == 'number'") == "true"); + CHECK(lua.run("return os.difftime(10, 4)") == "6"); + CHECK(lua.run("return os.time({ year = 2020, month = 1, day = 2, hour = 12 }) > 0") == "true"); + CHECK(lua.run("return os.date('!%Y-%m-%d', 0)") == "1970-01-01"); + CHECK(lua.run("return os.date('!*t', 86400 * 365).year") == "1971"); + CHECK(lua.run("return #os.date()") != "0"); + // a lone % at the end and %% are text + CHECK(lua.run("return os.date('!100%%', 0)") == "100%"); + CHECK(lua.run("return os.date('!100%', 0)") == "100%"); + // conversions the Microsoft C library doesn't know end the program there: refused before + CHECK(contains(lua.run("return os.date('%Q')"), "os.date: unknown conversion '%Q'")); + CHECK(contains(lua.run("return os.date('%#c')"), "os.date: unknown conversion '%#'")); + CHECK(contains(lua.run("return os.date('%Ey')"), "os.date: unknown conversion '%E'")); + // the table holds only the clock + CHECK(lua.run("local n = 0 for _ in pairs(os) do n = n + 1 end return n") == "4"); +} + +TEST_CASE("lua sandbox: all libraries opened over the sandbox are whole again (lua.fulllibraries)") { + sandboxed_state const lua; + luaL_openlibs(lua.get()); + for (auto const *name : {"io.open", "os.execute", "os.getenv", "os.date", "require", "loadstring", "dofile", "string.dump", "debug.traceback"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return type({})", name)) == "function"); + } + CHECK(lua.run("return type(require('ffi'))") == "table"); + CHECK(lua.run("return rawequal(os, package.loaded.os)") == "true"); +} + +TEST_CASE("lua sandbox: precompiled code isn't loaded") { + // real LuaJIT bytecode, from a state with all libraries + auto *full{luaL_newstate()}; + luaL_openlibs(full); + // luaL_dostring is a || of two calls, a bool in C++ + REQUIRE_FALSE(luaL_dostring(full, "return string.dump(function() return 42 end)")); + std::size_t length{0}; + auto const *bytes{lua_tolstring(full, -1, &length)}; + std::string const bytecode{bytes, length}; + lua_close(full); + REQUIRE(false == bytecode.empty()); + CHECK(bytecode.front() == '\x1b'); + + sandboxed_state const lua; + auto const top{lua_gettop(lua.get())}; + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), bytecode, "compiled.lua")); + CHECK(contains(lua_tostring(lua.get(), -1), "compiled.lua: precompiled scripts aren't loaded")); + lua_settop(lua.get(), top); + // nor in a text that only starts with the marker + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), std::string_view{"\x1bLJ\x02 return 1"}, "fake.lua")); + lua_settop(lua.get(), top); +} + +TEST_CASE("lua sandbox: a scenery reads its scripts only from its own folder") { + test::scratch_folder const root{"lua_sandbox_paths"}; + root.write("outside.lua", "return 1"); + root.write("scenery/test.lua", "return 2"); + root.write("scenery/scripts/module.lua", "return 3"); + root.write("scenery/folder.lua/inner.lua", "return 4"); + auto const folder{root.path("scenery") + "/"}; + + CHECK(lua_sandbox::read_script_file(folder, "test.lua") == std::optional{"return 2"}); + CHECK(lua_sandbox::read_script_file(folder, "scripts/module.lua") == std::optional{"return 3"}); + CHECK(lua_sandbox::read_script_file(folder, "scripts\\module.lua") == std::optional{"return 3"}); + for (auto const &path : {std::string{"../outside.lua"}, std::string{"scripts/../../outside.lua"}, std::string{"..\\outside.lua"}, + root.path("outside.lua"), std::string{"/outside.lua"}, std::string{"\\outside.lua"}, std::string{"C:outside.lua"}, + std::string{"missing.lua"}, std::string{"folder.lua"}, std::string{"scripts"}, std::string{}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_script_file(folder, path).has_value()); + } +} + +TEST_CASE("lua sandbox: a script larger than the limit isn't read") { + test::scratch_folder const root{"lua_sandbox_size"}; + root.write("scenery/limit.lua", std::string(static_cast(lua_sandbox::max_script_file), ' ')); + root.write("scenery/over.lua", std::string(static_cast(lua_sandbox::max_script_file) + 1, ' ')); + auto const folder{root.path("scenery") + "/"}; + CHECK(lua_sandbox::read_script_file(folder, "limit.lua").has_value()); + CHECK_FALSE(lua_sandbox::read_script_file(folder, "over.lua").has_value()); +} + +TEST_CASE("lua sandbox: a scenery script runs in protected mode, and its errors name the file") { + test::scratch_folder const root{"lua_sandbox_run"}; + root.write("scenery/good.lua", "ran = (ran or 0) + 1"); + root.write("scenery/fails.lua", "ran = 10\nlocal x = nil\nx.field = 1\nran = 20"); + root.write("scenery/files.lua", "local f = io.open('eu07.ini')"); + root.write("scenery/system.lua", "os.execute('cmd /c echo pwned')"); + root.write("scenery/syntax.lua", "this is not lua"); + root.write("scenery/compiled.lua", std::string_view{"\x1bLJ\x02 bytes"}); + auto const folder{root.path("scenery") + "/"}; + + sandboxed_state const lua; + auto *L{lua.get()}; + auto const top{lua_gettop(L)}; + + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "1"); + + auto const fails{lua_sandbox::run_script_file(L, folder, "fails.lua")}; + REQUIRE(fails.has_value()); + CHECK(contains(*fails, "fails.lua:3:")); + // it stopped at the error + CHECK(lua.run("return ran") == "10"); + + auto const files{lua_sandbox::run_script_file(L, folder, "files.lua")}; + REQUIRE(files.has_value()); + CHECK(contains(*files, "files.lua:1: attempt to index global 'io' (a nil value)")); + + auto const system{lua_sandbox::run_script_file(L, folder, "system.lua")}; + REQUIRE(system.has_value()); + CHECK(contains(*system, "system.lua:1: attempt to call field 'execute' (a nil value)")); + + auto const syntax{lua_sandbox::run_script_file(L, folder, "syntax.lua")}; + REQUIRE(syntax.has_value()); + CHECK(contains(*syntax, "syntax.lua:1:")); + + auto const compiled{lua_sandbox::run_script_file(L, folder, "compiled.lua")}; + REQUIRE(compiled.has_value()); + CHECK(contains(*compiled, "compiled.lua: precompiled scripts aren't loaded")); + + auto const outside{lua_sandbox::run_script_file(L, folder, "../good.lua")}; + REQUIRE(outside.has_value()); + CHECK(contains(*outside, "outside the folder")); + + // nothing left on the stack, and the state still works + CHECK(lua_gettop(L) == top); + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "11"); +} + +#endif diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..2b5684dab 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -956,6 +956,14 @@ bool global_settings::ConfigParseScriptScreens(cParser& Parser, std::string_view return true; } + // the scenery scripts (lua in the .scn) with all of LuaJIT's libraries, for a scenery that needs io, ffi or + // require: they then reach files and programs as the player does + if (token == "lua.fulllibraries") + { + ParseOne(Parser, lua_fulllibraries, 1); + return true; + } + if (token == "wasm.enabled") { ParseOne(Parser, wasm_enabled, 1); @@ -1962,6 +1970,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "python.uploadmain", python_uploadmain ); export_as_text( Output, "python.mipmaps", python_mipmaps ); export_as_text( Output, "luascreens.enabled", luascreens_enabled ); + export_as_text( Output, "lua.fulllibraries", lua_fulllibraries ); export_as_text( Output, "wasm.enabled", wasm_enabled ); export_as_text( Output, "screens.cabframes", screens_cabframes ); export_as_text( Output, "screens.externalframes", screens_externalframes ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 8d32a463c..25c7872c8 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -312,6 +312,7 @@ struct global_settings { bool python_uploadmain = true; std::chrono::duration python_minframetime {0.01f}; bool luascreens_enabled{true}; // screens drawn by Lua scripts (luascreen:, luadestinationsign: in the .mmd) + bool lua_fulllibraries{false}; // the scenery scripts (lua in the .scn) get all of LuaJIT's libraries (io, os, ffi, require...), not only the sandboxed ones bool wasm_enabled{true}; // screens drawn by WebAssembly modules (wasmscreen:, wasmdestinationsign: in the .mmd) int screens_cabframes{4}; // the script screens in the cab are refreshed every so many rendered frames int screens_externalframes{30}; // the script screens outside the cab (destination signs) are refreshed every so many rendered frames From cae152c96e8c79241ad337fbc34df8b6045abfac Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 16:23:57 +0100 Subject: [PATCH 08/59] feat(ui): driving aid shows the ED braking and hides a local brake the cab lacks The driving aid panel works out its throttle and brakes numbers in a new pure helper, vehicle/drivingaid.{h,cpp} (in CORE_SOURCES, unit tested). - EIM vehicles: the brakes line gets " ED brake: N%" while the ED braking demand (-eimic_real) is at least 1%, except where the integrated universal controller already shows it as the brake number (eu07/maszyna#558). - SplitEDPneumaticBrake (Vectron): the ED lever off zero shows in the throttle line as the negative step the cab's joint controller shows. - The local brake setting ("+N") shows only when the cab has a localbrake: lever or a jointctrl: whose braking range is the local brake, or when the local brake is applied. The Elf cabs have neither (eu07/maszyna#555). Vehicles without an EIM controller and with a local brake control show what they did. The existing msgids stay; two new ones show in English until the game data's lang/*.po (SVN) have them: "Brakes: %5.1f%c%s" (pl "Hamulce: %5.1f%c%s") and " ED brake: %d%%%%" (pl " Hamowanie ED: %d%%%%"). Adds the Vectron (vectron_v1/wariant_7w) to the real definitions of the unit tests. --- CMakeLists.txt | 1 + application/driveruipanels.cpp | 48 +++-- tests/unit/data/fiz/README.md | 3 +- .../unit/data/fiz/vectron_v1/wariant_7w.json | 72 +++++++ tests/unit/test_drivingaid.cpp | 176 ++++++++++++++++++ vehicle/drivingaid.cpp | 79 ++++++++ vehicle/drivingaid.h | 68 +++++++ 7 files changed, 434 insertions(+), 13 deletions(-) create mode 100644 tests/unit/data/fiz/vectron_v1/wariant_7w.json create mode 100644 tests/unit/test_drivingaid.cpp create mode 100644 vehicle/drivingaid.cpp create mode 100644 vehicle/drivingaid.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..a88a88424 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -548,6 +548,7 @@ set(CORE_SOURCES "vehicle/blackbox.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/drivingaid.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" "vehicle/linebreaker.cpp" diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index ba8e7556d..c598842d7 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "world/mtable.h" #include "vehicle/Train.h" #include "vehicle/Driver.h" +#include "vehicle/drivingaid.h" #include "model/AnimModel.h" #include "vehicle/DynObj.h" #include "model/Model3d.h" @@ -76,6 +77,13 @@ drivingaid_panel::update() { auto const *mover = controlled->MoverParameters; auto const *vehicledriver = controlled->Mechanik; auto const *owner = controlled->ctOwner != nullptr ? controlled->ctOwner : controlled->Mechanik; + // the numbers of the throttle and brakes lines, with the controls of the cab the driver is in + auto const readout { drivingaid::compute( drivingaid::from_movers( + *mover, + *vehicledriver->Controlling(), + drivingaid::cab_controls { + train->ggLocalBrake.SubModel != nullptr, + train->ggJointCtrl.SubModel != nullptr } ) ) }; { // throttle, velocity, speed limits and grade std::string expandedtext; @@ -116,8 +124,8 @@ drivingaid_panel::update() { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("Throttle: %3d+%d %c%s"), - mover->EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * mover->eimic_real)) : vehicledriver->Controlling()->MainCtrlPos, - mover->EIMCtrlType > 0 ? vehicledriver->Controlling()->MainCtrlPos : vehicledriver->Controlling()->ScndCtrlPos, + readout.throttle_first, + readout.throttle_second, mover->SpeedCtrlUnit.IsActive ? 'T' : mover->DirActive > 0 ? 'D' : mover->DirActive < 0 ? 'R' : @@ -137,16 +145,32 @@ drivingaid_panel::update() { mover->PipePress * 100 ); expandedtext = m_buffer.data(); } - auto const basicbraking { mover->fBrakeCtrlPos }; - auto const eimicbraking { std::max( 0.0, -100.0 * mover->eimic_real ) }; - std::snprintf( - m_buffer.data(), m_buffer.size(), - STR_C("Brakes: %5.1f+%-2.0f%c%s"), -// ( mover->EIMCtrlType == 0 ? basicbraking : mover->EIMCtrlType == 3 ? ( mover->UniCtrlIntegratedBrakeCtrl ? eimicbraking : basicbraking ) : eimicbraking ), - mover->UniCtrlIntegratedBrakeCtrl ? eimicbraking : basicbraking, - mover->LocalBrakePosA * LocalBrakePosNo, - mover->SlippingWheels ? '!' : ' ', - expandedtext.c_str() ); + if( readout.ed_percent ) { + // the ED braking demand, ahead of the expanded data (eu07/maszyna#558) + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C(" ED brake: %d%%%%"), + *readout.ed_percent ); + expandedtext.insert( 0, m_buffer.data() ); + } + if( readout.show_local_brake ) { + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C("Brakes: %5.1f+%-2.0f%c%s"), + readout.brake_first, + readout.local_brake, + mover->SlippingWheels ? '!' : ' ', + expandedtext.c_str() ); + } + else { + // the cab has no local brake control: its setting is left out (eu07/maszyna#555) + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C("Brakes: %5.1f%c%s"), + readout.brake_first, + mover->SlippingWheels ? '!' : ' ', + expandedtext.c_str() ); + } text_lines.emplace_back( m_buffer.data(), Global.UITextColor ); } diff --git a/tests/unit/data/fiz/README.md b/tests/unit/data/fiz/README.md index 514fb6287..eb5650edb 100644 --- a/tests/unit/data/fiz/README.md +++ b/tests/unit/data/fiz/README.md @@ -59,8 +59,9 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `su45_v2/301d.fiz` | SU45 | DumbDE | LSt | FV4a | PneumaticBrake | Screw | | `su46_v2/303d.fiz` | SU46 | DumbDE | LSt | FV4a | PneumaticBrake | Screw | | `tem2_v2/tem2a.fiz` | TEM2 | DieselElectric | LSt | M394 | PneumaticBrake | Screw | +| `vectron_v1/wariant_7w.fiz` | VECTRON | ElectricInductionMotor | EStED | MHZ_K8P | PneumaticBrake | Screw | | `wm15_v1/wm15.fiz` | WM15 | Dumb | LSt | FV4a | PneumaticBrake | Screw | | `wmb10_v1/wmb10.fiz` | WMB10 | DieselEngine | LSt | FV4a | PneumaticBrake | Screw | | `z1_v2/152a.fiz` | Z1 | - | KE | - | ManualBrake | Screw | -The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. +The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft, the Vectron for its ED brake lever of its own (SplitEDPneumaticBrake). The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. diff --git a/tests/unit/data/fiz/vectron_v1/wariant_7w.json b/tests/unit/data/fiz/vectron_v1/wariant_7w.json new file mode 100644 index 000000000..777f4a78b --- /dev/null +++ b/tests/unit/data/fiz/vectron_v1/wariant_7w.json @@ -0,0 +1,72 @@ +{ + "_source": "pkp/vectron_v1/wariant_7w.fiz", + "_comment": "converted by test_fiz.cpp from the game's definition with the files it includes, keeping what the game's loader reads", + "Param": {"Category": "train", "M": "90000", "Mred": "12000", "Vmax": "200", "PWR": "6400", "SandCap": "700"}, + "Load": {"MaxLoad": "7", "LoadQ": "pieces", "LoadAccepted": "pantstate", "LoadSpeed": "1", "UnLoadSpeed": "0.1"}, + "Dimensions": {"L": "18.925", "H": "3.95", "W": "2.95", "Cx": "0.1"}, + "Wheels": {"D": "1.250", "AIM": "4000", "Tw": "1.435", "Axle": "Bo'Bo'", "Ad": "3", "Bd": "9.5", "Rmin": "80"}, + "Brake": {"BrakeValve": "EStED", "NBpA": "4", "MBF": "50", "MaxBP": "3.7", "MaxLBP": "3.7", "BCN": "8", "RM": "0.81", "BCR": "0.127", "BCD": "0.04", "BCM": "2.7", "BCS": "0.8", "BSA": "0", "BM": "Disk2", "BVV": "125", "Vv": "0.8", "CompressorSpeed": "0.06", "CompressorPower": "Main", "MinCP": "8.5", "MaxCP": "9.9", "UBB1": "8", "UBB2": "2", "LPOn": "3.0", "LPOff": "4.5", "HandlePipeUnlockPos": "-1", "EmergencyCutsOffHandle": "Yes"}, + "SpringBrake": {"Volume": "10", "MBF": "8", "MaxSP": "5.5", "ResetP": "4.0", "MinFP": "3.5", "PressOff": "4.5", "PressOn": "3.5", "ValveOnArea": "0.0002", "ValveOffArea": "0.0002", "ValvePNBArea": "0.002", "MTC": "4"}, + "BuffCoupl": {"CType": "Screw", "kB": "9200", "DmaxB": "0.15", "FmaxB": "740", "kC": "4800", "DmaxC": "0.15", "FmaxC": "780", "beta": "0.58", "AllowedFlag": "103"}, + "Cntrl": {"BrakeSystem": "Pneumatic", "BrakeOpModes": "PN", "BCPN": "4", "BDelay1": "15", "BDelay2": "4", "BDelay3": "35", "BDelay4": "25", "ASB": "Automatic", "LocalBrake": "PneumaticBrake", "MCPN": "15", "SCPN": "40", "SpeedCtrlDelay": "0.5", "AutoRelay": "No", "MainInitTime": "10", "MainStart": "Manual", "IniCDelay": "0.5", "SCDelay": "0.1", "BrakeDelays": "GPR", "BrakeHandle": "MHZ_K8P", "LocBrakeHandle": "FD1", "ScndS": "Yes", "SBD": "0", "ConverterStart": "Automatic", "ConverterStartDelay": "10", "PantCompressorStart": "Automatic", "PantAutoValve": "Yes", "EIMCtrlType": "0", "HAO": "No", "HMO": "No", "HGDP1": "0.1", "OMP": "0.4", "DirChangeMaxPos": "0", "LocalBrakeTraxx": "No", "PantEPValveStart": "Manual", "PantEPValveSpring": "No", "HideDirStatusWhenMoving": "Yes", "HideDirStatusSpeed": "5", "AutomaticCabActivation": "No", "InactiveCabFlag": "161", "DCMB": "Yes", "DCDPP": "1.0", "IBTB": "Yes", "SBBBH": "Yes", "BBHT": "2.0", "MotorBlowersStart": "Converter", "SplitEDPneumaticBrake": "Yes", "DBPN": "15", "rows": [ + ["-1","0.8","-1","20","Pneumatic"], + ["0","0.5","-1","2","Pneumatic"], + ["1","0.46","-1","2","Pneumatic"], + ["2","0.42","-1","2","Pneumatic"], + ["3","0.38","-1","2","Pneumatic"], + ["4","0.34","-1","2","Pneumatic"], + ["5","0.29","-1","2","Pneumatic"], + ["6","0","-1","40","Pneumatic"], + ["LampRed=255","LampGreen=255","LampBlue=228"] + ]}, + "Security": {"AwareSystem": "Active,CabSignal,SeparateAcknowledge", "AwareDelay": "30", "SoundSignalDelay": "0", "MaxHoldTime": "1.0", "EmergencyBrakeDelay": "5", "RadioStop": "Yes"}, + "Light": {"Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": "24", "LMaxCurrent": "155"}, + "Clima": {"Heating": "Main"}, + "Power": {"EnginePower": "CurrentCollector", "CollectorsNo": "2", "MaxVoltage": "4200", "MaxCurrent": "2000", "MinH": "0.38", "MinV": "1900", "MaxH": "2.4", "CSW": "1.4", "PhysicalLayout": "3", "PantType": "WBL85"}, + "Engine": {"EngineType": "ElectricInductionMotor", "Trans": "10:47", "dfic": "931", "dfmax": "1.67", "p": "2", "cfu": "29", "cim": "8.86", "icif": "0.642", "Uzmax": "2216", "Uzh": "2216", "DU": "20", "I0": "20", "fcfu": "30", "F0": "340", "a1": "0.35", "Pmax": "6400", "Fh": "150", "Ph": "5200", "Vh0": "5", "Vh1": "10", "Imax": "2500", "Flat": "Yes", "abed": "1", "edep": "1.5", "Imaxrpc": "500", "BRVto": "15", "MotorBlowersSustainTime": "30", "MotorBlowersStartVelocity": "0.1", "MotorBlowersSpeed": "-10"}, + "SpeedControl": {"SpeedCtrl": "Yes", "OverrideManual": "No", "InitPwr": "1.0", "MaxPwrVel": "-1", "StartVel": "-1", "VelStep": "5", "PwrStep": "0.01", "MinPwr": "0.0", "MaxPwr": "1.0", "MinVel": "0", "MaxVel": "200", "Offset": "0", "kPpos": "0.1", "kPneg": "0.2", "kIpos": "0.03", "kIneg": "0.03", "BrakeIntervention": "No", "SpeedCtrlType": "Time", "SpeedCtrlDelay": "0.5"}, + "Doors": {"OpenCtrl": "Mixed", "CloseCtrl": "Mixed", "DoorOpenWithPermit": "1", "DoorMaxShiftL": "2", "DoorsPermitLightBlinking": "0"}, + "Switches": {"Pantograph": "Impulse", "PantographPresets": "2|1|3|2", "PantographPresetDefault": "1", "ModernDimmer": "Yes"}, + "DimmerList": {"Size": "5", "Cycle": "no", "DefaultPos": "3", "rows": [ + ["yes","no","no"], + ["yes","yes","no"], + ["no","no","yes"], + ["no","no","no"], + ["no","yes","no"] + ]}, + "ffList": {"Size": "8", "rows": [ + ["0","0.2"], + ["1","0.2"], + ["9.2","0.6"], + ["24.6","0.8"], + ["30.0","0.8"], + ["30.0","1.74"], + ["35.2","2.07"], + ["35.2","2.44"], + ["49.8","3.388"] + ]}, + "LightsList": {"Size": "16", "Wrap": "Yes", "Default": "1", "rows": [ + ["0","0"], + ["17","0"], + ["4","0"], + ["16","1"], + ["1","16"], + ["21","34"], + ["34","0"], + ["21","0"], + ["37","0"], + ["33","0"], + ["22","34"], + ["36","0"], + ["21","0"], + ["21","0"], + ["38","34"], + ["38","0"] + ]}, + "WiperList": {"Size": "4", "Angle": "58", "rows": [ + ["0","0.7","0.0","0.5"], + ["3","0.7","7.0","0.5"], + ["3","0.7","0.7","0.0"], + ["3","0.5","0.5","0.0"] + ]} +} diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp new file mode 100644 index 000000000..b6ae1cc9d --- /dev/null +++ b/tests/unit/test_drivingaid.cpp @@ -0,0 +1,176 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "real_vehicles.h" + +#include "vehicle/drivingaid.h" +#include "McZapkie/hamulce.h" + +#include +#include +#include + +// the numbers of the driving aid panel's throttle and brakes lines: the ED braking shows (eu07/maszyna#558) and +// the local brake is left out where the cab has no control of it (eu07/maszyna#555) + +using test::definition; +using test::vehicle; + +namespace { + +// the cab controls of the vehicles here, as their cab definitions (.mmd) have them: the Vectron has a local brake +// lever and a joint controller whose braking range is its ED lever, the Traxx and the EU07 a local brake lever, +// the SM42 a joint controller whose braking range is the local brake, none of the 45 Elf cabs either of them +constexpr drivingaid::cab_controls vectron_cab{true, true}; +constexpr drivingaid::cab_controls lever_cab{true, false}; +constexpr drivingaid::cab_controls jointctrl_cab{false, true}; +constexpr drivingaid::cab_controls elf_cab{false, false}; + +drivingaid::readout read(vehicle &Vehicle, drivingaid::cab_controls const &Cab) { + return drivingaid::compute(drivingaid::from_movers(Vehicle.mover(), Vehicle.mover(), Cab)); +} + +// what the panel showed before: the throttle and brakes numbers, and the local brake always +drivingaid::readout before(TMoverParameters const &Mover) { + drivingaid::readout result; + result.throttle_first = Mover.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Mover.eimic_real)) : Mover.MainCtrlPos; + result.throttle_second = Mover.EIMCtrlType > 0 ? Mover.MainCtrlPos : Mover.ScndCtrlPos; + result.brake_first = Mover.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Mover.eimic_real) : Mover.fBrakeCtrlPos; + result.local_brake = Mover.LocalBrakePosA * LocalBrakePosNo; + return result; +} + +test::track const line{0.15, 0.0, test::catenary_3kv}; + +} // namespace + +TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step, and its ED braking") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 80.0 /* km/h */, "vectron", 1}; + REQUIRE(vectron->SplitEDPneumaticBrake); + REQUIRE(vectron->DynamicBrakeCtrlPosNo == 15); + REQUIRE(vectron->EIMCtrlType == 0); + + // lever at zero: the master controller, as before, and no ED braking + auto const idle{read(vectron, vectron_cab)}; + CHECK(idle.throttle_first == vectron->MainCtrlPos); + CHECK_FALSE(idle.ed_percent.has_value()); + CHECK(idle.show_local_brake); + + // six steps of the ED lever, as the cab's joint controller shows them + for (int step = 0; step < 6; ++step) { + REQUIRE(vectron->IncDynamicBrakeLevel(1.f)); + } + vectron.run(1.0, line); + REQUIRE(vectron->Vel > 15.0); // above Vh1, where the ED brake has its full demand + auto const braking{read(vectron, vectron_cab)}; + CHECK(braking.throttle_first == -6); + REQUIRE(vectron->eimic_real == doctest::Approx(-0.4)); + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == 40); + // the train brake handle and the local brake, as before + CHECK(braking.brake_first == doctest::Approx(vectron->fBrakeCtrlPos)); + CHECK(braking.show_local_brake); + CHECK(braking.local_brake == doctest::Approx(0.0)); + + // the joint controller's braking range is the ED lever, so it isn't a local brake control + CHECK_FALSE(read(vectron, jointctrl_cab).show_local_brake); +} + +TEST_CASE("driving aid: the Traxx's ED braking from its master controller") { + vehicle traxx{definition::fiz("e186_v2/eu47"), 80.0 /* km/h */, "traxx", 1}; + REQUIRE(traxx->EIMCtrlType == 1); + REQUIRE_FALSE(traxx->SplitEDPneumaticBrake); + + CHECK_FALSE(read(traxx, lever_cab).ed_percent.has_value()); + // B+: the braking demand ramps towards full + traxx->MainCtrlPos = 0; + traxx.run(3.0, line); + REQUIRE(traxx->eimic_real < -0.2); + auto const braking{read(traxx, lever_cab)}; + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == std::lround(-100.0 * traxx->eimic_real)); + // the drive demand stays at zero while braking, with the controller position next to it, as before + CHECK(braking.throttle_first == 0); + CHECK(braking.throttle_second == 0); + CHECK(braking.show_local_brake); +} + +TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, and shows its ED braking") { + vehicle elf{definition::fiz("elf_v1/21we-a"), 60.0 /* km/h */, "elf", 1}; + REQUIRE(elf->EIMCtrlType == 2); + // the definition has a local brake (LocalBrake=PneumaticBrake, LocBrakeHandle=FD1), the cab no control of it + REQUIRE(elf->LocalBrake == TLocalBrake::PneumaticBrake); + + auto const idle{read(elf, elf_cab)}; + CHECK_FALSE(idle.show_local_brake); + CHECK_FALSE(idle.ed_percent.has_value()); + + // the controller at its lowest braking position: the demand ramps towards full braking + elf->MainCtrlPos = 0; + elf.run(2.0, line); + REQUIRE(elf->eimic_real < -0.1); + auto const braking{read(elf, elf_cab)}; + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == std::lround(-100.0 * elf->eimic_real)); + CHECK(braking.throttle_first == 0); + CHECK(braking.throttle_second == 0); + CHECK_FALSE(braking.show_local_brake); + + // applied after all (the AI, or the keys), it shows + elf->LocalBrakePosA = 0.3; + auto const applied{read(elf, elf_cab)}; + CHECK(applied.show_local_brake); + CHECK(applied.local_brake == doctest::Approx(3.0)); +} + +TEST_CASE("driving aid: a vehicle without an EIM controller shows what it did") { + vehicle eu07{definition::fiz("4e_v1/4e"), 60.0 /* km/h */, "eu07", 1}; + eu07->MainCtrlPos = 5; + eu07->LocalBrakePosA = 0.2; + auto const readout{read(eu07, lever_cab)}; + CHECK(readout.throttle_first == 5); + CHECK(readout.throttle_second == eu07->ScndCtrlPos); + CHECK(readout.local_brake == doctest::Approx(2.0)); + CHECK(readout.show_local_brake); + CHECK_FALSE(readout.ed_percent.has_value()); + + // the SM42's local brake is the braking range of its joint controller + vehicle sm42{definition::fiz("sm42_v1/6d1"), 0.0, "sm42", 1}; + CHECK(read(sm42, jointctrl_cab).show_local_brake); + CHECK_FALSE(read(sm42, elf_cab).show_local_brake); +} + +TEST_CASE("driving aid: the integrated universal controller shows the ED demand as its brake number, once") { + drivingaid::input input; + input.eim = true; + input.eimctrltype = 3; + input.integratedbrake = true; + input.eimic_real = -0.35; + input.brakectrlpos = 2.0; + auto const readout{drivingaid::compute(input)}; + CHECK(readout.brake_first == doctest::Approx(35.0)); + CHECK_FALSE(readout.ed_percent.has_value()); + CHECK(readout.throttle_first == 0); +} + +TEST_CASE("driving aid: every real vehicle with a local brake control shows the numbers it showed before") { + // with the ED lever of a split ED brake at zero, the change only adds the ED part and leaves out the local brake + // of a cab without a control of it + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + vehicle real{definition::fiz(path), 40.0 /* km/h */, "real", 1}; + for (auto const &[mainctrl, localbrake, eimic] : {std::tuple{0, 0.0, 0.0}, std::tuple{1, 0.4, -0.25}, std::tuple{1, 0.0, 0.6}}) { + real->MainCtrlPos = std::min(mainctrl, real->MainCtrlPosNo); + real->LocalBrakePosA = localbrake; + real->eimic_real = eimic; + auto const now{read(real, lever_cab)}; + auto const was{before(real.mover())}; + CHECK(now.throttle_first == was.throttle_first); + CHECK(now.throttle_second == was.throttle_second); + CHECK(now.brake_first == doctest::Approx(was.brake_first)); + CHECK(now.local_brake == doctest::Approx(was.local_brake)); + CHECK(now.show_local_brake); + } + } +} diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp new file mode 100644 index 000000000..df8fc37a7 --- /dev/null +++ b/vehicle/drivingaid.cpp @@ -0,0 +1,79 @@ +/* +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/drivingaid.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" + +#include +#include + +namespace drivingaid { + +namespace { + +// the first throttle number: the drive demand in percent with an EIM controller, else the master controller. +// a separate ED lever off its zero shows as the negative step the cab's joint controller is at +int throttle_first(input const &Input) { + if (Input.splited && Input.dynamicbrakepos > 0.0) { + return -static_cast(std::lround(Input.dynamicbrakepos * Input.dynamicbrakeposno)); + } + if (Input.eimctrltype > 0) { + return std::max(0, static_cast(100.4 * Input.eimic_real)); + } + return Input.mainctrlpos; +} + +// the cab has a control of the local brake: its own lever, or the braking range of the joint controller +// unless that range is the separate ED lever +bool has_local_brake_control(input const &Input) { + return Input.cab.localbrake || (Input.cab.jointctrl && false == Input.splited); +} + +} // namespace + +readout compute(input const &Input) { + readout result; + result.throttle_first = throttle_first(Input); + result.throttle_second = Input.eimctrltype > 0 ? Input.mainctrlpos : Input.scndctrlpos; + + auto const edbraking{std::max(0.0, -100.0 * Input.eimic_real)}; + result.brake_first = Input.integratedbrake ? edbraking : Input.brakectrlpos; + result.local_brake = Input.localbrakepos * LocalBrakePosNo; + // without a control in the cab the local brake is left out, unless it is applied after all (the AI or a key) + result.show_local_brake = has_local_brake_control(Input) || Input.localbrakepos > 0.0; + // the integrated universal controller shows the ED demand as its brake number already + if (Input.eim && false == Input.integratedbrake) { + if (auto const percent{static_cast(std::lround(edbraking))}; percent > 0) { + result.ed_percent = percent; + } + } + return result; +} + +input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab) { + input result; + result.eim = Vehicle.EngineType == TEngineType::ElectricInductionMotor || Vehicle.EIMCtrlType > 0; + result.eimctrltype = Vehicle.EIMCtrlType; + result.splited = Controlling.SplitEDPneumaticBrake; + result.integratedbrake = Vehicle.UniCtrlIntegratedBrakeCtrl; + result.eimic_real = Vehicle.eimic_real; + result.dynamicbrakepos = Controlling.DynamicBrakeCtrlPos; + result.dynamicbrakeposno = Controlling.DynamicBrakeCtrlPosNo; + result.mainctrlpos = Controlling.MainCtrlPos; + result.scndctrlpos = Controlling.ScndCtrlPos; + result.brakectrlpos = Vehicle.fBrakeCtrlPos; + result.localbrakepos = Vehicle.LocalBrakePosA; + result.cab = Cab; + return result; +} + +} // namespace drivingaid diff --git a/vehicle/drivingaid.h b/vehicle/drivingaid.h new file mode 100644 index 000000000..8cec257da --- /dev/null +++ b/vehicle/drivingaid.h @@ -0,0 +1,68 @@ +/* +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 + +class TMoverParameters; + +// what the driving aid panel shows of the controls and of the braking: the numbers of its throttle and +// brakes lines, worked out from the vehicle state (eu07/maszyna#558, eu07/maszyna#555) +namespace drivingaid { + +// the cab controls the panel needs to know of, which the cab definition (.mmd) has or lacks +struct cab_controls { + // a lever of the local (auxiliary) brake: localbrake: + bool localbrake{true}; + // a joint controller, jointctrl:, whose braking range is the local brake, or the ED lever with + // SplitEDPneumaticBrake + bool jointctrl{false}; +}; + +struct input { + // the vehicle works out the integrated drive and brake demand (eimic): an induction motor vehicle, + // or a diesel one with an EIM controller + bool eim{false}; + int eimctrltype{0}; + // the ED brake has a lever of its own (SplitEDPneumaticBrake), with dynamicbrakeposno steps + bool splited{false}; + // the universal controller brakes with the ED brake, so the brake handle number is the ED demand already + bool integratedbrake{false}; + // the demand in use, -1..1, negative braking + double eimic_real{0.0}; + double dynamicbrakepos{0.0}; // 0..1 + int dynamicbrakeposno{10}; + int mainctrlpos{0}; + int scndctrlpos{0}; + double brakectrlpos{0.0}; // the train brake handle + double localbrakepos{0.0}; // 0..1 + cab_controls cab; +}; + +struct readout { + // "Throttle: first+second" + int throttle_first{0}; + int throttle_second{0}; + // "Brakes: first+local" + double brake_first{0.0}; + double local_brake{0.0}; + bool show_local_brake{true}; + // the ED braking demand in percent, while there is some + std::optional ed_percent; +}; + +// the panel's numbers from the vehicle state +readout compute(input const &Input); + +// the state the panel reads: Vehicle is the one the driver sits in, Controlling the one whose controllers +// the driver moves (TController::Controlling()) +input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab); + +} // namespace drivingaid From 57c723a72e929bb389c055dbc62ebdf8ad2df027 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 17:56:09 +0100 Subject: [PATCH 09/59] refactor: reentrant localtime and no goto in the cross switch lookup (Sonar S1912, S1909) The date of the scenery wizard's .scn header and the stamp of the editor's terrain backups use local_tm() (localtime_s/localtime_r) instead of std::localtime. The goto out of the loop over the four tracks of a cross switch, into the continue of the failed "ac" assignment, becomes a std::all_of check which continues the outer node loop, as the goto did. --- launcher/scenery_wizard.cpp | 4 +++- scene/scenelayerssave.cpp | 3 ++- scene/scenenodegroups.cpp | 8 ++++---- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/launcher/scenery_wizard.cpp b/launcher/scenery_wizard.cpp index 339a2871c..7038415d6 100644 --- a/launcher/scenery_wizard.cpp +++ b/launcher/scenery_wizard.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" #include "utilities/translation.h" +#include "utilities/utilities.h" #include #include @@ -400,7 +401,8 @@ bool ui::scenerywizard_panel::create_scenery() } auto const now{std::time(nullptr)}; char date[32]; - std::strftime(date, sizeof(date), "%Y-%m-%d", std::localtime(&now)); + std::tm const local{local_tm(now)}; + std::strftime(date, sizeof(date), "%Y-%m-%d", &local); char reference[96]; std::snprintf(reference, sizeof(reference), "//$g PUWG1992 %.3f %.3f", m_map.point().x / 1000.0, m_map.point().y / 1000.0); auto const area{range()}; diff --git a/scene/scenelayerssave.cpp b/scene/scenelayerssave.cpp index d85d43ac4..8321c1844 100644 --- a/scene/scenelayerssave.cpp +++ b/scene/scenelayerssave.cpp @@ -1668,7 +1668,8 @@ save_result node_layers::save(std::vector const &Rootstatements, st { auto const now{std::time(nullptr)}; char stamp[32]; - std::strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", std::localtime(&now)); + std::tm const local{local_tm(now)}; + std::strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", &local); for (auto const output : written) { auto const filepath{path(output)}; diff --git a/scene/scenenodegroups.cpp b/scene/scenenodegroups.cpp index 781287806..dd10fc143 100644 --- a/scene/scenenodegroups.cpp +++ b/scene/scenenodegroups.cpp @@ -207,12 +207,12 @@ node_groups::update_map() continue; last_switch->track[lastc - 'a'] = track; - for (auto trk : last_switch->track) - if (!trk) - goto skip_e; + // all four tracks of the cross switch have to be known before it's assigned + if (!std::all_of(last_switch->track.begin(), last_switch->track.end(), [](TTrack const *Track) { return Track != nullptr; })) + continue; if (!assign_cross_switch(*last_switch, sw_name, "ac", 0)) - skip_e: continue; + continue; if (!assign_cross_switch(*last_switch, sw_name, "ad", 1)) continue; if (!assign_cross_switch(*last_switch, sw_name, "bc", 2)) From 8467eab8b49d87c0ff3cfdccd1444cda9ad8df49 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 18:35:47 +0100 Subject: [PATCH 10/59] fix(scripting): read '\' as a folder separator in scenery script paths on Linux too The unit test reading "scripts\module.lua" failed on Linux/GCC: there '\' is part of a file name, not a separator. The game already reads '\' in its data paths as '/' (replace_slashes, the model and texture names, the parser's include tokens), and sceneries made on Windows often name their folders with it, so the scenery scripts do the same: read_script_file turns '\' into '/' (lua_sandbox::with_forward_slashes) after the path check. is_safe_relative_path splits on both separators on every system, so '..\' and 'a\..\..\' stay refused; the test now checks those too. --- script_screens_doc.md | 2 +- scripting/luasandbox.cpp | 10 +++++++++- scripting/luasandbox.h | 7 ++++++- tests/unit/test_lua_sandbox.cpp | 3 +++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 09a4c2638..4cdc5badd 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -216,7 +216,7 @@ and works with memcells, tracks and vehicles through the table `eu07.events` (`e `memcell_update`, `writelog` and the rest, see `scripting/lua.cpp`). It shares the sandbox of the Lua screens: - the file is a path relative to the scenery folder (`scenery/`), and stays inside it: no `..`, no drive, no leading - `/`. It is text, of at most 16 MB; precompiled code is not loaded; + `/`. `/` and `\` both separate folders, on Linux too. It is text, of at most 16 MB; precompiled code is not loaded; - the script gets the base library, `table`, `string`, `math` and `bit`, and of `os` only the clock: `os.time`, `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index 8d80cdebf..ea5f98a88 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreenrules.h" +#include #include #include #include @@ -59,6 +60,13 @@ int api_date(lua_State *L) } // namespace +std::string with_forward_slashes(std::string_view const Path) +{ + std::string result{Path}; + std::ranges::replace(result, '\\', '/'); + return result; +} + void open_safe_libraries(lua_State *L) { open_library(L, luaopen_base, ""); @@ -121,7 +129,7 @@ std::optional read_script_file(std::string const &Folder, std::stri } // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens // its files - std::filesystem::path const path{Folder + std::string{Path}}; + std::filesystem::path const path{Folder + with_forward_slashes(Path)}; std::error_code error; if (false == std::filesystem::is_regular_file(path, error)) { diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h index abdd21933..167060026 100644 --- a/scripting/luasandbox.h +++ b/scripting/luasandbox.h @@ -38,8 +38,13 @@ void open_clock_library(lua_State *L); // stack bool load_text_chunk(lua_State *L, std::string_view Code, std::string const &Name); +// Path with each '\' turned into '/', as the game reads the paths in its data (replace_slashes): a scenery made on +// Windows may name its folders either way, and on Linux only '/' separates them +std::string with_forward_slashes(std::string_view Path); + // the file Path of Folder, when Path is a relative path inside Folder (no '..', no drive, no leading separator) and -// names a regular file of at most max_script_file bytes. nothing otherwise +// names a regular file of at most max_script_file bytes. nothing otherwise. '\' separates folders in Path as '/' does, +// on every system std::optional read_script_file(std::string const &Folder, std::string_view Path); // reads the script Path of Folder (as read_script_file), loads it as text and runs it in protected mode. nothing when diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp index f23cb0406..6768e27ed 100644 --- a/tests/unit/test_lua_sandbox.cpp +++ b/tests/unit/test_lua_sandbox.cpp @@ -148,8 +148,11 @@ TEST_CASE("lua sandbox: a scenery reads its scripts only from its own folder") { CHECK(lua_sandbox::read_script_file(folder, "test.lua") == std::optional{"return 2"}); CHECK(lua_sandbox::read_script_file(folder, "scripts/module.lua") == std::optional{"return 3"}); + // '\' separates the folders on Linux too, as in the rest of the scenery's paths + CHECK(lua_sandbox::with_forward_slashes("a\\b/c\\d.lua") == "a/b/c/d.lua"); CHECK(lua_sandbox::read_script_file(folder, "scripts\\module.lua") == std::optional{"return 3"}); for (auto const &path : {std::string{"../outside.lua"}, std::string{"scripts/../../outside.lua"}, std::string{"..\\outside.lua"}, + std::string{"scripts\\..\\..\\outside.lua"}, std::string{"scripts/..\\../outside.lua"}, root.path("outside.lua"), std::string{"/outside.lua"}, std::string{"\\outside.lua"}, std::string{"C:outside.lua"}, std::string{"missing.lua"}, std::string{"folder.lua"}, std::string{"scripts"}, std::string{}}) { CAPTURE(path); From fde6d10f32a7d1ecbda8e462b275e9b5425a9e0a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 18:55:19 +0100 Subject: [PATCH 11/59] feat(scripting): file functions for the scenery Lua scripts The sandbox took io away from the scenery scripts; this gives them files back the way the Lua screens have them. The screens have eu07.read_file(path); the scenery state now gets it too, together with a write function and one to read the written files back: - eu07.read_file(path): a file of the scenery folder (scenery/), or nil. The path rule of `lua ` and the screens (relative, no '..', no drive, no leading separator), a regular file of at most 16 MB. - eu07.write_file(path, text): writes the file in the scenery's data folder, replacing it, and makes the folders of path. true, or nil and the reason. - eu07.read_data_file(path): a file of the data folder, or nil. The data folder is per scenery and among the player's files, next to the user eu07.ini and eu07_odometers.txt (user_config_path): %APPDATA%/MaSzyna/scenery_data//, ~/.config/MaSzyna/ on Linux. Nothing is written into the game folder; with no user folder, writes are refused. The log names the folder when the scenery loads its first script. Writes are limited to 1 MB a file, 256 files and 16 MB a data folder, and to relative paths of at most 200 bytes and 8 folders, of portable names: no '.', '..', empty names, :<>"|?* or control characters, no trailing dot or space, no Windows device names (con, nul, com1, lpt1...). The parent folder is checked with canonical paths, so a link in the data folder doesn't lead a write out of it. The code is in scripting/luasandbox.{h,cpp} (read_file, which read_script_file now uses, is_safe_write_path, write_data_file, scenery_data_folder, open_file_library); lua.cpp only opens the functions and sets the folders in interpret(). The screens keep their own read_screen_file, which #356 changes. Documented in the "Scenery scripts" section of script_screens_doc.md; 8 new cases in test_lua_sandbox.cpp. --- script_screens_doc.md | 27 ++++ scripting/lua.cpp | 13 ++ scripting/lua.h | 4 + scripting/luasandbox.cpp | 276 +++++++++++++++++++++++++++++++- scripting/luasandbox.h | 47 ++++++ tests/unit/test_lua_sandbox.cpp | 206 ++++++++++++++++++++++++ 6 files changed, 569 insertions(+), 4 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 4cdc5badd..435706fe4 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -223,6 +223,33 @@ and works with memcells, tracks and vehicles through the table `eu07.events` (`e - a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on loading. An event handler that fails is logged with the name of the event, and the simulation goes on. +Instead of `io`, a scenery script reads and writes files through `eu07`, as the Lua screens read theirs: + +| function | meaning | +|----------------------------------|------------------------------------------------------------------------------------------| +| `eu07.read_file(path)` | the contents of a file of the scenery folder (`scenery/`), or `nil`: a regular file of at most 16 MB, the path as for `lua ` | +| `eu07.write_file(path, text)` | writes `text` (any bytes) to a file of the scenery's data folder, replacing what was there, and makes the folders of `path`; returns `true`, or `nil` and the reason | +| `eu07.read_data_file(path)` | the contents of a file of the scenery's data folder, or `nil`: what `write_file` wrote there | + +The data folder is the scenery's own, in the player's folder of the game: `%APPDATA%\MaSzyna\scenery_data\\` +on Windows, `~/.config/MaSzyna/scenery_data//` on Linux (`~/Library/Application Support/MaSzyna/...` on a +Mac), `` being the `.scn` file without `.scn` (`td.scn`: `scenery_data/td/`). The game writes nowhere else +for a script, and never into its own folder; the log says where the folder is when the scenery loads its first +script. What is written there stays for the next run of the scenery, and the player may delete it. + +A path to write to is relative, with `/` or `\` between the folders, at most 8 folders deep and 200 bytes long, and +each name in it portable: no `..`, no `.`, no empty name, no drive, no `:` `<` `>` `"` `|` `?` `*` or control +characters, no `.` or space at the end, and none of the names Windows keeps for its devices (`con`, `nul`, `com1`, +`lpt1`... with or without an extension). A file is at most 1 MB (1048576 bytes), and the data folder of a scenery holds at most 256 +files and 16 MB together; a write over these limits is refused, and leaves the file as it was. + +```lua +local saved = eu07.read_data_file("state.txt") +local runs = tonumber(saved or "0") + 1 +local ok, reason = eu07.write_file("state.txt", tostring(runs)) +if not ok then eu07.events.writelog("state not saved: " .. reason) end +``` + A script written for the earlier full libraries stops at the first call to one of them (`attempt to index global 'io' (a nil value)` in the log). For a scenery you trust, `eu07.ini` can give the scripts all of LuaJIT's libraries again: diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 0854579d9..7079bb2c3 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -6,6 +6,7 @@ #include "vehicle/Driver.h" #include "simulation/simulation.h" #include "scripting/luasandbox.h" +#include "utilities/utilities.h" lua::lua() { @@ -45,6 +46,9 @@ lua::lua() {nullptr, nullptr} }; luaL_register(state, "eu07.events", api); + lua_pop(state, 1); + // eu07.read_file, eu07.write_file and eu07.read_data_file, the files of the scenery in place of io + lua_sandbox::open_file_library(state, &files); } lua::~lua() @@ -67,6 +71,15 @@ void lua::interpret(const std::string &folder, const std::string &file) full_libraries = true; WriteLog("lua: lua.fulllibraries is on, the scenery scripts run with all libraries (io, os, ffi, require...)", logtype::lua); } + // the scripts read the files of the scenery folder, and write theirs into a folder of the scenery among the + // player's files (%APPDATA%/MaSzyna, ~/.config/MaSzyna), never into the game + files.scenery = folder; + if (auto data = lua_sandbox::scenery_data_folder(user_config_path("scenery_data"), Global.SceneryFile); data != files.data) { + files.data = std::move(data); + auto const name = files.data.u8string(); + if (!name.empty()) + WriteLog("lua: the scenery scripts write their files (eu07.write_file) to \"" + std::string(name.begin(), name.end()) + "\"", logtype::lua); + } // a relative path inside the scenery folder, a file of text, run in protected mode: a script that fails stops // there, and the scenery goes on loading if (auto const error = lua_sandbox::run_script_file(state, folder, file)) { diff --git a/scripting/lua.h b/scripting/lua.h index 8663103df..a0a2b9333 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -1,6 +1,7 @@ #pragma once #include #include +#include "scripting/luasandbox.h" class basic_event; class TMemCell; @@ -11,6 +12,9 @@ class lua { lua_State *state; bool full_libraries = false; // lua.fulllibraries: all of LuaJIT's libraries opened + // what eu07.read_file reads (the scenery folder) and eu07.write_file writes (the scenery's data folder), known + // when the scenery loads its scripts (interpret()) + lua_sandbox::file_folders files; static int atpanic(lua_State *s); diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index ea5f98a88..bf6ab3961 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include #include namespace lua_sandbox @@ -121,22 +123,23 @@ bool load_text_chunk(lua_State *L, std::string_view const Code, std::string cons return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); } -std::optional read_script_file(std::string const &Folder, std::string_view const Path) +std::optional read_file(std::filesystem::path const &Folder, std::string_view const Path, std::uintmax_t const Limit) { - if (false == script_screens::is_safe_relative_path(Path)) + // a NUL would end the name the system sees + if (false == script_screens::is_safe_relative_path(Path) || Path.find('\0') != std::string_view::npos) { return std::nullopt; } // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens // its files - std::filesystem::path const path{Folder + with_forward_slashes(Path)}; + auto const path{Folder / with_forward_slashes(Path)}; std::error_code error; if (false == std::filesystem::is_regular_file(path, error)) { return std::nullopt; } auto const size{std::filesystem::file_size(path, error)}; - if (error || size > max_script_file) + if (error || size > Limit) { return std::nullopt; } @@ -152,6 +155,11 @@ std::optional read_script_file(std::string const &Folder, std::stri return contents; } +std::optional read_script_file(std::string const &Folder, std::string_view const Path) +{ + return read_file(std::filesystem::path{Folder}, Path, max_script_file); +} + std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view const Path) { auto const name{Folder + std::string{Path}}; @@ -172,4 +180,264 @@ std::optional run_script_file(lua_State *L, std::string const &Fold return std::nullopt; } +namespace +{ + +char lower_case(char const Character) +{ + return Character >= 'A' && Character <= 'Z' ? static_cast(Character - 'A' + 'a') : Character; +} + +// the names Windows opens as its devices, whatever the extension +bool is_device_name(std::string_view Name) +{ + // the extension, and the spaces before it, don't count ("nul.txt", "con .log") + Name = Name.substr(0, Name.find('.')); + while (false == Name.empty() && Name.back() == ' ') + { + Name.remove_suffix(1); + } + std::string name; + std::ranges::transform(Name, std::back_inserter(name), lower_case); + if (name == "con" || name == "prn" || name == "aux" || name == "nul" || name == "conin$" || name == "conout$") + { + return true; + } + return name.size() == 4 && (name.starts_with("com") || name.starts_with("lpt")) && name[3] >= '0' && name[3] <= '9'; +} + +// a name of a file or a folder that every system takes as it is +bool is_portable_name(std::string_view const Name) +{ + if (Name.empty() || Name == "." || Name == ".." || Name.back() == '.' || Name.back() == ' ') + { + return false; + } + for (auto const character : Name) + { + if (static_cast(character) < 0x20 || character == 0x7f || + std::string_view{"<>:\"|?*"}.find(character) != std::string_view::npos) + { + return false; + } + } + return false == is_device_name(Name); +} + +// true when Path, a canonical path, is Folder, a canonical path, or inside it +bool is_inside(std::filesystem::path const &Path, std::filesystem::path const &Folder) +{ + return std::mismatch(Folder.begin(), Folder.end(), Path.begin(), Path.end()).first == Folder.end(); +} + +file_folders const &folders_of(lua_State *L) +{ + return *static_cast(lua_touserdata(L, lua_upvalueindex(1))); +} + +std::string_view check_text(lua_State *L, int const Index) +{ + std::size_t length{0}; + auto const *text{luaL_checklstring(L, Index, &length)}; + return {text, length}; +} + +void push_contents(lua_State *L, std::optional const &Contents) +{ + if (Contents.has_value()) + { + lua_pushlstring(L, Contents->data(), Contents->size()); + } + else + { + lua_pushnil(L); + } +} + +// eu07.read_file(path): the contents of a file of the scenery folder, or nil +int api_read_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.scenery.empty() ? std::nullopt : read_file(folders.scenery, path, max_script_file)); + return 1; +} + +// eu07.read_data_file(path): the contents of a file of the scenery's data folder, or nil +int api_read_data_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.data.empty() ? std::nullopt : read_file(folders.data, path, max_data_file)); + return 1; +} + +// eu07.write_file(path, text): writes the file of the scenery's data folder. true, or nil and why not +int api_write_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const contents{check_text(L, 2)}; + if (auto const error{write_data_file(folders_of(L).data, path, contents)}; error.has_value()) + { + lua_pushnil(L); + lua_pushlstring(L, error->data(), error->size()); + return 2; + } + lua_pushboolean(L, 1); + return 1; +} + +} // namespace + +bool is_safe_write_path(std::string_view const Path) +{ + if (Path.size() > max_data_path || false == script_screens::is_safe_relative_path(Path)) + { + return false; + } + std::size_t names{0}; + std::size_t start{0}; + while (start <= Path.size()) + { + auto const end{std::min(Path.find_first_of("/\\", start), Path.size())}; + if (false == is_portable_name(Path.substr(start, end - start))) + { + return false; + } + ++names; + start = end + 1; + } + // the folders, and the file in them + return names <= max_data_depth + 1; +} + +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view const Path, std::string_view const Contents) +{ + namespace fs = std::filesystem; + std::string const name{Path}; + if (Folder.empty()) + { + return name + ": no folder to write to (the game knows no folder of the player)"; + } + if (false == is_safe_write_path(Path)) + { + return name + ": not a path to write to (a relative path of portable names, at most " + std::to_string(max_data_path) + + " bytes and " + std::to_string(max_data_depth) + " folders deep, without '..')"; + } + if (Contents.size() > max_data_file) + { + return name + ": larger than " + std::to_string(max_data_file) + " bytes"; + } + auto const target{Folder / with_forward_slashes(Path)}; + std::error_code error; + // a link, a folder or anything else that isn't a file stays as it is + auto const status{fs::symlink_status(target, error)}; + auto const exists{status.type() != fs::file_type::not_found}; + if (exists && status.type() != fs::file_type::regular) + { + return name + ": not a file"; + } + std::uintmax_t replaced{0}; + if (exists) + { + replaced = fs::file_size(target, error); + if (error) + { + return name + ": can't be replaced"; + } + } + // what the folder holds, and will hold with the file in place of what was there + std::uintmax_t held{0}; + std::size_t files{0}; + if (fs::is_directory(Folder, error)) + { + for (fs::recursive_directory_iterator entry{Folder, error}, end; !error && entry != end; entry.increment(error)) + { + std::error_code entryerror; + if (entry->symlink_status(entryerror).type() == fs::file_type::regular) + { + auto const size{entry->file_size(entryerror)}; + held += entryerror ? 0 : size; + ++files; + } + } + if (error) + { + return name + ": the data folder can't be read"; + } + } + if (files + (exists ? 0 : 1) > max_data_files) + { + return name + ": the data folder holds " + std::to_string(max_data_files) + " files already"; + } + if (held - std::min(replaced, held) + Contents.size() > max_data_folder) + { + return name + ": the data folder would hold more than " + std::to_string(max_data_folder) + " bytes"; + } + fs::create_directories(target.parent_path(), error); + if (error) + { + return name + ": its folder can't be made"; + } + // still inside the data folder, should a link in it lead elsewhere + auto const root{fs::canonical(Folder, error)}; + auto const parent{error ? fs::path{} : fs::canonical(target.parent_path(), error)}; + if (error || false == is_inside(parent, root)) + { + return name + ": outside the data folder"; + } + std::ofstream file{parent / target.filename(), std::ios::binary | std::ios::trunc}; + if (false == file.is_open()) + { + return name + ": can't be opened to write"; + } + file.write(Contents.data(), static_cast(Contents.size())); + file.close(); + if (file.fail()) + { + return name + ": couldn't be written whole"; + } + return std::nullopt; +} + +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view const Scenery) +{ + auto name{with_forward_slashes(Scenery)}; + if (name.size() >= 4) + { + std::string extension; + std::ranges::transform(std::string_view{name}.substr(name.size() - 4), std::back_inserter(extension), lower_case); + if (extension == ".scn") + { + name.resize(name.size() - 4); + } + } + if (Root.empty() || false == is_safe_write_path(name)) + { + return {}; + } + return Root / name; +} + +void open_file_library(lua_State *L, file_folders const *Folders) +{ + // eu07, which the scenery scripts have for eu07.events, made when there is none + lua_getglobal(L, "eu07"); + if (false == lua_istable(L, -1)) + { + lua_pop(L, 1); + lua_newtable(L); + lua_pushvalue(L, -1); + lua_setglobal(L, "eu07"); + } + for (auto const &[name, function] : {std::pair{"read_file", api_read_file}, std::pair{"write_file", api_write_file}, + std::pair{"read_data_file", api_read_data_file}}) + { + lua_pushlightuserdata(L, const_cast(Folders)); + lua_pushcclosure(L, function, 1); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); +} + } // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h index 167060026..5f57c62af 100644 --- a/scripting/luasandbox.h +++ b/scripting/luasandbox.h @@ -15,7 +15,9 @@ http://mozilla.org/MPL/2.0/. #include +#include #include +#include #include #include #include @@ -51,4 +53,49 @@ std::optional read_script_file(std::string const &Folder, std::stri // it ran, otherwise why it didn't std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view Path); +// the files a scenery script reads and writes itself (eu07.read_file, eu07.write_file, eu07.read_data_file): it reads +// the files of the scenery folder, and writes only into a data folder of its scenery, outside the game + +// the largest file a script writes, all the files of a data folder together, and how many files a data folder holds +constexpr std::uintmax_t max_data_file{1024 * 1024}; +constexpr std::uintmax_t max_data_folder{16 * 1024 * 1024}; +constexpr std::size_t max_data_files{256}; +// the longest path a script writes to, and how many folders deep it goes +constexpr std::size_t max_data_path{200}; +constexpr std::size_t max_data_depth{8}; + +// the file Path of Folder, when Path is a relative path inside Folder (as read_script_file) and names a regular file of +// at most Limit bytes. nothing otherwise +std::optional read_file(std::filesystem::path const &Folder, std::string_view Path, std::uintmax_t Limit); + +// true for a path a script may write to: a relative path inside the folder (is_safe_relative_path), '/' or '\' between +// the folders, at most max_data_path bytes and max_data_depth folders deep, each name portable: not empty, not '.' or +// '..', none of the characters Windows refuses (: < > " | ? * and the control characters), no '.' or ' ' at the end, +// and not a device of Windows (con, prn, aux, nul, com0-9, lpt0-9, conin$, conout$, with an extension or without) +bool is_safe_write_path(std::string_view Path); + +// writes Contents to the file Path of Folder (a data folder), replacing what was there, and makes Folder and the folders +// of Path. refused for a path that isn't safe (is_safe_write_path), for more than max_data_file bytes, when Folder would +// hold more than max_data_files files or max_data_folder bytes, when Path names something else than a file, and when it +// leads out of Folder through a link. nothing when written, otherwise why not +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view Path, std::string_view Contents); + +// the data folder of the scenery Scenery (its .scn file, relative to the scenery folder) in Root: Root and the file +// without ".scn" (td.scn: Root/td). empty when Root is, or the name isn't a safe path (is_safe_write_path) +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view Scenery); + +// where the file functions of a scenery script read and write +struct file_folders +{ + // the scenery folder, which eu07.read_file reads, ending with a separator. empty: nothing is read + std::string scenery; + // the data folder of the scenery, which eu07.write_file writes and eu07.read_data_file reads. empty: nothing is + // written there or read from it + std::filesystem::path data; +}; + +// adds eu07.read_file(path), eu07.write_file(path, text) and eu07.read_data_file(path) to the state, on the folders of +// Folders, read on every call: Folders is to outlive the state +void open_file_library(lua_State *L, file_folders const *Folders); + } // namespace lua_sandbox diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp index 6768e27ed..344f51c63 100644 --- a/tests/unit/test_lua_sandbox.cpp +++ b/tests/unit/test_lua_sandbox.cpp @@ -12,6 +12,7 @@ #include "scripting/luasandbox.h" #include "scratch.h" +#include #include #include #include @@ -218,4 +219,209 @@ TEST_CASE("lua sandbox: a scenery script runs in protected mode, and its errors CHECK(lua.run("return ran") == "11"); } +TEST_CASE("lua sandbox: eu07.read_file reads a file of the scenery folder, and nothing outside it") { + test::scratch_folder const root{"lua_sandbox_read"}; + root.write("outside.txt", "secret"); + root.write("scenery/data.txt", "line 1\nline 2"); + root.write("scenery/sub/more.txt", "more"); + root.write("scenery/folder/inner.txt", "inner"); + auto const folder{std::filesystem::path{root.path("scenery")}}; + + CHECK(lua_sandbox::read_file(folder, "data.txt", 100) == std::optional{"line 1\nline 2"}); + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 100) == std::optional{"more"}); + CHECK(lua_sandbox::read_file(folder, "sub\\more.txt", 100) == std::optional{"more"}); + // the limit is the caller's + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 4).has_value()); + CHECK_FALSE(lua_sandbox::read_file(folder, "sub/more.txt", 3).has_value()); + for (auto const &path : {std::string{"../outside.txt"}, std::string{"sub/../../outside.txt"}, std::string{"..\\outside.txt"}, + std::string{"sub\\..\\..\\outside.txt"}, root.path("outside.txt"), std::string{"/outside.txt"}, + std::string{"\\outside.txt"}, std::string{"C:outside.txt"}, std::string{"missing.txt"}, + std::string{"folder"}, std::string{}, std::string{"data.txt\0x", 10}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_file(folder, path, 100).has_value()); + } +} + +TEST_CASE("lua sandbox: the paths a script may write to") { + for (auto const *path : {"state.txt", "saves/state.txt", "saves\\state.txt", "a/b/c/d/e/f/g/h/file.txt", "con_log.txt", "comx.txt", + "com10.txt", "nul_state", ".hidden", "stan poci\xc4\x85gu.txt", "a..b"}) { + CAPTURE(path); + CHECK(lua_sandbox::is_safe_write_path(path)); + } + for (auto const &path : {std::string{}, std::string{".."}, std::string{"../x.txt"}, std::string{"a/../../x.txt"}, std::string{"..\\x.txt"}, + std::string{"/x.txt"}, std::string{"\\x.txt"}, std::string{"C:x.txt"}, std::string{"C:\\x.txt"}, + std::string{"x.txt:stream"}, std::string{"a//b.txt"}, std::string{"a/"}, std::string{"./x.txt"}, + std::string{"a/./x.txt"}, std::string{"con"}, std::string{"CON.txt"}, std::string{"saves/nul.dat"}, + std::string{"Com1"}, std::string{"lpt9.log"}, std::string{"aux"}, std::string{"prn.x.y"}, + std::string{"conin$"}, std::string{"CONOUT$.txt"}, std::string{"con .txt"}, std::string{"ab"}, std::string{"a\"b"}, std::string{"a|b"}, std::string{"a?b"}, std::string{"a*b"}, + std::string{"x."}, std::string{"x "}, std::string{"dir./x"}, std::string{"a\tb"}, std::string{"a\nb"}, + std::string{"a\0b", 3}, std::string{"a/b/c/d/e/f/g/h/i/file.txt"}, + std::string(lua_sandbox::max_data_path + 1, 'x')}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::is_safe_write_path(path)); + } + CHECK(lua_sandbox::is_safe_write_path(std::string(lua_sandbox::max_data_path, 'x'))); +} + +TEST_CASE("lua sandbox: a script writes into its data folder only, and reads back what it wrote") { + test::scratch_folder const root{"lua_sandbox_write"}; + root.write("outside.txt", "kept"); + auto const data{root.root() / "data" / "td"}; + + // the folder is made with the first file + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=1").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=1"}); + // replaced, not appended + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=2").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=2"}); + // any bytes, and the folders of the path + std::string const bytes{"a\0b\r\n\xff", 6}; + CHECK_FALSE(lua_sandbox::write_data_file(data, "saves\\day 1/bin.dat", bytes).has_value()); + CHECK(lua_sandbox::read_file(data, "saves/day 1/bin.dat", lua_sandbox::max_data_file) == std::optional{bytes}); + CHECK_FALSE(lua_sandbox::write_data_file(data, "empty.txt", "").has_value()); + CHECK(lua_sandbox::read_file(data, "empty.txt", lua_sandbox::max_data_file) == std::optional{""}); + + // nothing outside the folder + for (auto const *path : {"../outside.txt", "../../outside.txt", "..\\outside.txt", "saves/../../outside.txt", "nul", "con.txt", "x:y"}) { + CAPTURE(path); + auto const error{lua_sandbox::write_data_file(data, path, "overwritten")}; + REQUIRE(error.has_value()); + CHECK(contains(*error, "not a path to write to")); + } + CHECK(lua_sandbox::write_data_file(data, root.path("outside.txt"), "overwritten").has_value()); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"kept"}); + // a folder isn't replaced by a file + auto const folder{lua_sandbox::write_data_file(data, "saves", "x")}; + REQUIRE(folder.has_value()); + CHECK(contains(*folder, "not a file")); + CHECK(std::filesystem::is_directory(data / "saves")); + // no folder (the game knows no folder of the player), nothing written + CHECK(lua_sandbox::write_data_file(std::filesystem::path{}, "state.txt", "x").has_value()); +} + +TEST_CASE("lua sandbox: the limits of a data folder") { + test::scratch_folder const root{"lua_sandbox_limits"}; + auto const data{root.root() / "data"}; + std::string const full(static_cast(lua_sandbox::max_data_file), 'x'); + + SUBCASE("a file") { + CHECK_FALSE(lua_sandbox::write_data_file(data, "full.txt", full).has_value()); + CHECK(lua_sandbox::read_file(data, "full.txt", lua_sandbox::max_data_file).has_value()); + auto const over{lua_sandbox::write_data_file(data, "full.txt", full + "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "larger than")); + // the file stays as it was + CHECK(std::filesystem::file_size(data / "full.txt") == lua_sandbox::max_data_file); + } + SUBCASE("the bytes of the folder") { + auto const files{static_cast(lua_sandbox::max_data_folder / lua_sandbox::max_data_file)}; + for (int idx = 0; idx < files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("part{}.dat", idx), full).has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.dat", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "more than")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.dat")); + // a file replaced counts with its new size: as large again fits, and a smaller one makes room + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", full).has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", "small").has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "one_more.dat", "x").has_value()); + } + SUBCASE("the files of the folder") { + for (std::size_t idx = 0; idx < lua_sandbox::max_data_files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("sub{}/file{}.txt", idx % 4, idx), "x").has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.txt", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "files already")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.txt")); + // one that is there is still replaced + CHECK_FALSE(lua_sandbox::write_data_file(data, "sub0/file0.txt", "y").has_value()); + } +} + +TEST_CASE("lua sandbox: a link in the data folder doesn't lead a write out of it") { + test::scratch_folder const root{"lua_sandbox_link"}; + root.write("outside/kept.txt", "kept"); + auto const data{root.root() / "data"}; + std::filesystem::create_directories(data); + std::error_code error; + std::filesystem::create_directory_symlink(root.root() / "outside", data / "link", error); + if (error) { + // Windows makes links only for an administrator or in developer mode + MESSAGE("no folder link made (" << error.message() << "), not tested"); + return; + } + auto const written{lua_sandbox::write_data_file(data, "link/kept.txt", "overwritten")}; + REQUIRE(written.has_value()); + CHECK(contains(*written, "outside the data folder")); + CHECK(lua_sandbox::read_file(root.root(), "outside/kept.txt", 100) == std::optional{"kept"}); +} + +TEST_CASE("lua sandbox: the data folder of a scenery") { + std::filesystem::path const root{"user/scenery_data"}; + CHECK(lua_sandbox::scenery_data_folder(root, "td.scn") == root / "td"); + CHECK(lua_sandbox::scenery_data_folder(root, "Td.SCN") == root / "Td"); + CHECK(lua_sandbox::scenery_data_folder(root, "lines\\l107.scn") == root / "lines/l107"); + CHECK(lua_sandbox::scenery_data_folder(root, "test.scm") == root / "test.scm"); + for (auto const *scenery : {"", ".scn", "../td.scn", "/td.scn", "C:td.scn", "con.scn"}) { + CAPTURE(scenery); + CHECK(lua_sandbox::scenery_data_folder(root, scenery).empty()); + } + CHECK(lua_sandbox::scenery_data_folder(std::filesystem::path{}, "td.scn").empty()); +} + +TEST_CASE("lua sandbox: the file functions of a scenery script") { + test::scratch_folder const root{"lua_sandbox_api"}; + root.write("outside.txt", "secret"); + root.write("scenery/settings.txt", "speed=40"); + lua_sandbox::file_folders folders{root.path("scenery") + "/", root.root() / "data" / "td"}; + + sandboxed_state const lua; + // next to eu07.events, as the scenery state has it + REQUIRE_FALSE(luaL_dostring(lua.get(), "eu07 = { events = { marker = 1 } }")); + lua_sandbox::open_file_library(lua.get(), &folders); + auto const top{lua_gettop(lua.get())}; + + CHECK(lua.run("return eu07.events.marker") == "1"); + CHECK(lua.run("return eu07.read_file('settings.txt')") == "speed=40"); + CHECK(lua.run("return eu07.read_file('../outside.txt')") == "nil"); + CHECK(lua.run("return eu07.read_file('missing.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.write_file('state.txt', 'runs=' .. 1)") == "true"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "runs=1"); + // the scenery folder and the data folder are apart + CHECK(lua.run("return eu07.read_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('../../scenery/settings.txt')") == "nil"); + // a number is written as its text + CHECK(lua.run("return eu07.write_file('number.txt', 42)") == "true"); + CHECK(lua.run("return eu07.read_data_file('number.txt')") == "42"); + // a refused write gives nil and the reason + CHECK(lua.run("local ok, reason = eu07.write_file('../outside.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil ../outside.txt: not a path to write to (a relative path of portable names, at most 200 bytes and 8 folders deep, without '..')"); + CHECK(lua.run("local ok, reason = eu07.write_file('big.txt', string.rep('x', 1024 * 1024 + 1)) return reason") == + "big.txt: larger than 1048576 bytes"); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"secret"}); + // the arguments are checked + CHECK(contains(lua.run("return eu07.write_file('x.txt')"), "bad argument #2")); + CHECK(contains(lua.run("return eu07.read_file()"), "bad argument #1")); + CHECK(contains(lua.run("return eu07.write_file({}, 'x')"), "bad argument #1")); + + // the folders are read on every call: without a data folder nothing is written or read there + folders.data.clear(); + CHECK(lua.run("local ok, reason = eu07.write_file('state.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil state.txt: no folder to write to (the game knows no folder of the player)"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua_gettop(lua.get()) == top); +} + +TEST_CASE("lua sandbox: the file functions make eu07 when there is none") { + lua_sandbox::file_folders const folders; + sandboxed_state const lua; + lua_sandbox::open_file_library(lua.get(), &folders); + CHECK(lua.run("return type(eu07.read_file) .. type(eu07.write_file) .. type(eu07.read_data_file)") == "functionfunctionfunction"); + CHECK(lua.run("return eu07.read_file('x.txt')") == "nil"); +} + #endif From 33609881449216d2731cdc6501ba3907279e88f9 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 10:28:06 +0100 Subject: [PATCH 12/59] feat(physics): criteria of derailment: overturning and flange climbing held over 2 m McZapkie/derailment.{h,cpp} in eu07_core: plain functions of the vehicle and the track under it, for the speed in a curve now and the collisions and the buckled track later. - overturning: the wheel unloading D = 2/s * a/g * (h + s0 (h - hc)) of the lateral acceleration the cant doesn't balance, v^2/R - g sin(cant), with the lean of the body on its suspension (s0 0.4, hc 0.5 m of the kinematic gauge), a lateral vibration of 0.05 g and the uneven track; over at D = 1 - flange climbing: Y/Q of the flanging wheel over 1.2 (Nadal, 70 degrees, friction 0.36). Y from the force the cant doesn't balance, the sideways part of the forces of the couplings in the curve and the guiding force of the leading axle; Q with the load the lateral forces move onto the wheel and the twist of the track takes off it - either has to hold over 2 m of track (the window of EN 14363), so the decision doesn't depend on the step - the centre of gravity of a vehicle from the height of its body, raised by the load; the friction of a vehicle sliding off the rails --- CMakeLists.txt | 1 + McZapkie/derailment.cpp | 232 +++++++++++++++++++++++++++++++++ McZapkie/derailment.h | 204 +++++++++++++++++++++++++++++ tests/unit/test_derailment.cpp | 227 ++++++++++++++++++++++++++++++++ 4 files changed, 664 insertions(+) create mode 100644 McZapkie/derailment.cpp create mode 100644 McZapkie/derailment.h create mode 100644 tests/unit/test_derailment.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..76f359eab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -537,6 +537,7 @@ set(CORE_SOURCES "McZapkie/hamulce.cpp" "McZapkie/Mover.cpp" "McZapkie/couplerphysics.cpp" +"McZapkie/derailment.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp new file mode 100644 index 000000000..382c5c14e --- /dev/null +++ b/McZapkie/derailment.cpp @@ -0,0 +1,232 @@ +/* +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 "derailment.h" + +#include +#include + +namespace derailment { + +namespace { + +// a curve with a radius under this is taken for a straight track [m] +constexpr double straight{1e-3}; + +bool curved(double const Radius) { + return std::abs(Radius) > straight; +} + +// the height the lateral force on the body acts at, with the lean of the body on its suspension [m] +double leaning_height(double const CentreOfGravity, suspension const &Suspension) { + return CentreOfGravity + Suspension.flexibility * std::max(0.0, CentreOfGravity - Suspension.roll_centre); +} + +bool has(int const Flags, int const Flag) { + return (Flags & Flag) != 0; +} + +// the acceleration [m/s2] of what moves with the track sideways, besides the curve: the sway of the body and the +// short waves of an uneven track +double dynamic_acceleration(track_state const &Track, double const Velocity) { + return body_vibration(Velocity) + uneven_share * Velocity * Velocity * std::abs(Track.uneven_curvature); +} + +// the sideways force of the couplings of both ends on the vehicle, positive out of the curve [N]: pushed in, the +// ends go out of the curve, pulled out, they go into it +double coupling_force(vehicle_state const &Vehicle, track_state const &Track) { + auto force{0.0}; + for (auto const &end : Vehicle.ends) { + force += end.compression * std::sin(coupling_angle(Vehicle.length, end.other_length, Track.radius)); + } + return force; +} + +} // namespace + +double contact_spacing(double const Gauge) { + return Gauge + rail_head_width; +} + +double default_centre_of_gravity(double const BodyHeight, vehicle_class const Class) { + auto const body{BodyHeight > 2.0 ? BodyHeight : 4.0}; + return body * (Class == vehicle_class::powered ? 0.38 : 0.35); +} + +double loaded_centre_of_gravity(double const EmptyHeight, double const EmptyMass, double const LoadMass, double const LoadShare, double const Floor, double const BodyHeight) { + if (LoadMass <= 0.0 || EmptyMass + LoadMass <= 0.0) { + return EmptyHeight; + } + auto const body{BodyHeight > 2.0 ? BodyHeight : 4.0}; + // a floor not given (or the older meaning of the keys) is that of a wagon + auto const floor{Floor > 0.3 ? Floor : 1.2}; + auto const load{floor + 0.5 * std::max(0.0, body - floor) * std::clamp(LoadShare, 0.0, 1.0)}; + return (EmptyHeight * EmptyMass + load * LoadMass) / (EmptyMass + LoadMass); +} + +double unbalanced_acceleration(double const Velocity, double const Radius, double const Cant) { + auto const cant{gravity * std::sin(std::abs(Cant))}; + if (false == curved(Radius)) { + return -cant; + } + return Velocity * Velocity / std::abs(Radius) - cant; +} + +double unloading_ratio(double const Acceleration, double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { + return 2.0 / ContactSpacing * std::abs(Acceleration) / gravity * leaning_height(CentreOfGravity, Suspension); +} + +double overturning_acceleration(double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { + return gravity * ContactSpacing / (2.0 * leaning_height(CentreOfGravity, Suspension)); +} + +double body_vibration(double const Velocity) { + return vibration * std::min(1.0, std::abs(Velocity) / (100.0 / 3.6)); +} + +double overturning_speed(double const Radius, double const Cant, double const CentreOfGravity, double const Gauge) { + if (false == curved(Radius)) { + return 0.0; + } + vehicle_state vehicle; + vehicle.mass = 1.0; + vehicle.centre_of_gravity = CentreOfGravity; + track_state track; + track.radius = Radius; + track.cant = Cant; + track.gauge = Gauge; + auto const spacing{contact_spacing(Gauge)}; + // the unloading grows with the speed: halve the range until the speed of D = 1 is found + auto low{0.0}; + auto high{200.0}; + for (int iteration = 0; iteration < 60; ++iteration) { + auto const middle{0.5 * (low + high)}; + auto const acceleration{body_acceleration(vehicle, track, middle)}; + // below the balancing speed the cant leans the vehicle the other way + auto const outwards{unbalanced_acceleration(middle, Radius, Cant) > 0.0}; + if (outwards && unloading_ratio(acceleration, CentreOfGravity, spacing) >= 1.0) { + high = middle; + } + else { + low = middle; + } + } + return high; +} + +double nadal_limit(double const FlangeAngle, double const Friction) { + auto const slope{std::tan(FlangeAngle)}; + return (slope - Friction) / (1.0 + Friction * slope); +} + +track_condition condition_of(track_state const &Track) { + track_condition condition; + // as the legacy criterion had it, a loose rail sways the vehicles 1.4 times as much + condition.lateral = 1.0 + 0.4 * has(Track.damage, track_damage::freerail) + 0.5 * has(Track.damage, track_damage::railbend) + 0.1 * has(Track.damage, track_damage::railwear) + + 0.1 * has(Track.damage, track_damage::thinrail); + // the twist of the track lifts a wheel: 1 % of its load for each mm of cross level, up to the 0.6 the twist test + // of EN 14363 lets the load drop by + condition.unloading = std::min(0.6, 0.01 * std::max(0.0, Track.uneven_cross) + 0.1 * has(Track.damage, track_damage::freerail) + 0.1 * has(Track.damage, track_damage::railbend)); + return condition; +} + +double coupling_angle(double const Length, double const OtherLength, double const Radius) { + if (false == curved(Radius) || OtherLength <= 0.0) { + return 0.0; + } + return (Length + OtherLength) / (4.0 * std::abs(Radius)); +} + +wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + wheel_forces result; + if (Vehicle.mass <= 0.0) { + return result; + } + auto const axles{static_cast(std::max(Vehicle.axles, 1))}; + auto const condition{condition_of(Track)}; + auto const spacing{contact_spacing(Track.gauge)}; + auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; + auto const staticload{Vehicle.mass * gravity / (2.0 * axles)}; + + auto const inertia{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant)}; + auto const couplings{coupling_force(Vehicle, Track)}; + auto const quasistatic{inertia + couplings}; + // the sway and the uneven track push the worst way: towards the rail the vehicle already leans on + auto const direction{quasistatic >= 0.0 ? 1.0 : -1.0}; + auto const dynamic{Vehicle.mass * dynamic_acceleration(Track, Velocity)}; + result.lateral = direction * (std::abs(quasistatic) + dynamic) * condition.lateral; + + // the leading axle meets the rail at an angle in a curve, the creep force of its inner wheel at most the friction + auto guiding{0.0}; + if (curved(Track.radius)) { + auto const attack{Vehicle.axle_base / (2.0 * std::abs(Track.radius))}; + guiding = tread_friction * staticload * std::min(1.0, attack / saturated_attack); + } + result.y = std::abs(result.lateral) / axles + guiding; + + // the lateral forces at their heights move the load onto the wheels they push towards + auto const moment{(direction * (inertia * height + couplings * buffer_height) + dynamic * height) * condition.lateral}; + auto const shift{moment / (spacing * axles)}; + result.q = std::max(0.0, (staticload + shift) * (1.0 - condition.unloading)); + return result; +} + +double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + if (Vehicle.mass <= 0.0) { + return 0.0; + } + auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; + // the couplings pull at the height of the buffers: as much of a lean as their moment gives + auto const moment{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant) * height + coupling_force(Vehicle, Track) * buffer_height}; + return (std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity)) * condition_of(Track).lateral; +} + +bool stretch::update(bool const Holds, double const Distance, double const Window) { + if (false == Holds) { + m_distance = 0.0; + return false; + } + m_distance += std::abs(Distance); + return m_distance >= Window; +} + +verdict monitor::update(vehicle_state const &Vehicle, track_state const &Track, double const Velocity, double const Distance) { + verdict result; + result.acceleration = body_acceleration(Vehicle, Track, Velocity); + result.unloading = unloading_ratio(result.acceleration, Vehicle.centre_of_gravity, contact_spacing(Track.gauge)); + result.flange_ratio = flange_forces(Vehicle, Track, Velocity).ratio(); + auto const overturns{m_overturning.update(result.unloading >= 1.0, Distance)}; + auto const climbs{m_climbing.update(result.flange_ratio >= climbing_limit, Distance)}; + if (overturns) { + result.result = outcome::overturned; + } + else if (climbs) { + result.result = outcome::off_rails; + } + return result; +} + +void monitor::reset() { + m_overturning.reset(); + m_climbing.reset(); +} + +double sliding_friction(outcome const Outcome) { + switch (Outcome) { + case outcome::off_rails: + return off_rails_friction; + case outcome::overturned: + return overturned_friction; + default: + return 0.0; + } +} + +} // namespace derailment diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h new file mode 100644 index 000000000..39999d878 --- /dev/null +++ b/McZapkie/derailment.h @@ -0,0 +1,204 @@ +/* +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 + +// the criteria of a vehicle leaving the rails, as plain functions of what the vehicle and the track under it are +// like, so the collisions and the buckled track can use them as well as the speed in a curve does +// (physics.derailment new in eu07.ini, see TMoverParameters::check_derailment()). two ways off the rails: +// +// overturning: the lateral acceleration the cant doesn't balance, a = v^2 / R - g * sin(cant), takes the load off the +// inner wheels; the unloading ratio D = dQ / Q = 2 / s * a / g * (h + s_flex * (h - h_c)) reaches 1 when they lift. +// s the distance between the contact points of the wheels, h the height of the centre of gravity, s_flex and h_c the +// flexibility coefficient and the roll centre height of the suspension, which lets the body lean out of the curve +// (the reference values of the kinematic gauge, EN 15273-2 / UIC 505-1). the body sways on top of that: a lateral +// vibration of 0.05 g at speed (as Kunieda's overturning formula of the Japanese railways adds one) and what the +// uneven track adds +// flange climbing: the ratio of the lateral to the vertical force of the flanging wheel, Y / Q, over Nadal's limit +// (tan d - mu) / (1 + mu * tan d). Y from the force the cant doesn't balance and the sideways part of the forces of +// the couplings in the curve, shared by the axles, plus the guiding force of the leading axle under its angle of +// attack; Q the static wheel load, with what the lateral forces at their heights move onto the wheel +// +// either has to hold over a stretch of track, not at an instant: EN 14363 takes the Y / Q of a 2 m sliding window, so +// a peak shorter than that, or the length of a simulation step, doesn't derail the vehicle +namespace derailment { + +inline constexpr double gravity{9.81}; // [m/s2] + +// the distance between the contact points of the wheels of a wheelset [m]: the gauge and the width of the rail head +// (1.5 m on the standard gauge) +inline constexpr double rail_head_width{0.065}; +double contact_spacing(double Gauge); + +// the suspension of the body, the reference vehicle of the kinematic gauge (EN 15273-2, UIC 505-1) +struct suspension { + double flexibility{0.4}; // roll of the body to the angle of the force on it, s0 + double roll_centre{0.5}; // height of the roll centre above the rail [m], h_c0 +}; + +// ---- the centre of gravity + +// what the vehicle is, for its centre of gravity when its definition gives none +enum class vehicle_class { + powered, // a locomotive, a motor car of a unit + unpowered // a coach, a wagon +}; +// height of the centre of gravity of the empty vehicle above the rail [m], from the height of the body: 0.38 of it for +// a locomotive or a motor car, 0.35 for a coach or a wagon (EU07: 1.65 m, the 430W coal wagon: 1.13 m, a 4 m high +// coach: 1.4 m). a body height up to 2 m in the definition is the height of the floor, the older meaning of the key: +// a 4 m high body is taken then +double default_centre_of_gravity(double BodyHeight, vehicle_class Class); +// the load raises it: the load lies on the floor, its centre half way up to the share of the height of the body +// above the floor it fills (the share of the load it can take), and the heights weigh with the masses [m] +double loaded_centre_of_gravity(double EmptyHeight, double EmptyMass, double LoadMass, double LoadShare, double Floor, double BodyHeight); + +// ---- overturning + +// the lateral acceleration [m/s2] the cant doesn't balance, positive out of the curve: v^2 / R - g sin(cant). the +// sign of the radius and of the cant is left out: the cant lifts the outer rail of a curve. on a straight piece of a +// transition the cant leans the vehicle into the curve to come +double unbalanced_acceleration(double Velocity, double Radius, double Cant); +// D = dQ / Q of the wheels on the inner side, at the lateral acceleration [m/s2] +double unloading_ratio(double Acceleration, double CentreOfGravity, double ContactSpacing, suspension const &Suspension = {}); +// the lateral acceleration [m/s2] which lifts the inner wheels off the rail (D = 1) +double overturning_acceleration(double CentreOfGravity, double ContactSpacing, suspension const &Suspension = {}); +// lateral vibration of the body on a good track [m/s2], growing with the speed up to 100 km/h +inline constexpr double vibration{0.05 * gravity}; +double body_vibration(double Velocity); +// the speed [m/s] at which the vehicle overturns in a curve of the radius [m] and the cant [rad], on a good track +double overturning_speed(double Radius, double Cant, double CentreOfGravity, double Gauge); + +// ---- flange climbing + +// Nadal's limit of Y / Q for the flange angle [rad] and the friction of the flange on the rail +double nadal_limit(double FlangeAngle, double Friction); +// 70 degrees, the flange of the S1002 and the Polish 1:40 profiles +inline constexpr double flange_angle{1.2217304763960306}; +// 1.2: Nadal with 70 degrees and a friction of 0.36 on a dry rail; the limit of EN 14363 for the flange climbing test +// in a tight curve on a twisted track. its 0.8 for the tests on the line is that with a margin for the acceptance of +// a vehicle, and a simulator wants the derailment itself +inline constexpr double climbing_limit{1.2}; +// friction of the tread of the inner wheel of the leading axle, the guiding force it gives under the angle of attack +inline constexpr double tread_friction{0.3}; +// angle of attack [rad] at which the creep force of the tread saturates +inline constexpr double saturated_attack{0.005}; +// height of the buffers and the couplings above the rail [m] (UIC: 940 to 1065 mm) +inline constexpr double buffer_height{1.0}; + +// one end of the vehicle in a train +struct end_force { + double compression{0.0}; // force of the coupling along the vehicle, pushing in [N]; negative pulls out + double other_length{0.0}; // length of the vehicle at that end [m], 0 without one +}; + +// the vehicle as the flange climbing sees it +struct vehicle_state { + double mass{0.0}; // with the load, without the rotating masses [kg] + int axles{4}; + double length{0.0}; // over the buffers [m] + double axle_base{0.0}; // the wheelbase of a bogie, or of the vehicle without bogies [m] + double centre_of_gravity{1.5}; // [m] + std::array ends{}; +}; + +// the dtrack_* flags of the track (MOVER.h) the criteria look at +namespace track_damage { +inline constexpr int railwear{2}; +inline constexpr int freerail{4}; +inline constexpr int thinrail{8}; +inline constexpr int railbend{16}; +} // namespace track_damage + +// the track under the vehicle +struct track_state { + double radius{0.0}; // [m], 0 on a straight one + double cant{0.0}; // [rad] + double gauge{1.435}; // [m] + double uneven_curvature{0.0}; // the lateral curvature of the unevenness under the vehicle [1/m] + double uneven_cross{0.0}; // the cross level unevenness of the track [mm] + int damage{0}; // dtrack_* flags +}; + +// what the state of the track does to the lateral forces and the wheel loads +struct track_condition { + double lateral{1.0}; // multiplier of the lateral acceleration + double unloading{0.0}; // share of the wheel load the twist of the track takes off +}; +track_condition condition_of(track_state const &Track); +// share of the vehicle that follows the short waves of an uneven track: the wheelsets and the bogies, the body not +inline constexpr double uneven_share{0.3}; + +// the angle [rad] between the vehicle and the line of the force of the coupling at the end, in a curve: half the +// angle between the two vehicles, whose middles are half their lengths apart along the curve +double coupling_angle(double Length, double OtherLength, double Radius); + +struct wheel_forces { + double lateral{0.0}; // the lateral force on the vehicle, positive out of the curve [N] + double y{0.0}; // lateral force of the flanging wheel [N] + double q{0.0}; // its vertical force [N] + double ratio() const { return q > 0.0 ? y / q : 1e9; } +}; +// the forces of the flanging wheel of the leading axle, at the speed [m/s] +wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double Velocity); +// the lateral acceleration of the body the overturning goes by [m/s2]: what the cant doesn't balance, the sideways +// pull of the couplings, the vibration and the uneven track, by the state of the track +double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, double Velocity); + +// ---- the stretch a condition holds over + +// the distance [m] a condition has to hold over: the window of EN 14363 +inline constexpr double window{2.0}; + +// the distance travelled while the condition held, without a break. the same distance with any step: a step the +// condition holds at counts with its whole length +class stretch { +public: + // true once the condition held over the window, given the distance of the step [m] + bool update(bool Holds, double Distance, double Window = window); + double distance() const { return m_distance; } + void reset() { m_distance = 0.0; } + +private: + double m_distance{0.0}; +}; + +enum class outcome { + none, + off_rails, // the flange climbed the rail: the vehicle runs off the rails, upright + overturned // the vehicle fell over out of the curve +}; + +// what the vehicle came to in a step, with the values the decision went by +struct verdict { + outcome result{outcome::none}; + double unloading{0.0}; // D + double flange_ratio{0.0}; // Y / Q + double acceleration{0.0}; // of the body, [m/s2] +}; + +// both criteria of a vehicle, step by step +class monitor { +public: + // the step travelled the distance [m]; the condition at its end goes for the whole of it + verdict update(vehicle_state const &Vehicle, track_state const &Track, double Velocity, double Distance); + void reset(); + +private: + stretch m_overturning; + stretch m_climbing; +}; + +// the friction of a derailed vehicle sliding along [-]: on its wheels on the sleepers and the ballast, or on its side +inline constexpr double off_rails_friction{0.3}; +inline constexpr double overturned_friction{0.5}; +double sliding_friction(outcome Outcome); + +} // namespace derailment diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp new file mode 100644 index 000000000..c66c8f72d --- /dev/null +++ b/tests/unit/test_derailment.cpp @@ -0,0 +1,227 @@ +#include "stdafx.h" +#include "doctest.h" +#include "McZapkie/derailment.h" + +#include +#include + +// the criteria of derailment (McZapkie/derailment.h): overturning by the lateral acceleration the cant doesn't +// balance, the flange climbing the rail by Nadal's Y/Q, either held over 2 m + +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the cant [rad] of the height of the outer rail [mm] on the standard gauge +double cant(double const Millimetres) { + return std::asin(Millimetres / 1000.0 / dr::contact_spacing(1.435)); +} + +// the centres of gravity the vehicles of data/fiz get without a CoGH of their own +// EU07 (4E): 80 t, a body 4.348 m high +double const eu07{dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered)}; +// the 430W coal wagon: 20.5 t, a body 3.235 m high, 59.5 t of coal +double const coal_wagon{dr::default_centre_of_gravity(3.235, dr::vehicle_class::unpowered)}; +double const coal_wagon_loaded{dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 59500.0, 1.0, 0.0, 3.235)}; + +} // namespace + +TEST_CASE("derailment: Nadal's limit of Y/Q") { + // 70 degrees of the flange: 1.34 with a friction of 0.3, 1.2 with 0.36, the limit the criterion takes + CHECK(dr::nadal_limit(dr::flange_angle, 0.3) == doctest::Approx(1.342).epsilon(0.001)); + CHECK(dr::nadal_limit(dr::flange_angle, 0.36) == doctest::Approx(dr::climbing_limit).epsilon(0.01)); + // a steeper flange holds more, a higher friction less + CHECK(dr::nadal_limit(dr::flange_angle + 0.05, 0.3) > dr::nadal_limit(dr::flange_angle, 0.3)); + CHECK(dr::nadal_limit(dr::flange_angle, 0.5) < dr::nadal_limit(dr::flange_angle, 0.3)); +} + +TEST_CASE("derailment: the centre of gravity") { + CHECK(eu07 == doctest::Approx(1.65).epsilon(0.01)); + CHECK(coal_wagon == doctest::Approx(1.13).epsilon(0.01)); + // the load raises it: a full coal wagon is near 2 m, the limit of the railways for a loaded wagon is 2 to 2.5 m + CHECK(coal_wagon_loaded == doctest::Approx(1.94).epsilon(0.01)); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 30000.0, 0.5, 0.0, 3.235) > coal_wagon); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 30000.0, 0.5, 0.0, 3.235) < coal_wagon_loaded); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 0.0, 0.0, 0.0, 3.235) == coal_wagon); + // a body height of 2 m or less is the floor, the older meaning of the key: a 4 m high body then + CHECK(dr::default_centre_of_gravity(1.2, dr::vehicle_class::unpowered) == doctest::Approx(1.4)); +} + +TEST_CASE("derailment: the overturning speed by the radius and the cant") { + struct expected { + char const *vehicle; + double centre; + double radius; + double cant; // mm + double speed; // km/h + }; + // EU07 overturns at 108 km/h in a 300 m curve without cant, as the legacy criterion had it near 112 km/h; at + // 119 km/h with a cant of 100 mm. a full coal wagon at 98 km/h, an empty one at 137 km/h + for (auto const &[name, centre, radius, height, speed] : { + expected{"EU07", eu07, 150.0, 0.0, 77.6}, + expected{"EU07", eu07, 300.0, 0.0, 107.8}, + expected{"EU07", eu07, 300.0, 100.0, 119.0}, + expected{"EU07", eu07, 600.0, 150.0, 175.8}, + expected{"430W empty", coal_wagon, 300.0, 0.0, 136.9}, + expected{"430W empty", coal_wagon, 300.0, 100.0, 145.9}, + expected{"430W loaded", coal_wagon_loaded, 300.0, 0.0, 97.5}, + expected{"430W loaded", coal_wagon_loaded, 300.0, 100.0, 109.6}, + expected{"430W loaded", coal_wagon_loaded, 1200.0, 150.0, 230.5}, + }) { + CAPTURE(name); + CAPTURE(radius); + CAPTURE(height); + CHECK(dr::overturning_speed(radius, cant(height), centre, 1.435) / kmh == doctest::Approx(speed).epsilon(0.002)); + } + // on the faster side of 100 km/h, where the vibration is all there: v^2 / R - g sin(cant) + 0.05 g = g s / 2 h' + auto const leaning{eu07 + 0.4 * (eu07 - 0.5)}; + auto const limit{dr::gravity * 1.5 / (2.0 * leaning)}; + CHECK(dr::overturning_acceleration(eu07, 1.5) == doctest::Approx(limit)); + auto const speed{std::sqrt((limit - dr::vibration + dr::gravity * std::sin(cant(100.0))) * 300.0)}; + CHECK(dr::overturning_speed(300.0, cant(100.0), eu07, 1.435) == doctest::Approx(speed).epsilon(0.001)); + // the legacy criterion, the lateral acceleration over g times the gauge to the height of the vehicle, without cant + auto const legacy{std::sqrt(dr::gravity * 1.435 / 4.348 * 300.0)}; + CHECK(dr::overturning_speed(300.0, 0.0, eu07, 1.435) == doctest::Approx(legacy).epsilon(0.05)); + // faster on a wider curve, as its square root + CHECK(dr::overturning_speed(1200.0, 0.0, eu07, 1.435) / dr::overturning_speed(300.0, 0.0, eu07, 1.435) == doctest::Approx(2.0).epsilon(0.001)); + // the cant only helps + CHECK(dr::overturning_speed(300.0, cant(150.0), eu07, 1.435) > dr::overturning_speed(300.0, cant(60.0), eu07, 1.435)); + // no overturning on a straight track + CHECK(dr::overturning_speed(0.0, 0.0, eu07, 1.435) == 0.0); +} + +TEST_CASE("derailment: below the balancing speed the cant leans the vehicle into the curve") { + // 100 mm on the 1.5 m between the contact points of the wheels + CHECK(dr::unbalanced_acceleration(0.0, 300.0, cant(100.0)) == doctest::Approx(-dr::gravity * 0.1 / 1.5)); + // at the balancing speed nothing's left + auto const balanced{std::sqrt(dr::gravity * 0.1 / 1.5 * 300.0)}; + CHECK(dr::unbalanced_acceleration(balanced, 300.0, cant(100.0)) == doctest::Approx(0.0).epsilon(1e-9)); + // the sign of the radius and of the cant doesn't matter + CHECK(dr::unbalanced_acceleration(30.0, -300.0, -cant(100.0)) == doctest::Approx(dr::unbalanced_acceleration(30.0, 300.0, cant(100.0)))); +} + +TEST_CASE("derailment: the decision and the place don't depend on the step") { + // EU07 runs at a steady speed into a 300 m curve without cant 100 m ahead, the track checked at the end of each step + dr::vehicle_state eu07vehicle; + eu07vehicle.mass = 80000.0; + eu07vehicle.axles = 4; + eu07vehicle.length = 15.915; + eu07vehicle.axle_base = 3.05; + eu07vehicle.centre_of_gravity = eu07; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435)}; + constexpr double curve{100.0}; + + // where the vehicle overturns, if it does within 400 m + auto const run = [&](double const Speed, double const Step) -> std::optional { + dr::monitor monitor; + dr::track_state track; + auto distance{0.0}; + while (distance < 400.0) { + auto const travelled{Speed * Step}; + distance += travelled; + track.radius = distance >= curve ? 300.0 : 0.0; + if (monitor.update(eu07vehicle, track, Speed, travelled).result == dr::outcome::overturned) { + return distance; + } + } + return std::nullopt; + }; + + for (auto const step : {0.01, 0.05, 0.5}) { + CAPTURE(step); + // 5 % too fast: overturns 2 m into the curve, give or take the step it got there in + auto const fast{run(1.05 * critical, step)}; + REQUIRE(fast.has_value()); + CHECK(*fast >= curve + dr::window - 1.05 * critical * step - 1e-6); + CHECK(*fast <= curve + dr::window + 1.05 * critical * step + 1e-6); + // 5 % below it: never + CHECK_FALSE(run(0.95 * critical, step).has_value()); + } + auto const fine{run(1.05 * critical, 0.01)}; + auto const coarse{run(1.05 * critical, 0.5)}; + REQUIRE(fine.has_value()); + REQUIRE(coarse.has_value()); + CHECK(std::abs(*coarse - *fine) <= 1.05 * critical * 0.5); +} + +TEST_CASE("derailment: a peak shorter than the window doesn't derail") { + dr::stretch stretch; + CHECK_FALSE(stretch.update(true, 1.5)); + CHECK_FALSE(stretch.update(false, 0.5)); + CHECK_FALSE(stretch.update(true, 1.5)); + CHECK(stretch.update(true, 0.5)); + CHECK(stretch.distance() == doctest::Approx(2.0)); +} + +TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") { + // the empty 3WL (10.5 t, 2 axles 6 m apart, 9.87 m long) between two EU07 in a 150 m curve: the more the train + // pushes, the more the couplings push the wagon out of the curve, the higher its Y/Q + dr::vehicle_state wagon; + wagon.mass = 10500.0; + wagon.axles = 2; + wagon.length = 9.87; + wagon.axle_base = 6.0; + wagon.centre_of_gravity = dr::default_centre_of_gravity(3.0, dr::vehicle_class::unpowered); + dr::track_state track; + track.radius = 150.0; + auto const speed{20.0 * kmh}; + + auto const ratio = [&](dr::vehicle_state Vehicle, double const Compression) { + for (auto &end : Vehicle.ends) { + end.compression = Compression; + end.other_length = 15.915; + } + return dr::flange_forces(Vehicle, track, speed).ratio(); + }; + auto previous{ratio(wagon, 0.0)}; + // the leading axle guides the wagon with the friction of its inner wheel: over 0.3 even unpushed + CHECK(previous > dr::tread_friction); + CHECK(previous < 0.4); + for (auto const compression : {100e3, 300e3, 600e3, 1000e3}) { + CAPTURE(compression); + auto const pushed{ratio(wagon, compression)}; + CHECK(pushed > previous); + previous = pushed; + } + // a loaded 430W in its place is pushed out less + dr::vehicle_state loaded; + loaded.mass = 80000.0; + loaded.axles = 4; + loaded.length = 14.028; + loaded.axle_base = 2.0; + loaded.centre_of_gravity = coal_wagon_loaded; + CHECK(ratio(loaded, 600e3) < ratio(wagon, 600e3)); + // pulled, the couplings draw the wagon into the curve: the flange of the inner wheel then + auto pulled{wagon}; + for (auto &end : pulled.ends) { + end.compression = -600e3; + end.other_length = 15.915; + } + CHECK(dr::flange_forces(pulled, track, speed).lateral < 0.0); + // on a twisted track the wheel is lighter, so the same push comes nearer the limit + auto const twisted{[&] { + auto const flat{ratio(wagon, 600e3)}; + track.uneven_cross = 30.0; + auto const result{ratio(wagon, 600e3)}; + track.uneven_cross = 0.0; + return result > flat; + }()}; + CHECK(twisted); + // on a bent rail, with a twist of 40 mm, the wagon pushed with 300 kN climbs the rail over 2 m, without falling over + track.damage = dr::track_damage::railbend; + track.uneven_cross = 40.0; + dr::monitor monitor; + auto pushed{wagon}; + for (auto &end : pushed.ends) { + end.compression = 300e3; + end.other_length = 15.915; + } + CHECK(monitor.update(pushed, track, speed, 1.0).result == dr::outcome::none); + auto const verdict{monitor.update(pushed, track, speed, 1.0)}; + CAPTURE(verdict.flange_ratio); + CAPTURE(verdict.unloading); + CHECK(verdict.unloading < 1.0); + CHECK(verdict.result == dr::outcome::off_rails); +} From a257d5d8034374734840b695f6d780e108dba95d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 10:28:24 +0100 Subject: [PATCH 13/59] feat(physics): a vehicle too fast in a curve overturns or climbs the rail by the criteria, and slides on physics.derailment in eu07.ini: new (the default) checks the criteria of McZapkie/derailment.h in every full step over the distance travelled since the last one, so the decision doesn't depend on the frame rate; old keeps the per-step draw of the lateral acceleration against the gauge to the height of the vehicle; off, no derailment from the speed. - the cant of the track (dHrail) is taken off the lateral acceleration, the centre of gravity comes from the new optional CoGH key of the Dimensions of the .fiz (from the height of the body otherwise), raised by the load - the forces of the couplings at both ends push the vehicle out of the curve, or pull it into it - the uneven track under the outer axles (its lateral curvature and cross level, new fields of TTrackShape set by TDynamicObject) and the damage flags of the track add to it - off the rails by the criteria the vehicle opens its main switch, keeps its speed and slides with the friction of the ballast (0.3 upright, 0.5 on its side) instead of stopping dead; its torn brake hoses vent the brake pipe, the train brakes in emergency. TMoverParameters::Derailed tells overturned from derailed upright, the log says which with the numbers. Other derailments keep the legacy effects --- McZapkie/MOVER.h | 20 ++++ McZapkie/Mover.cpp | 104 ++++++++++++++++-- tests/unit/test_derailment_vehicle.cpp | 142 +++++++++++++++++++++++++ tests/unit/vehicle.cpp | 2 + tests/unit/vehicle.h | 2 + utilities/Globals.cpp | 18 ++++ utilities/Globals.h | 6 ++ vehicle/DynObj.cpp | 3 + 8 files changed, 291 insertions(+), 6 deletions(-) create mode 100644 tests/unit/test_derailment_vehicle.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index b619ba7de..a1754b7c6 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include #include "hamulce.h" #include "couplerphysics.h" +#include "derailment.h" #include "scripting/ladderlogic.h" #include "vehicle/odometerreading.h" @@ -690,6 +691,10 @@ struct TTrackShape double dHtrack = 0.0; // nachylenie /// Track cant / superelevation. double dHrail = 0.0; // przechylka + /// Lateral curvature of the track unevenness under the vehicle [1/m], see world/TrackUneven.h. + double uneven_curvature = 0.0; + /// Cross level unevenness of the track [mm]. + double uneven_cross = 0.0; }; /// Per-segment track parameters: gauge, friction, category, load capacity, damage. @@ -1654,6 +1659,9 @@ class TMoverParameters TDimension Dim; /*wymiary*/ double Cx = 0.0; /*wsp. op. aerodyn.*/ float Floor = 0.96f; // poziom podłogi dla ładunków + // height of the centre of gravity of the empty vehicle above the rail [m] (CoGH in the Dimensions of the .fiz), + // negative when the definition gives none: derailment::default_centre_of_gravity() then + double CentreOfGravity = -1.0; float WheelDiameter = 1.f; /*srednica kol napednych*/ float WheelDiameterL = 0.9f; // Ra: srednica kol tocznych przednich float WheelDiameterT = 0.9f; // Ra: srednica kol tocznych tylnych @@ -2038,6 +2046,9 @@ class TMoverParameters int SoundFlag = 0; /*!o patrz stale sound_ */ int AIFlag{0}; // HACK: events of interest for consist owner double DistCounter = 0.0; /*! licznik kilometrow */ + // the criteria of derailment (physics.derailment new), and the distance travelled since they were checked [m] + derailment::monitor derailment_monitor; + double derailment_distance = 0.0; odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) std::pair EnergyMeter; // energy from grid [kWh] double V = 0.0; // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) @@ -2424,6 +2435,15 @@ class TMoverParameters // was a broken coupler to repair bool repair_coupler(int const End); void Derail(DerailReason Reason); + // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m] + void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); + // the vehicle leaves the rails, as the criteria of derailment.h found + void derail(derailment::verdict const &Verdict, TTrackShape const &Shape); + // height of the centre of gravity above the rail with the load [m] + double centre_of_gravity() const; + // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other + // derailment, which stops it as the legacy model does + derailment::outcome Derailed{derailment::outcome::none}; bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ bool EIMDirectionChangeAllow(void) const; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..0e9cc3993 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1503,6 +1503,77 @@ bool TMoverParameters::repair_coupler(int const End) return true; } +static_assert(derailment::track_damage::railwear == dtrack_railwear && derailment::track_damage::freerail == dtrack_freerail && derailment::track_damage::thinrail == dtrack_thinrail && + derailment::track_damage::railbend == dtrack_railbend); + +double TMoverParameters::centre_of_gravity() const +{ + auto const kind{EngineType == TEngineType::None ? derailment::vehicle_class::unpowered : derailment::vehicle_class::powered}; + auto const empty{CentreOfGravity > 0.0 ? CentreOfGravity : derailment::default_centre_of_gravity(Dim.H, kind)}; + auto const loadmass{TotalMass - Mass - Mred}; + auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 1.0}; + return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); +} + +void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) +{ + if (TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) + { + derailment_monitor.reset(); + return; + } + derailment::vehicle_state vehicle; + vehicle.mass = TotalMass - Mred; + vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.length = Dim.L; + vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + vehicle.centre_of_gravity = centre_of_gravity(); + for (int end = end::front; end <= end::rear; ++end) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + // the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls + vehicle.ends[end].compression = (end == end::front ? -1.0 : 1.0) * Couplers[end].CForce; + vehicle.ends[end].other_length = other->MoverParameters->Dim.L; + } + derailment::track_state track; + track.radius = Shape.R; + track.cant = Shape.dHrail; + track.gauge = TrackW; + track.uneven_curvature = Shape.uneven_curvature; + track.uneven_cross = Shape.uneven_cross; + track.damage = Track.DamageFlag; + + auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; + if (verdict.result != derailment::outcome::none) + { + derail(verdict, Shape); + } +} + +void TMoverParameters::derail(derailment::verdict const &Verdict, TTrackShape const &Shape) +{ + if (false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + Derailed = Verdict.result; + EventFlag = true; + MainSwitch(false, range_t::local); + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + if (std::any_of(std::begin(Couplers), std::end(Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) + { + AlarmChainFlag = true; + } + auto const cant{1000.0 * derailment::contact_spacing(TrackW) * std::sin(std::abs(Shape.dHrail))}; + ErrorLog(std::format("Bad driving: {} {} at {:.0f} km/h, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}", Name, + Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Shape.R), cant, Verdict.acceleration, + Verdict.unloading, Verdict.flange_ratio)); +} + void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) @@ -1578,7 +1649,8 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out)) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) AccS = -Sign(V) * g * 1; // random(0.0, 0.1) // przyspieszenie normalne @@ -1621,7 +1693,9 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap { if (TestFlag(Track.DamageFlag, dtrack_norail)) Derail(END_OF_TRACK); - if (FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) + // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria + // once the step's distance is known, below + if (Global.derailment == global_settings::derailment_model::old && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) Derail(TOO_HIGH_SPEED); // wykolejanie na poszerzeniu toru if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) @@ -1634,6 +1708,12 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // dL:=(V+AccS*dt/2)*dt; // przyrost dlugosci czyli przesuniecie dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} + if (Global.derailment == global_settings::derailment_model::physical) + { + // over the distance of this step and of the simpler ones of the frame before it + check_derailment(Shape, Track, derailment_distance + std::abs(dL)); + } + derailment_distance = 0.0; // ale jesli jest kolizja (zas. zach. pedu) to...} for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) @@ -1675,7 +1755,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out)) + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) // simple mode skips calculation of normal acceleration @@ -1702,6 +1782,8 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh } dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha + // the criteria of derailment go by the distance, checked in the full step which ends the frame + derailment_distance += std::abs(dL); // ale jesli jest kolizja (zas. zach. pedu) to... for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) @@ -5252,9 +5334,17 @@ void TMoverParameters::ComputeTotalForce(double dt) FStand = FrictionForce(); // siła oporów ruchu if (true == TestFlag(DamageFlag, dtrain_out)) { - // HACK: crude way to reduce speed after derailment - // TBD, TODO: more accurate approach? - FStand *= 1e20; + if (Derailed != derailment::outcome::none) + { + // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side + FStand = derailment::sliding_friction(Derailed) * (TotalMass - Mred) * g; + } + else + { + // HACK: crude way to reduce speed after derailment + // TBD, TODO: more accurate approach? + FStand *= 1e20; + } } double old_nrot = abs(nrot); nrot = v2n(); // przeliczenie prędkości liniowej na obrotową @@ -10967,6 +11057,8 @@ void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) extract_value(Dim.L, "L", line, ""); extract_value(Dim.H, "H", line, ""); extract_value(Dim.W, "W", line, ""); + // height of the centre of gravity of the empty vehicle [m], for the criteria of derailment + extract_value(CentreOfGravity, "CoGH", line, ""); extract_value(Cx, "Cx", line, "0.3"); if (Dim.H <= 2.0) diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp new file mode 100644 index 000000000..54ffc4504 --- /dev/null +++ b/tests/unit/test_derailment_vehicle.cpp @@ -0,0 +1,142 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "McZapkie/derailment.h" +#include "McZapkie/MOVER.h" +#include "utilities/Globals.h" + +// a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of McZapkie/derailment.h checked by +// TMoverParameters::check_derailment(), and what the vehicle comes to off the rails + +using test::definition; +using test::vehicle; +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// the centres of gravity of EU07 (4E) and of the 430W coal wagon of data/fiz, without a CoGH of their own +double const eu07{dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered)}; +double const coal_wagon{dr::default_centre_of_gravity(3.235, dr::vehicle_class::unpowered)}; + +} // namespace + +TEST_CASE("derailment: a vehicle too fast in a curve") { + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + + SUBCASE("below the overturning speed it runs on") { + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical - 5.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + } + SUBCASE("over it, it falls over and slides to a stop on its side") { + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 5.0}; + CHECK(eu07vehicle->centre_of_gravity() == doctest::Approx(eu07)); + // 2 m at 113 km/h is 0.07 s + for (int step = 0; step < 10; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK_FALSE(eu07vehicle->Mains); + // not stopped dead as the legacy model has it: it slows down at half of g on the 80 of its 96 t + auto const start{eu07vehicle->V}; + CHECK(start > 0.95 * (critical + 5.0) * kmh); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + auto const deceleration{(start - eu07vehicle->V) / 1.0}; + CHECK(deceleration == doctest::Approx(0.5 * dr::gravity * 80.0 / 96.0).epsilon(0.05)); + for (int step = 0; step < 2000; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->V == doctest::Approx(0.0)); + } + SUBCASE("a higher centre of gravity of its definition overturns it slower") { + vehicle high{definition::fiz("4e_v1/4e").set("Dimensions", "CoGH", 2.2), critical - 5.0}; + CHECK(high->centre_of_gravity() == doctest::Approx(2.2)); + for (int step = 0; step < 50; ++step) { + high.step(curve); + } + CHECK(high->Derailed == dr::outcome::overturned); + } + SUBCASE("the same with steps of 0.01 and 0.05 s") { + for (auto const dt : {0.01, 0.05}) { + CAPTURE(dt); + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + for (auto time = 0.0; time < 1.0; time += dt) { + eu07vehicle.step(curve, dt); + } + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + vehicle slower{definition::fiz("4e_v1/4e"), critical - 2.0}; + for (auto time = 0.0; time < 1.0; time += dt) { + slower.step(curve, dt); + } + CHECK(slower->Derailed == dr::outcome::none); + } + } + SUBCASE("a load raises the centre of gravity") { + vehicle wagon{definition::fiz("430w_v2/430w")}; + auto const empty{wagon->centre_of_gravity()}; + CHECK(empty == doctest::Approx(coal_wagon)); + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + CHECK(wagon->centre_of_gravity() > empty + 0.5); + } +} + +TEST_CASE("derailment: the model of eu07.ini") { + test::track curve; + curve.radius = 300.0; + SUBCASE("off: no derailment at any speed") { + model_setting const off{global_settings::derailment_model::off}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + } + SUBCASE("old: the legacy draw stops the vehicle dead") { + model_setting const old{global_settings::derailment_model::old}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + eu07vehicle.step(curve); + } + // far over its threshold the draw comes out at once + CHECK(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + CHECK(eu07vehicle->V == doctest::Approx(0.0).epsilon(0.01)); + } +} + +TEST_CASE("derailment: the brake hoses tear") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + eu07vehicle->Couplers[end::rear].CouplingFlag = coupling::coupler | coupling::brakehose; + test::track curve; + curve.radius = 300.0; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->AlarmChainFlag); +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index e38999f7d..100344369 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -170,6 +170,8 @@ TTrackShape shape_of(track const &Track) { TTrackShape shape; shape.Len = 1000.0; shape.dHtrack = Track.gradient; + shape.R = Track.radius; + shape.dHrail = Track.cant; return shape; } diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index e14f4e464..784a4486d 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -66,6 +66,8 @@ struct track { int category{0}; int iterations{1}; double width{1.435}; + double radius{0.0}; // of a curve [m], 0 straight + double cant{0.0}; // [rad] }; // the catenary of the Polish railways [V] diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..746105ad6 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -882,6 +882,20 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.derailment") + { + // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed + std::string model; + ParseOne(Parser, model, 1); + if (model == "old") + derailment = derailment_model::old; + else if (model == "off" || model == "no") + derailment = derailment_model::off; + else + derailment = derailment_model::physical; + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1776,6 +1790,10 @@ global_settings::export_as_text( std::ostream &Output ) const { couplerphysics = "all"; } export_as_text( Output, "couplerphysics", couplerphysics ); + export_as_text( Output, "physics.derailment", std::string{ + derailment == derailment_model::old ? "old" : + derailment == derailment_model::off ? "off" : + "new" } ); 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 8d32a463c..19dabab53 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -290,6 +290,12 @@ struct global_settings { // train with coupler_physics_all bool coupler_physics = false; bool coupler_physics_all = false; + // a vehicle too fast in a curve (physics.derailment in eu07.ini): new, it overturns or its flange climbs the rail + // by the criteria of McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the + // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops + // it; off, it stays on the rails at any speed + enum class derailment_model { off, old, physical }; + derailment_model derailment = derailment_model::physical; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..66b1007df 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3227,6 +3227,9 @@ bool TDynamicObject::Update(double dt, double dt1) // między skrajnymi osiami // (!!!odwrotny) ts.dHrail = (Axle1.GetRoll() + Axle0.GetRoll()) * 0.5; //średnia przechyłka pudła + // the uneven track under the outer axles, for the criteria of derailment: its lateral curvature, and its cross level + ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); + ts.uneven_cross = MyTrack->uneven_underway().cross; // TTrackParam tp; tp.Width = MyTrack->fTrackWidth; // McZapkie-250202 From f1dd033f24952deb47e0cd5e4c107e838e0a0b15 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 11:40:56 +0100 Subject: [PATCH 14/59] feat(physics): the damage flags of a track make the ride rougher, a derailed vehicle once stopped stays put Found running line 107 with every train driven by the AI: - a 401Ka wagon of a freight train overturned into a 282 m curve with a cant of 179 mm at 28 km/h: line 107 has damage 31 on every track, which scaled the whole lateral acceleration by 2.1, the cant too. The sceneries set the flags for the jolts of a worn track (thousands of tracks with 2, 31, 4 or 16), so they now scale only the sway of the body and the short waves of the uneven track, and no longer take load off the wheels; the cross level of the uneven track still does - the overturned wagon crept and stopped in turn in every step (the friction of the ballast against the pull of its train), which kept the physics of the whole train awake: the run went at half the speed after it. The friction now holds a stopped derailed vehicle until the forces on it are larger - a vehicle without a mass got Y/Q 1e9 (no wheel load), now none - the log of a derailment tells the mass, the centre of gravity, the forces of the couplings, the damage flags and the cross level as well --- McZapkie/MOVER.h | 2 +- McZapkie/Mover.cpp | 25 ++++++++--- McZapkie/derailment.cpp | 14 ++++--- McZapkie/derailment.h | 7 ++-- tests/unit/test_derailment.cpp | 57 +++++++++++++++++++++++++- tests/unit/test_derailment_vehicle.cpp | 21 ++++++++++ 6 files changed, 108 insertions(+), 18 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index a1754b7c6..63783419b 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2438,7 +2438,7 @@ class TMoverParameters // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m] void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); // the vehicle leaves the rails, as the criteria of derailment.h found - void derail(derailment::verdict const &Verdict, TTrackShape const &Shape); + void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track); // height of the centre of gravity above the rail with the load [m] double centre_of_gravity() const; // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 0e9cc3993..2fa19e184 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1550,11 +1550,11 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; if (verdict.result != derailment::outcome::none) { - derail(verdict, Shape); + derail(verdict, vehicle, track); } } -void TMoverParameters::derail(derailment::verdict const &Verdict, TTrackShape const &Shape) +void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track) { if (false == SetFlag(DamageFlag, dtrain_out)) { @@ -1568,10 +1568,12 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, TTrackShape co { AlarmChainFlag = true; } - auto const cant{1000.0 * derailment::contact_spacing(TrackW) * std::sin(std::abs(Shape.dHrail))}; - ErrorLog(std::format("Bad driving: {} {} at {:.0f} km/h, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}", Name, - Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Shape.R), cant, Verdict.acceleration, - Verdict.unloading, Verdict.flange_ratio)); + auto const cant{1000.0 * derailment::contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; + ErrorLog(std::format("Bad driving: {} {} at {:.0f} km/h, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" + " (mass {:.1f} t, centre of gravity {:.2f} m, couplings pushing {:.0f} / {:.0f} kN, track damage {}, cross level {:.0f} mm)", + Name, Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Track.radius), cant, + Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, Vehicle.ends[end::front].compression / 1000.0, + Vehicle.ends[end::rear].compression / 1000.0, Track.damage, Track.uneven_cross)); } void TMoverParameters::Derail(DerailReason const Reason) @@ -1652,6 +1654,10 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) AccS = -Sign(V) * g * 1; // random(0.0, 0.1) + // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger + auto const stuck{Derailed != derailment::outcome::none && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + AccS = 0.0; // przyspieszenie normalne if (abs(Shape.R) > 0.01) @@ -1662,6 +1668,8 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // velocity change auto const Vprev{V}; V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + V = 0.0; if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) { // tlumienie predkosci przy hamowaniu @@ -1757,12 +1765,17 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) + auto const stuck{Derailed != derailment::outcome::none && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + AccS = 0.0; // simple mode skips calculation of normal acceleration // velocity change auto const Vprev{V}; V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + V = 0.0; if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) { // tlumienie predkosci przy hamowaniu diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index 382c5c14e..5cccc9f9c 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -128,12 +128,14 @@ double nadal_limit(double const FlangeAngle, double const Friction) { track_condition condition_of(track_state const &Track) { track_condition condition; - // as the legacy criterion had it, a loose rail sways the vehicles 1.4 times as much + // the flags make the ride rougher: the sway of the vehicles and the short waves of the track grow, the curve and + // the cant stay what they are. sceneries set them for the jolts of a worn track (damage 31 on all of line 107), + // not for broken rails. a loose rail sways the vehicles 1.4 times as much, as the legacy criterion had it condition.lateral = 1.0 + 0.4 * has(Track.damage, track_damage::freerail) + 0.5 * has(Track.damage, track_damage::railbend) + 0.1 * has(Track.damage, track_damage::railwear) + 0.1 * has(Track.damage, track_damage::thinrail); // the twist of the track lifts a wheel: 1 % of its load for each mm of cross level, up to the 0.6 the twist test // of EN 14363 lets the load drop by - condition.unloading = std::min(0.6, 0.01 * std::max(0.0, Track.uneven_cross) + 0.1 * has(Track.damage, track_damage::freerail) + 0.1 * has(Track.damage, track_damage::railbend)); + condition.unloading = std::min(0.6, 0.01 * std::max(0.0, Track.uneven_cross)); return condition; } @@ -160,8 +162,8 @@ wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Trac auto const quasistatic{inertia + couplings}; // the sway and the uneven track push the worst way: towards the rail the vehicle already leans on auto const direction{quasistatic >= 0.0 ? 1.0 : -1.0}; - auto const dynamic{Vehicle.mass * dynamic_acceleration(Track, Velocity)}; - result.lateral = direction * (std::abs(quasistatic) + dynamic) * condition.lateral; + auto const dynamic{Vehicle.mass * dynamic_acceleration(Track, Velocity) * condition.lateral}; + result.lateral = direction * (std::abs(quasistatic) + dynamic); // the leading axle meets the rail at an angle in a curve, the creep force of its inner wheel at most the friction auto guiding{0.0}; @@ -172,7 +174,7 @@ wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Trac result.y = std::abs(result.lateral) / axles + guiding; // the lateral forces at their heights move the load onto the wheels they push towards - auto const moment{(direction * (inertia * height + couplings * buffer_height) + dynamic * height) * condition.lateral}; + auto const moment{direction * (inertia * height + couplings * buffer_height) + dynamic * height}; auto const shift{moment / (spacing * axles)}; result.q = std::max(0.0, (staticload + shift) * (1.0 - condition.unloading)); return result; @@ -185,7 +187,7 @@ double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; // the couplings pull at the height of the buffers: as much of a lean as their moment gives auto const moment{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant) * height + coupling_force(Vehicle, Track) * buffer_height}; - return (std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity)) * condition_of(Track).lateral; + return std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity) * condition_of(Track).lateral; } bool stretch::update(bool const Holds, double const Distance, double const Window) { diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 39999d878..7d587517f 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -129,8 +129,8 @@ struct track_state { // what the state of the track does to the lateral forces and the wheel loads struct track_condition { - double lateral{1.0}; // multiplier of the lateral acceleration - double unloading{0.0}; // share of the wheel load the twist of the track takes off + double lateral{1.0}; // multiplier of the sway of the vehicle and of the short waves of an uneven track + double unloading{0.0}; // share of the wheel load the twist of the track (its cross level) takes off }; track_condition condition_of(track_state const &Track); // share of the vehicle that follows the short waves of an uneven track: the wheelsets and the bogies, the body not @@ -144,7 +144,8 @@ struct wheel_forces { double lateral{0.0}; // the lateral force on the vehicle, positive out of the curve [N] double y{0.0}; // lateral force of the flanging wheel [N] double q{0.0}; // its vertical force [N] - double ratio() const { return q > 0.0 ? y / q : 1e9; } + // a wheel lifted off the rail with a force on it is past any limit; no force at all (a vehicle without a mass) none + double ratio() const { return q > 0.0 ? y / q : (y > 0.0 ? 1e9 : 0.0); } }; // the forces of the flanging wheel of the leading axle, at the speed [m/s] wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double Velocity); diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index c66c8f72d..4fa314fcd 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -155,6 +155,19 @@ TEST_CASE("derailment: a peak shorter than the window doesn't derail") { CHECK(stretch.distance() == doctest::Approx(2.0)); } +TEST_CASE("derailment: a vehicle without a mass never derails") { + // a definition without M (or with all of it in the rotating masses) gives no forces, not a lifted wheel + dr::vehicle_state massless; + massless.mass = 0.0; + dr::track_state track; + track.radius = 150.0; + CHECK(dr::flange_forces(massless, track, 30.0).ratio() == 0.0); + dr::monitor monitor; + for (int step = 0; step < 10; ++step) { + CHECK(monitor.update(massless, track, 30.0, 1.0).result == dr::outcome::none); + } +} + TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") { // the empty 3WL (10.5 t, 2 axles 6 m apart, 9.87 m long) between two EU07 in a 150 m curve: the more the train // pushes, the more the couplings push the wagon out of the curve, the higher its Y/Q @@ -209,9 +222,9 @@ TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") return result > flat; }()}; CHECK(twisted); - // on a bent rail, with a twist of 40 mm, the wagon pushed with 300 kN climbs the rail over 2 m, without falling over + // on a bent rail, with a twist of 50 mm, the wagon pushed with 300 kN climbs the rail over 2 m, without falling over track.damage = dr::track_damage::railbend; - track.uneven_cross = 40.0; + track.uneven_cross = 50.0; dr::monitor monitor; auto pushed{wagon}; for (auto &end : pushed.ends) { @@ -225,3 +238,43 @@ TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") CHECK(verdict.unloading < 1.0); CHECK(verdict.result == dr::outcome::off_rails); } + +TEST_CASE("derailment: the damage flags of the track make the ride rougher, not the curve sharper") { + // line 107 has damage 31 on every track, for the jolts. a 401Ka wagon creeping at 28 km/h through a 282 m curve + // with a cant of 179 mm, pulled by a freight train, stays on: in the 2026-11-15 run with the flags scaling the + // whole lateral acceleration it overturned into the curve + dr::vehicle_state wagon; + wagon.mass = 23000.0; + wagon.axles = 4; + wagon.length = 14.7; + wagon.axle_base = 1.8; + wagon.centre_of_gravity = dr::default_centre_of_gravity(4.2, dr::vehicle_class::unpowered); + for (auto &end : wagon.ends) { + end.compression = -200e3; + end.other_length = 14.7; + } + dr::track_state track; + track.radius = 282.0; + track.cant = std::asin(0.179 / 1.5); + auto const speed{28.0 * kmh}; + auto const smooth{dr::body_acceleration(wagon, track, speed)}; + track.damage = 31; + auto const rough{dr::body_acceleration(wagon, track, speed)}; + // the sway grows, by what a rough track adds to the sway at that speed + CHECK(rough > smooth); + CHECK(rough - smooth == doctest::Approx(1.1 * dr::body_vibration(speed))); + CHECK(dr::unloading_ratio(rough, wagon.centre_of_gravity, 1.5) < 0.5); + CHECK(dr::flange_forces(wagon, track, speed).ratio() < 0.8); + // at speed the rough track still lowers the overturning speed some, as the legacy criterion's factor did + { + dr::vehicle_state eu07vehicle; + eu07vehicle.mass = 80000.0; + eu07vehicle.centre_of_gravity = eu07; + dr::track_state good; + good.radius = 300.0; + auto worn{good}; + worn.damage = 31; + CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) > dr::body_acceleration(eu07vehicle, good, 30.0)); + CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) - dr::body_acceleration(eu07vehicle, good, 30.0) == doctest::Approx(1.1 * dr::vibration)); + } +} diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 54ffc4504..23e395fdc 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -140,3 +140,24 @@ TEST_CASE("derailment: the brake hoses tear") { REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); CHECK(eu07vehicle->AlarmChainFlag); } + +TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { + // the friction of the ballast holds it, rather than the vehicle creeping and stopping in turn in every step, which + // kept the physics of its whole train awake (the run of line 107 went at half the speed after a derailment) + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + curve.gradient = 0.01; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 2000; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + REQUIRE(eu07vehicle->V == 0.0); + auto still{true}; + for (int step = 0; step < 500; ++step) { + eu07vehicle.step(curve); + still = still && eu07vehicle->V == 0.0 && eu07vehicle->AccS == 0.0; + } + CHECK(still); +} From 822182d26e8f2f0725ceb6e146b9366fa789eb56 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 11:14:37 +0100 Subject: [PATCH 15/59] feat(track): welded track buckles in the heat, drawn and followed by the axles world/TrackBuckle.h: the buckle of continuous welded rail as plain functions. - the shape: a main lobe and a side lobe of the other way on each side, a cosine under a cos^2 window over three lobes, so the side lobes come to a quarter of the main one and the curvature runs on smoothly into the straight track; peak curvature 11/9 pi^2 a / L^2. A straight track 0.4 m by 14 m, a curve (R < 1500 m) 0.2 m by 11 m out of the curve (Kish, Samavedam) - the heat: rail = air + 17 K in full sun (by the height of the sun and the clouds), the force E*A*alpha*dT, the limits of the rise above the neutral temperature (26 C, PLK) a track buckles at under a train and by itself: good 40/55 K, average 32/45, weak or worked lately 22/32, lowered in curves and by an uneven line; the chance of a pass growing between them - the draws by an FNV-1a hash of the name of the track and the seed The buckle is a part of TSegment::stray() across the path, so the rails, the sleepers and the axles on it follow it (the direction stays as designed); the path is divided every 1 m where it has one. Its curvature is kept apart from the unevenness (TSegment::buckle_bend()). - scenery: "buckle ;;[;]" and "cwr ;[;]" of a plain rail track, written back - event "trackbuckle [ [ []]]" buckles the target tracks during the game (0 straightens them), making their geometry again - physics.trackbuckling off|scenery|auto in eu07.ini, scenery by default; auto also buckles the weak places (one in 10 km of track, and the tracks worked on lately) by the temperature of the rails, by themselves or under a train going fast or braking --- CMakeLists.txt | 1 + editor/editorTrack.cpp | 3 + simulation/simulation.cpp | 2 + tests/unit/test_track_buckle.cpp | 321 ++++++++++++++++++++++ utilities/Globals.cpp | 18 ++ utilities/Globals.h | 4 + world/Event.cpp | 64 +++++ world/Event.h | 26 ++ world/Segment.cpp | 51 +++- world/Segment.h | 17 +- world/Track.cpp | 35 ++- world/Track.h | 29 ++ world/TrackBuckle.cpp | 233 ++++++++++++++++ world/TrackBuckle.h | 440 +++++++++++++++++++++++++++++++ 14 files changed, 1228 insertions(+), 16 deletions(-) create mode 100644 tests/unit/test_track_buckle.cpp create mode 100644 world/TrackBuckle.cpp create mode 100644 world/TrackBuckle.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 76f359eab..98e703cc0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -113,6 +113,7 @@ set(SOURCES "world/RailCarve.cpp" "world/RailLayer.cpp" "world/TrackUneven.cpp" +"world/TrackBuckle.cpp" "world/Road.cpp" "world/Sweep.cpp" "world/RoadPoint.cpp" diff --git a/editor/editorTrack.cpp b/editor/editorTrack.cpp index 548a794d8..f88c91a18 100644 --- a/editor/editorTrack.cpp +++ b/editor/editorTrack.cpp @@ -3400,6 +3400,9 @@ void write_ending(std::ostream &Text, TTrack const &Style, bool const Switch) if ((Style.iCategoryFlag & 15) == 1 && false == Style.m_profile1.first.empty()) Text << "railprofile " << Style.m_profile1.first << ' '; Text << track_uneven::write_attribute(Style.m_uneven, Switch); + // the welded rail goes on in the piece; a buckle stays where it was + if (false == Switch && (Style.iCategoryFlag & 15) == 1) + Text << track_buckle::write_cwr(Style.m_cwr); // a piece of the track made from another one stays in its track circuit and under the same overhead line for (auto const *isolated : Style.Isolated) Text << "isolated " << isolated->asName << ' '; diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 87cce81b6..a25e4ccc7 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -130,6 +130,8 @@ state_manager::update( double const Deltatime, int Iterationcount ) { simulation::Junctions.update( totaltime ); simulation::Roadpoints.update( totaltime ); simulation::Vehicles.update( Deltatime, Iterationcount ); + // the tracks the heat buckles, by itself or under the trains just moved + TTrack::update_buckling( totaltime ); } void diff --git a/tests/unit/test_track_buckle.cpp b/tests/unit/test_track_buckle.cpp new file mode 100644 index 000000000..df26c74ab --- /dev/null +++ b/tests/unit/test_track_buckle.cpp @@ -0,0 +1,321 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackBuckle.h" + +#include + +// the buckling of welded track in the heat, world/TrackBuckle.h: the shape the track takes, the force and the temperature of the rails, +// the limits it buckles at and the draws, repeated with the same seed + +namespace { + +double constexpr pi_squared{9.869604401089358}; + +int count_buckled(double const Rise, track_buckle::limits const &Limits, std::uint32_t const Seed, int const Passes) +{ + auto count{0}; + for (int pass = 1; pass <= Passes; ++pass) + { + auto const draw{track_buckle::draw(track_buckle::name_hash("tor_1234"), Seed, track_buckle::pass, static_cast(pass))}; + if (track_buckle::decide(Rise, Limits, true, draw) == track_buckle::verdict::under_train) + ++count; + } + return count; +} + +} // namespace + +TEST_CASE("the force in a rail held from growing longer is E*A*alpha*dT") +{ + // PLK ST-T1-A8 designs for 35 K, 665 kN in a 60E1 rail, with its own alpha of about 1.18e-5 + auto const force{track_buckle::thermal_force(track_buckle::area_60e1, 35.0)}; + CHECK(force == doctest::Approx(650e3).epsilon(0.03)); + CHECK(force == doctest::Approx(665e3).epsilon(0.03)); + // Kish, Samavedam: about 2.5 kips a rail for each degree F in a 136 lb rail (13.35 sq in), 20.0 kN/K + CHECK(track_buckle::thermal_force(13.35 * 6.4516e-4, 1.0) == doctest::Approx(20.0e3).epsilon(0.05)); + // lighter rails press less + CHECK(track_buckle::thermal_force(track_buckle::area_49e1, 35.0) < force); + CHECK(track_buckle::rail_area("49E1_rail") == track_buckle::area_49e1); + CHECK(track_buckle::rail_area("S42") == track_buckle::area_s42); + CHECK(track_buckle::rail_area("") == track_buckle::area_60e1); +} + +TEST_CASE("a rail is as warm as the air at night or under clouds, 17 K warmer in full sun") +{ + CHECK(track_buckle::rail_temperature(30.0, -10.0, 0.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 0.0) == doctest::Approx(47.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 1.0) == doctest::Approx(30.0)); + // rain cools as much as clouds + CHECK(track_buckle::rail_temperature(30.0, 90.0, 2.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 30.0, 0.0) == doctest::Approx(38.5)); + CHECK(track_buckle::rail_temperature(30.0, 60.0, 0.5) == doctest::Approx(30.0 + 17.0 * std::sin(60.0 * 3.141592653589793 / 180.0) * 0.5)); +} + +TEST_CASE("the limits of the grades meet the heat the tracks of PLK deform in") +{ + track_buckle::cwr track; + auto const average{track_buckle::limits_of(track, 0.0, 0.0)}; + // at the neutral 26 C under a train from rails at 58 C, by itself from 71 C: PLK, deformations with the rails above 70 C + CHECK(track.neutral + average.low == doctest::Approx(58.0)); + CHECK(track.neutral + average.high == doctest::Approx(71.0)); + // Kish, Samavedam: the chance of a buckle of a straight track grows fast from rails at 63 C with the neutral at 27 C, 36 K + CHECK(36.0 > average.low); + CHECK(36.0 < average.high); + // the design of PLK, 35 K, is short of where a good track buckles under a train + track.grade = track_buckle::grade::good; + CHECK(track_buckle::limits_of(track, 0.0, 0.0).low > 35.0); + // worked lately: weak whatever the grade + track.worked = true; + auto const worked{track_buckle::limits_of(track, 0.0, 0.0)}; + CHECK(worked.low == doctest::Approx(22.0)); + CHECK(worked.high == doctest::Approx(32.0)); + // curves and an uneven line lower them + track = {}; + CHECK(track_buckle::limits_of(track, 500.0, 0.0).low == doctest::Approx(29.0)); + CHECK(track_buckle::limits_of(track, -250.0, 0.0).low == doctest::Approx(26.0)); + CHECK(track_buckle::limits_of(track, 2000.0, 0.0).low == doctest::Approx(32.0)); + CHECK(track_buckle::limits_of(track, 0.0, 20.0).high == doctest::Approx(42.0)); + // FRA, the dynamic test: a 7.5 degree curve (233 m) with a 19 mm misalignment buckled under the train at 34 K + auto const fra{track_buckle::limits_of(track, 233.0, 19.0)}; + CHECK(34.0 > fra.low); + CHECK(34.0 < fra.high); +} + +TEST_CASE("below the lower limit a track never buckles, at the upper one it buckles by itself") +{ + track_buckle::limits const limits{32.0, 45.0}; + for (auto const draw : {0.0, 0.3, 0.999}) + { + CHECK(track_buckle::decide(31.9, limits, true, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(31.9, limits, false, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(45.0, limits, false, draw) == track_buckle::verdict::by_itself); + // in between only under a train + CHECK(track_buckle::decide(44.0, limits, false, draw) == track_buckle::verdict::none); + } + CHECK(track_buckle::chance(32.0, limits) == doctest::Approx(0.0)); + CHECK(track_buckle::chance(38.5, limits) == doctest::Approx(0.5)); + CHECK(track_buckle::chance(50.0, limits) == doctest::Approx(1.0)); + // a train going slowly and not braking doesn't stir it up + CHECK_FALSE(track_buckle::stirs(30.0, false)); + CHECK(track_buckle::stirs(30.0, true)); + CHECK(track_buckle::stirs(60.0, false)); + CHECK_FALSE(track_buckle::stirs(3.0, true)); +} + +TEST_CASE("the share of the passes that buckle a track grows with the heat, and repeats with the seed") +{ + track_buckle::limits const limits{32.0, 45.0}; + auto const passes{4000}; + auto const quarter{count_buckled(32.0 + 0.25 * 13.0, limits, 7, passes)}; + auto const most{count_buckled(32.0 + 0.75 * 13.0, limits, 7, passes)}; + CHECK(quarter == doctest::Approx(0.25 * passes).epsilon(0.1)); + CHECK(most == doctest::Approx(0.75 * passes).epsilon(0.05)); + CHECK(count_buckled(31.0, limits, 7, passes) == 0); + // the same seed and track, the same passes + CHECK(count_buckled(38.0, limits, 7, passes) == count_buckled(38.0, limits, 7, passes)); + auto const key{track_buckle::name_hash("tor_1234")}; + CHECK(track_buckle::draw(key, 7, track_buckle::pass, 3) == track_buckle::draw(key, 7, track_buckle::pass, 3)); + // another seed, other draws + auto differ{0}; + for (std::uint64_t pass = 1; pass <= 100; ++pass) + if (track_buckle::draw(key, 7, track_buckle::pass, pass) != track_buckle::draw(key, 8, track_buckle::pass, pass)) + ++differ; + CHECK(differ == 100); + // and another track + CHECK(track_buckle::draw(track_buckle::name_hash("tor_1235"), 7, track_buckle::pass, 3) != track_buckle::draw(key, 7, track_buckle::pass, 3)); + // the draws spread over 0 to 1 + auto low{0}; + for (std::uint64_t pass = 1; pass <= 1000; ++pass) + { + auto const draw{track_buckle::draw(key, 7, track_buckle::pass, pass)}; + CHECK(draw >= 0.0); + CHECK(draw < 1.0); + if (draw < 0.5) + ++low; + } + CHECK(low == doctest::Approx(500).epsilon(0.1)); +} + +TEST_CASE("the heat buckles a track at one place in about 10 km, and wherever the bed was worked on") +{ + auto sites{0}; + auto const tracks{20000}; + for (int track = 0; track < tracks; ++track) + if (track_buckle::weak_spot(track_buckle::name_hash("t" + std::to_string(track)), 3, 500.0, false)) + ++sites; + // 500 m each, 10 000 km together: about 1000 + CHECK(sites == doctest::Approx(1000).epsilon(0.1)); + CHECK(track_buckle::weak_spot(track_buckle::name_hash("t1"), 3, 1.0, true)); +} + +TEST_CASE("the buckle has its amplitude in the middle, side lobes the other way and ends smoothly") +{ + track_buckle::shape const shape{0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(shape, 60.0) == doctest::Approx(0.4)); + CHECK(track_buckle::slope(shape, 60.0) == doctest::Approx(0.0)); + // the main lobe crosses the line one length apart + CHECK(track_buckle::offset(shape, 60.0 - 7.0) == doctest::Approx(0.0)); + CHECK(track_buckle::offset(shape, 60.0 + 7.0) == doctest::Approx(0.0)); + // the side lobes the other way, a quarter as far out + CHECK(track_buckle::offset(shape, 60.0 + 14.0) == doctest::Approx(-0.1)); + CHECK(track_buckle::offset(shape, 60.0 - 14.0) == doctest::Approx(-0.1)); + // into the straight track at the ends with no displacement, slope or curvature + CHECK(track_buckle::reach(shape) == doctest::Approx(21.0)); + for (auto const at : {-21.0 + 1e-6, 21.0 - 1e-6}) + { + CAPTURE(at); + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::slope(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::bend(shape, 60.0 + at) == doctest::Approx(0.0)); + } + // nothing beyond + CHECK(track_buckle::offset(shape, 60.0 + 21.5) == 0.0); + CHECK(track_buckle::bend(shape, 60.0 - 30.0) == 0.0); + // symmetric + for (auto const at : {1.0, 4.0, 7.5, 12.0, 16.0, 20.0}) + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(track_buckle::offset(shape, 60.0 - at))); + // the largest curvature 11/9 pi^2 a / L^2 in the middle, bending back towards the line + auto const peak{track_buckle::peak_bend(0.4, 14.0)}; + CHECK(peak == doctest::Approx(11.0 / 9.0 * pi_squared * 0.4 / (14.0 * 14.0))); + CHECK(track_buckle::bend(shape, 60.0) == doctest::Approx(-peak)); + // none larger anywhere, and the curvature with no jumps + auto previous{track_buckle::bend(shape, 35.0)}; + for (auto at = 35.0; at <= 85.0; at += 0.01) + { + auto const bend{track_buckle::bend(shape, at)}; + CHECK(std::abs(bend) <= peak * 1.0001); + CHECK(std::abs(bend - previous) < 0.01 * peak); + previous = bend; + } + // the curvature as the displacement has it + auto const step{0.01}; + for (auto const at : {42.0, 50.5, 55.0, 61.0, 66.0, 73.0, 79.0}) + { + CAPTURE(at); + auto const slope{(track_buckle::offset(shape, at + step) - track_buckle::offset(shape, at - step)) / (2.0 * step)}; + auto const bend{(track_buckle::offset(shape, at + step) - 2.0 * track_buckle::offset(shape, at) + track_buckle::offset(shape, at - step)) / (step * step)}; + CHECK(track_buckle::slope(shape, at) == doctest::Approx(slope).epsilon(1e-4)); + CHECK(track_buckle::bend(shape, at) == doctest::Approx(bend).epsilon(1e-3)); + } + // to the left + track_buckle::shape const left{-0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(left, 60.0) == doctest::Approx(-0.4)); + CHECK(track_buckle::bend(left, 60.0) == doctest::Approx(peak)); + // none + CHECK(track_buckle::offset(track_buckle::shape{}, 60.0) == 0.0); + CHECK_FALSE(track_buckle::active(track_buckle::shape{})); +} + +TEST_CASE("a bogie feels the curvature of the buckle averaged over its wheelbase, a body that of its pivots") +{ + track_buckle::shape const shape{0.3, 20.0, 50.0}; + auto const peak{track_buckle::peak_bend(0.3, 20.0)}; + CHECK(track_buckle::mean_bend(shape, 50.0, 0.0) == doctest::Approx(track_buckle::bend(shape, 50.0))); + // a bogie 2.5 m long, almost the whole of it + CHECK(std::abs(track_buckle::mean_bend(shape, 50.0, 2.5)) > 0.95 * peak); + // the mean of the curvature over the stretch, anywhere + for (auto const at : {32.0, 42.0, 50.0, 57.5, 64.0}) + { + CAPTURE(at); + auto sum{0.0}; + auto const parts{2500}; + for (int part = 0; part < parts; ++part) + sum += track_buckle::bend(shape, at - 1.25 + (part + 0.5) * 2.5 / parts); + CHECK(track_buckle::mean_bend(shape, at, 2.5) == doctest::Approx(sum / parts).epsilon(1e-3)); + } + // a body on the pivots 0 apart is a bogie + CHECK(track_buckle::body_bend(shape, 47.0, 0.0, 2.5) == doctest::Approx(track_buckle::mean_bend(shape, 47.0, 2.5))); + // a coach with its pivots 17 m apart over the main lobe: its pivots are on the flanks, which bend the other way + auto const across{track_buckle::body_bend(shape, 50.0, 17.0, 2.5)}; + CHECK(std::abs(across) < 0.5 * peak); + // the most the body feels, at any place, is less than a bogie does + auto most{0.0}; + for (auto at = 20.0; at <= 80.0; at += 0.05) + most = std::max(most, std::abs(track_buckle::body_bend(shape, at, 17.0, 2.5))); + CHECK(most < 0.95 * peak); + CHECK(most > 0.3 * peak); +} + +TEST_CASE("the equivalent radius of a buckle") +{ + // the default ones as sharp as the raised cosine lobes of the research note: 0.4 m by 18 m on a straight 41 m, 0.2 by 14 in a curve 50 m + CHECK(1.0 / track_buckle::peak_bend(track_buckle::straight_amplitude, track_buckle::straight_length) == doctest::Approx(41.0).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(track_buckle::curve_amplitude, track_buckle::curve_length) == doctest::Approx(49.6).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(0.3, 20.0) == doctest::Approx(110.5).epsilon(0.01)); +} + +TEST_CASE("the entries buckle and cwr are read and written back") +{ + auto const buckle{track_buckle::read_buckle("400;18;60")}; + CHECK(buckle.amplitude == 400.f); + CHECK(buckle.length == 18.f); + CHECK(buckle.centre == 60.f); + CHECK(buckle.side == 0); + CHECK(track_buckle::write_buckle(buckle) == "buckle 400;18;60 "); + auto const left{track_buckle::read_buckle("250;;;-1")}; + CHECK(left.amplitude == 250.f); + CHECK(left.length < 0.f); + CHECK(left.centre < 0.f); + CHECK(left.side == -1); + CHECK(track_buckle::write_buckle(left) == "buckle 250;;;-1 "); + CHECK(track_buckle::read_buckle(track_buckle::write_buckle(left).substr(7)).side == -1); + // kept within bounds + auto const wild{track_buckle::read_buckle("5000;100;-5;3")}; + CHECK(wild.amplitude == 1000.f); + CHECK(wild.length == 60.f); + CHECK(wild.centre < 0.f); + CHECK(wild.side == 1); + CHECK(track_buckle::read_buckle("300;1").length == 4.f); + // none + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("0;18;60"))); + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("x"))); + CHECK(track_buckle::write_buckle(track_buckle::declared{}).empty()); + + auto const cwr{track_buckle::read_cwr("20;2;1")}; + CHECK(cwr.neutral == 20.f); + CHECK(cwr.grade == track_buckle::grade::weak); + CHECK(cwr.worked); + CHECK(track_buckle::write_cwr(cwr) == "cwr 20;2;1 "); + auto const partial{track_buckle::read_cwr("22")}; + CHECK(partial.neutral == 22.f); + CHECK(partial.grade == track_buckle::grade::average); + CHECK_FALSE(partial.worked); + CHECK(track_buckle::write_cwr(partial) == "cwr 22;1 "); + auto const bounded{track_buckle::read_cwr("99;7")}; + CHECK(bounded.neutral == 60.f); + CHECK(bounded.grade == 2); + // the default isn't written + CHECK(track_buckle::write_cwr(track_buckle::read_cwr("26;1;0")).empty()); +} + +TEST_CASE("a buckle is laid into its track away from the ends, out of a curve") +{ + auto const values{track_buckle::read_buckle("400;18;60")}; + auto const straight{track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.2)}; + CHECK(straight.centre == 60.0); + CHECK(straight.length == 18.0); + // the side drawn on a straight + CHECK(straight.amplitude == doctest::Approx(-0.4)); + CHECK(track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.7).amplitude == doctest::Approx(0.4)); + // out of a curve, whatever the draw + CHECK(track_buckle::resolve(values, 200.0, 1, 400.0, 0.5, 0.2).amplitude == doctest::Approx(0.4)); + CHECK(track_buckle::resolve(values, 200.0, -1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the side given wins + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;60;-1"), 200.0, 1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the centre kept away from the ends by the reach, 1.5 lengths, and a margin + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;5"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;195"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(171.0)); + // drawn where not given + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 0.0, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 1.0, 0.2).centre == doctest::Approx(171.0)); + // the length by the shape of the track: a curve goes out less far and shorter + CHECK(track_buckle::resolve(track_buckle::read_buckle("200"), 200.0, 1, 400.0, 0.5, 0.2).length == track_buckle::curve_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 0, 0.0, 0.5, 0.2).length == track_buckle::straight_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 1, 3000.0, 0.5, 0.2).length == track_buckle::straight_length); + // too short a track + CHECK_FALSE(track_buckle::active(track_buckle::resolve(values, 57.9, 0, 0.0, 0.5, 0.2))); + CHECK(track_buckle::active(track_buckle::resolve(values, 58.0, 0, 0.0, 0.5, 0.2))); + // the natural ones + CHECK(track_buckle::natural(true).amplitude == 200.f); + CHECK(track_buckle::natural(false).length == 14.f); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 746105ad6..37dd30eed 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -872,6 +872,20 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.trackbuckling") + { + // off, scenery: the buckles of the scenery and its events, auto: also by the temperature of the rails + std::string mode; + ParseOne(Parser, mode, 1); + if (mode == "off" || mode == "no") + track_buckling = track_buckling_mode::off; + else if (mode == "auto") + track_buckling = track_buckling_mode::automatic; + else + track_buckling = track_buckling_mode::scenery; + return true; + } + if (token == "couplerphysics") { // yes: the player's train and the trains it closes in on, all: every train @@ -1783,6 +1797,10 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "scenario.time.offset", ScenarioTimeOffset ); export_as_text( Output, "scenario.time.current", ScenarioTimeCurrent ); export_as_text( Output, "scenario.weather.temperature", AirTemperature ); + export_as_text( Output, "physics.trackbuckling", std::string{ + track_buckling == track_buckling_mode::off ? "off" : + track_buckling == track_buckling_mode::automatic ? "auto" : + "scenery" } ); export_as_text( Output, "ai.trainman", AITrainman ); export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check ); std::string couplerphysics { coupler_physics ? "yes" : "no" }; diff --git a/utilities/Globals.h b/utilities/Globals.h index 19dabab53..e82beddd4 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -284,6 +284,10 @@ struct global_settings { bool captureonstart = true; bool render_cab = true; bool crash_damage = true; + // the buckling of welded track in the heat (physics.trackbuckling in eu07.ini, see world/TrackBuckle.h): off, none; scenery, the + // buckles the scenery enters and its trackbuckle events; automatic, also by the temperature of the rails at the weak places + enum class track_buckling_mode { off, scenery, automatic }; + track_buckling_mode track_buckling = track_buckling_mode::scenery; // the physical model of the couplings (McZapkie/couplerphysics.h): progressive buffers and draw gear with hysteresis, // the play of the coupling, its yield and breaking; the legacy model of TMoverParameters::CouplerForce() without it. // it covers the player's train and the trains it closes in on (vehicle_table::update_coupler_physics()), or every diff --git a/world/Event.cpp b/world/Event.cpp index 80697cfa2..2452b7881 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -2054,6 +2054,69 @@ track_event::export_as_text_( std::ostream &Output ) const { +// prepares event for use +void +buckle_event::init() { + + init_targets( simulation::Paths, "track" ); +} + +// event type string +std::string +buckle_event::type() const { + + return "trackbuckle"; +} + +// deserialize() subclass details +void +buckle_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) { + + Input.getTokens(); + Input >> m_buckle.amplitude; + m_buckle.amplitude = std::clamp( m_buckle.amplitude, 0.f, static_cast( 1000.0 * track_buckle::most_amplitude ) ); + Input.getTokens(); + // the length, the centre and the side, each optional + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.length; + if( m_buckle.length > 0.f ) { + m_buckle.length = std::clamp( m_buckle.length, static_cast( track_buckle::least_length ), static_cast( track_buckle::most_length ) ); + } + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.centre; + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + auto side { 0.f }; + Input >> side; + m_buckle.side = ( side > 0.f ? 1 : side < 0.f ? -1 : 0 ); + Input.getTokens(); + } +} + +// run() subclass details +void +buckle_event::run_() { + + WriteLog( "Type: TrackBuckle - [" + to_string( m_buckle.amplitude, 0 ) + " mm]" ); + for( auto &target : m_targets ) { + auto *targettrack = static_cast( std::get( target ) ); + if( targettrack == nullptr ) { continue; } + targettrack->buckle_now( m_buckle, "event " + m_name ); + } +} + +// export_as_text() subclass details +void +buckle_event::export_as_text_( std::ostream &Output ) const { + + Output << m_buckle.amplitude << ' ' << m_buckle.length << ' ' << m_buckle.centre << ' ' << m_buckle.side << ' '; +} + + + // prepares event for use void voltage_event::init() { @@ -2310,6 +2373,7 @@ make_event( cParser &Input, scene::scratch_data &Scratchpad ) { else if( type == "multiple" ) { event = new multi_event(); } else if( type == "switch" ) { event = new switch_event(); } else if( type == "trackvel" ) { event = new track_event(); } + else if( type == "trackbuckle" ) { event = new buckle_event(); } else if( type == "sound" ) { event = new sound_event(); } else if( type == "texture" ) { event = new texture_event(); } else if( type == "animation" ) { event = new animation_event(); } diff --git a/world/Event.h b/world/Event.h index f1d75689b..090d165d6 100644 --- a/world/Event.h +++ b/world/Event.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/scene.h" #include "utilities/Names.h" #include "world/EvLaunch.h" +#include "world/TrackBuckle.h" #include "utilities/Logs.h" #include "input/command.h" #include "utilities/comparison.h" @@ -527,6 +528,31 @@ private: +// trackbuckle [ [ []]]: the target tracks buckle in the heat as the entry +// "buckle" of a track says (see world/TrackBuckle.h), amplitude 0 straightens them +class buckle_event : public basic_event { + +public: +// methods + // prepares event for use + void init() override; + +private: +// methods + // event type string + std::string type() const override; + // deserialize() subclass details + void deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) override; + // run() subclass details + void run_() override; + // export_as_text() subclass details + void export_as_text_( std::ostream &Output ) const override; +// members + track_buckle::declared m_buckle; +}; + + + class voltage_event : public basic_event { public: diff --git a/world/Segment.cpp b/world/Segment.cpp index d1c5f2c89..5e0f47116 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -141,6 +141,10 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N // dense enough for the waves; a switch keeps its division, the blades depend on it fStep = std::min( fStep, 2.0 ); } + if( m_setting.buckled ) { + // and for the lobes of a buckle, 9 m and more + fStep = std::min( fStep, 1.0 ); + } // NOTE: optionally replace this part with the commented version, after solving geometry issues with double switches if( pOwner->eType == tt_Switch && fStep * (3.0 * Global.SplineFidelity) > fLength ) { @@ -431,14 +435,33 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const }; */ -glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const { - auto const field { track_uneven::field( Point ) }; - glm::dvec3 result { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side }; - result *= track_uneven::stray_per_mm; - result.y -= pOwner->joint_dip( Distance ); +glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const { + glm::dvec3 result { 0.0 }; + if( m_setting.uneven ) { + auto const field { track_uneven::field( Point ) }; + result = glm::dvec3 { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side } * track_uneven::stray_per_mm; + result.y -= pOwner->joint_dip( Distance ); + } + if( m_setting.buckled && m_pieces.empty() ) { + result += Across * track_buckle::offset( pOwner->buckle(), Distance ); + } return result; } +double TSegment::buckle_bend( double const Distance, double const Base ) const { + if( false == m_setting.buckled || false == m_pieces.empty() ) { + return 0.0; + } + return track_buckle::mean_bend( pOwner->buckle(), Distance, Base ); +} + +glm::dvec3 TSegment::across_at( double const Distance ) const { + glm::dvec3 point; + glm::dvec3 across; + plan_frame( Distance, point, across ); + return across; +} + glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( false == m_setting.uneven ) { return glm::dvec3 { 0.0 }; @@ -453,12 +476,13 @@ glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( auto const direction { FastGetDirection( t, 0.1 / fLength ) }; on != At && glm::length( direction ) > 0.0 ) { point += direction * ( ( At - on ) / glm::length( direction ) ); } - return stray( point, pOwner->uneven_at( At, m_setting.path ), At ); }; + // the buckle left out: its curvature is taken on its own, see buckle_bend() + return stray( point, pOwner->uneven_at( At, m_setting.path ), At, glm::dvec3 { 0.0 } ); }; return ( strayed( Distance + reach ) - 2.0 * strayed( Distance ) + strayed( Distance - reach ) ) / ( reach * reach ); } void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const { - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } // the rails settling apart turn about the middle of the track, what's outside them follows the rail; the foot of the ballast stays @@ -468,9 +492,9 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi if( share <= 0.0 ) { return; } - auto const amount { pOwner->uneven_at( Distance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( Distance, m_setting.path ) : track_uneven::amounts {} }; Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); - Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) }; + Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance, glm::dvec3 { Parallel } ) }; } void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm::vec3 &rotation) const { @@ -500,17 +524,18 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: rotation.y = static_cast(fStoop); // pochylenie toru prostego rotation.z = static_cast(fDirection); // kierunek toru w planie } - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } - // direction and slope stay as designed: the physics takes the curve radius and the grade from them + // direction and slope stay as designed: the physics takes the curve radius and the grade from them, and the curvature of a buckle + // on its own (buckle_bend()) auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; - auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( fDistance, m_setting.path ) : track_uneven::amounts {} }; rotation.x += static_cast( track_uneven::stray_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); - position += track_uneven::across_only( stray( position, amount, fDistance ), across ); + position += track_uneven::across_only( stray( position, amount, fDistance, across ), across ); }; void TSegment::plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const { diff --git a/world/Segment.h b/world/Segment.h index 3255de362..58d5785f3 100644 --- a/world/Segment.h +++ b/world/Segment.h @@ -96,6 +96,7 @@ class TSegment struct setting { std::array designrolls { 0.f, 0.f }; // as entered; fRoll1 and fRoll2 can differ at a joint bool uneven { false }; // see TrackUneven.h + bool buckled { false }; // see TrackBuckle.h int path { 0 }; // which path of a switch // where the path meets the next one: the middle of their ends and their common vector across std::array>, 2> joints; @@ -132,8 +133,9 @@ class TSegment // moves a lofted vertex with the unevenness of the track void settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const; - // displacement of a point by the unevenness, at a distance along the path - glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const; + // displacement of a point by the unevenness, at a distance along the path, and by the buckle of the track across it, along Across + // (none along a zero vector) + glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const; public: bool bCurve = false; @@ -188,6 +190,10 @@ public: set_uneven( bool const Uneven, int const Path = 0 ) { m_setting.uneven = Uneven; m_setting.path = Path; } + // call before Init too + void + set_buckled( bool const Buckled ) { + m_setting.buckled = Buckled; } // a point of the path and the unit vector across it in the plan, towards the right rail profile; zero for a path never made void plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const; @@ -201,6 +207,13 @@ public: // second derivative of the displacement along the path; times speed squared: acceleration of an axle glm::dvec3 uneven_bend( double const Distance ) const; + // the curvature the buckle of the track adds to the path at the distance, 1/m, positive bending towards its right; averaged over Base + // around it, as a bogie or a body takes it + double + buckle_bend( double const Distance, double const Base = 0.0 ) const; + // the unit vector across the path at the distance, towards its right + glm::dvec3 + across_at( double const Distance ) const; glm::dvec3 FastGetPoint(double const t) const; inline glm::dvec3 diff --git a/world/Track.cpp b/world/Track.cpp index 947a5836c..27bf7c9dc 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -756,6 +756,20 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) m_uneven = track_uneven::read_attribute( values, eType == tt_Switch ); } } + else if( str == "buckle" ) { + // buckle ;;[;]: the track buckled by the heat, see TrackBuckle.h + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_buckledeclared = track_buckle::read_buckle( values ); + } + } + else if( str == "cwr" ) { + // cwr ;[;]: the welded rail, for the buckling by the temperature + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_cwr = track_buckle::read_cwr( values ); + } + } else if( str == "friction" ) { // memory cell holding friction value modifiers m_friction.first = parser->getToken(); @@ -818,8 +832,15 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) // from the scenery is put back after it auto const velocity { fVelocity }; init_segments( true ); + // the buckle goes along the path made + if( Global.track_buckling != global_settings::track_buckling_mode::off && track_buckle::given( m_buckledeclared ) ) { + m_buckle = resolve_buckle( m_buckledeclared, 0 ); + if( false == is_buckled() ) { + ErrorLog( "Bad track: \"" + m_name + "\" too short for its buckle" ); + } + } // made with no unevenness, which is read with the attributes and goes onto them by making them again - if( is_uneven() ) { + if( is_uneven() || is_buckled() ) { init_segments( false ); } if( SwitchExtension ) { @@ -875,6 +896,7 @@ void TTrack::init_segments( bool const Initial ) { } else if( Segment ) { Segment->set_uneven( is_uneven() ); + Segment->set_buckled( is_buckled() ); } switch (eType) { @@ -1266,6 +1288,10 @@ bool TTrack::AddDynamicObject(TDynamicObject *Dynamic) } } } + if( Dynamics.empty() ) { + // a train comes onto the track, which can buckle under it in the heat + buckle_pass_enter( *Dynamic ); + } Dynamics.emplace_back( Dynamic ); Dynamic->MyTrack = this; // ABu: na ktorym torze jesteśmy if( Dynamic->iOverheadMask ) { @@ -1313,6 +1339,10 @@ bool TTrack::RemoveDynamicObject(TDynamicObject *Dynamic) } } } + if( result ) { + // the head of a train leaving the track the pass was drawn to buckle + buckle_pass_leave(); + } if( Global.iMultiplayer ) { // jeśli multiplayer if( true == Dynamics.empty() ) { @@ -2868,6 +2898,9 @@ TTrack::export_as_text_( std::ostream &Output ) const { Output << "railprofile " << m_profile1.first << ' '; } Output << track_uneven::write_attribute( m_uneven, eType == tt_Switch ); + if( eType == tt_Normal && iCategoryFlag == 1 ) { + Output << track_buckle::write_buckle( m_buckledeclared ) << track_buckle::write_cwr( m_cwr ); + } if( false == m_friction.first.empty() ) { Output << "friction " << m_friction.first << ' '; } diff --git a/world/Track.h b/world/Track.h index 033bee610..3fefde977 100644 --- a/world/Track.h +++ b/world/Track.h @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Segment.h" #include "world/RailLayout.h" #include "world/TrackSleepers.h" +#include "world/TrackBuckle.h" #include "world/TrackUneven.h" #include "model/material.h" #include "scene/scenenode.h" @@ -278,6 +279,8 @@ public: int iAction = 0; // czy modyfikowany eventami (specjalna obsługa przy skanowaniu) float fOverhead = -1.0; // można normalnie pobierać prąd (0 dla jazdy bezprądowej po danym odcinku, >0-z opuszczonym i ograniczeniem prędkości) track_uneven::attribute m_uneven; // plain tracks and switches + track_buckle::declared m_buckledeclared; // the buckle entered in the scenery; plain rail tracks + track_buckle::cwr m_cwr; // the welded rail, for the buckling by the temperature private: double fVelocity = -1.0; // ograniczenie prędkości // prędkość dla AI (powyżej rośnie prawdopowobieństwo wykolejenia) public: @@ -412,6 +415,17 @@ public: track_uneven::amounts uneven_at( double const Distance, int const Path = 0 ); // how much of the displacement a point of the profile at the depth takes double uneven_bed_share( double const Depth ) const; + // the buckle the track has now (see TrackBuckle.h): none with physics.trackbuckling off + track_buckle::shape const &buckle() const { + return m_buckle; } + bool is_buckled() const { + return track_buckle::active( m_buckle ); } + // buckles the track during the game as the values say, or with none straightens it, and makes its geometry again. Cause goes to the log + bool buckle_now( track_buckle::declared const &Values, std::string const &Cause ); + // the buckling of the tracks by the temperature of the rails, physics.trackbuckling auto; once a minute + static void update_buckling( double const Deltatime ); + // the radius of the path in the plan at the distance, 0 straight, and the side away from its centre: -1 left, 1 right, 0 straight + double plan_radius( double const Distance, int &Outward ) const; // closes the gaps and steps of cant between the ends of joined paths void share_joints(); double joint_depth() const; // mm @@ -473,6 +487,21 @@ private: int stamp { -1 }; }; switch_stray m_switchstray; + track_buckle::shape m_buckle; + // the buckling by the temperature: the passes of the trains over the track, and the pass which will buckle it as its head leaves + std::uint32_t m_buckle_passes { 0 }; + bool m_buckle_armed { false }; + // the buckle of the values on this track, its place and side drawn with the seed where not given + track_buckle::shape resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const; + // the draws for this track: by its name, by where it is for one with none + std::uint64_t buckle_key() const; + // whether the temperature can buckle the track, and the rise of the rails above its neutral temperature it does it at + bool buckles_by_heat() const; + track_buckle::limits buckle_limits() const; + // a train coming onto the track and its head leaving it, for the buckling under a train + void buckle_pass_enter( TDynamicObject const &Dynamic ); + void buckle_pass_leave(); + void buckle_under_train(); switch_stray const &switch_uneven(); void settle_switch_stray(); void settle_switch_ends(); diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp new file mode 100644 index 000000000..b49dd5753 --- /dev/null +++ b/world/TrackBuckle.cpp @@ -0,0 +1,233 @@ +/* +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 "world/Track.h" +#include "simulation/simulation.h" +#include "simulation/simulationenvironment.h" +#include "scene/scene.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "vehicle/DynObj.h" + +#include + +namespace { + +// how often the temperature is checked, s of the simulation +double constexpr check_interval { 60.0 }; +// the tracks the temperature can buckle, found at the first check +std::vector heat_sites; +bool heat_sites_found { false }; +double heat_clock { 0.0 }; +// the tracks to buckle under a train, done with the next update rather than amid the moves of the vehicles +std::vector heat_due; + +double rail_temperature_now() { + + return track_buckle::rail_temperature( Global.AirTemperature, simulation::Environment.sun().getAngle(), Global.Overcast ); +} + +} // namespace + +double TTrack::plan_radius( double const Distance, int &Outward ) const { + + Outward = 0; + if( Segment == nullptr || eType != tt_Normal ) { + return 0.0; + } + auto const length { Segment->GetLength() }; + auto const reach { std::min( 5.0, 0.25 * length ) }; + auto const at { std::clamp( Distance, reach, length - reach ) }; + glm::dvec3 behind, middle, ahead, across; + Segment->plan_frame( at - reach, behind, across ); + Segment->plan_frame( at + reach, ahead, across ); + Segment->plan_frame( at, middle, across ); + auto bend { ( behind + ahead - 2.0 * middle ) / ( reach * reach ) }; + bend.y = 0.0; + auto const curvature { glm::length( bend ) }; + // straighter than the curves the tracks are laid with + if( curvature < 1.0 / 20000.0 ) { + return 0.0; + } + // away from the centre, which the bend points to + Outward = ( glm::dot( bend, across ) > 0.0 ? -1 : 1 ); + return 1.0 / curvature; +} + +std::uint64_t TTrack::buckle_key() const { + + if( false == m_name.empty() && m_name != "none" ) { + return track_buckle::name_hash( m_name ); + } + auto const point { location() }; + return track_buckle::name_hash( std::format( "{:.1f};{:.1f};{:.1f}", point.x, point.y, point.z ) ); +} + +track_buckle::shape TTrack::resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const { + + if( Segment == nullptr || eType != tt_Normal || iCategoryFlag != 1 ) { + return {}; + } + auto const length { Segment->GetLength() }; + auto const key { buckle_key() }; + auto const place { track_buckle::draw( key, Seed, track_buckle::place ) }; + // the side out of the curve where the buckle is + auto const centre { Values.centre >= 0.f ? static_cast( Values.centre ) : 0.5 * length }; + auto outward { 0 }; + auto const radius { plan_radius( centre, outward ) }; + return track_buckle::resolve( Values, length, outward, radius, place, track_buckle::draw( key, Seed, track_buckle::way ) ); +} + +bool TTrack::buckle_now( track_buckle::declared const &Values, std::string const &Cause ) { + + if( Global.track_buckling == global_settings::track_buckling_mode::off ) { + return false; + } + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr ) { + ErrorLog( "Bad track: \"" + m_name + "\" can't buckle, it isn't a plain rail track" ); + return false; + } + auto const shape { resolve_buckle( Values, 0 ) }; + if( track_buckle::given( Values ) && false == track_buckle::active( shape ) ) { + ErrorLog( std::format( "Bad track: \"{}\" too short for a buckle {:.0f} m long", m_name, 2.0 * track_buckle::reach_share * ( Values.length > 0.f ? Values.length : track_buckle::straight_length ) ) ); + return false; + } + m_buckle = shape; + m_buckle_armed = false; + // made again with the buckle, which the rails, the sleepers and the axles on the track follow + init_segments( false ); + auto const rebuild = []( TTrack &Track ) { + auto §ion { simulation::Region->section( Track.location() ) }; + Track.rebuild_geometry( section.m_geometrycreated ? section.m_geometrybank : gfx::geometrybank_handle {} ); }; + rebuild( *this ); + for( auto *crossing : m_crossings ) { + if( crossing != nullptr && crossing != this ) { + rebuild( *crossing ); + } + } + if( is_buckled() ) { + WriteLog( std::format( + "Track \"{}\" buckled ({}): {:.0f} mm to the {} at {:.1f} m, main lobe {:.1f} m, curvature up to 1/{:.0f} m", + m_name, Cause, std::abs( 1000.0 * m_buckle.amplitude ), m_buckle.amplitude > 0.0 ? "right" : "left", m_buckle.centre, m_buckle.length, + 1.0 / track_buckle::peak_bend( m_buckle.amplitude, m_buckle.length ) ) ); + } + else { + WriteLog( "Track \"" + m_name + "\" straightened (" + Cause + ")" ); + } + return true; +} + +bool TTrack::buckles_by_heat() const { + + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr || is_buckled() || false == m_crossings.empty() ) { + return false; + } + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + // continuous welded rail is laid down to a radius of 190 m (PLK ST-T1-A8) + if( radius > 0.0 && radius < 190.0 ) { + return false; + } + auto const natural { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + if( Segment->GetLength() < 2.0 * ( track_buckle::reach_share * natural.length + track_buckle::end_margin ) ) { + return false; + } + return track_buckle::weak_spot( buckle_key(), Global.random_seed, Segment->GetLength(), m_cwr.worked ); +} + +track_buckle::limits TTrack::buckle_limits() const { + + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + return track_buckle::limits_of( m_cwr, radius, uneven_declared().side ); +} + +void TTrack::update_buckling( double const Deltatime ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic ) { + return; + } + if( false == heat_sites_found ) { + heat_sites_found = true; + for( auto *track : simulation::Paths.sequence() ) { + if( track != nullptr && track->buckles_by_heat() ) { + heat_sites.push_back( track ); + } + } + WriteLog( std::format( "Track buckling: {} places the heat can buckle", heat_sites.size() ) ); + // the first check right away, a scenario can start in the heat + heat_clock = check_interval; + } + for( auto *track : heat_due ) { + track->buckle_under_train(); + } + heat_due.clear(); + heat_clock += Deltatime; + if( heat_clock < check_interval ) { + return; + } + heat_clock = 0.0; + auto const rail { rail_temperature_now() }; + for( auto *track : heat_sites ) { + if( track->is_buckled() ) { + continue; + } + auto const rise { rail - track->m_cwr.neutral }; + if( track_buckle::decide( rise, track->buckle_limits(), false, 1.0 ) == track_buckle::verdict::by_itself ) { + auto outward { 0 }; + auto const radius { track->plan_radius( 0.5 * track->Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, track->Segment->GetLength(), outward, radius, + track_buckle::draw( track->buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + track->buckle_now( values, std::format( "rails at {:.0f} C, {:.0f} K above neutral, {:.0f} kN in each", rail, rise, + 0.001 * track_buckle::thermal_force( track_buckle::rail_area( track->m_profile1.first ), rise ) ) ); + } + } +} + +void TTrack::buckle_pass_enter( TDynamicObject const &Dynamic ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic || is_buckled() || false == heat_sites_found ) { + return; + } + if( std::ranges::find( heat_sites, this ) == heat_sites.end() ) { + return; + } + ++m_buckle_passes; + auto const *mover { Dynamic.MoverParameters }; + auto const train { mover != nullptr && track_buckle::stirs( std::abs( mover->Vel ), mover->BrakePress > 0.5 ) }; + auto const rise { rail_temperature_now() - m_cwr.neutral }; + auto const draw { track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::pass, m_buckle_passes ) }; + m_buckle_armed = ( track_buckle::decide( rise, buckle_limits(), train, draw ) != track_buckle::verdict::none ); +} + +void TTrack::buckle_pass_leave() { + + if( false == m_buckle_armed ) { + return; + } + m_buckle_armed = false; + heat_due.push_back( this ); +} + +void TTrack::buckle_under_train() { + + if( is_buckled() ) { + return; + } + // under the rest of the train, which lifts the track between its bogies + auto const rail { rail_temperature_now() }; + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, Segment->GetLength(), outward, radius, + track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + buckle_now( values, std::format( "under a train, rails at {:.0f} C, {:.0f} K above neutral", rail, rail - m_cwr.neutral ) ); +} diff --git a/world/TrackBuckle.h b/world/TrackBuckle.h new file mode 100644 index 000000000..25825ed99 --- /dev/null +++ b/world/TrackBuckle.h @@ -0,0 +1,440 @@ +/* +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 +#include +#include +#include +#include + +// Lateral buckling of continuous welded rail: in the heat the rails, held from growing longer, press on the track along it with +// E*A*alpha*dT, and where the bed holds it too weakly sideways the track jumps out to the side. The track of the scenery takes it as +// a displacement across it (TSegment::stray()), drawn and followed by the axles as the unevenness of TrackUneven.h is. +// Sources: Kish, Samavedam, "Risk analysis based CWR track buckling safety evaluations" (Volpe, about 2001); FRA, "Dynamic buckling +// test analyses of a high degree CWR track"; PKP PLK ST-T1-A8 (2021); the answers of the ministry to interpellations 3875 (2026) and +// 2575 (2025). The thresholds and the shape are fitted to the numbers there, see test_track_buckle.cpp. +namespace track_buckle { + +// the shape: a main lobe and a side lobe of the other way on each side of it, as the buckled shapes of Kerr and Kish have it. A +// cosine of a period twice the main lobe under a window cos^2 over three lobes: the side lobes come to a quarter of the main one, and +// the curvature runs on smoothly all along, into the straight track at the ends too, as a bent rail has it +// straight track jumps out far at once, a curve goes out step by step and less far, to the outside of the curve (Kish, Samavedam) +inline constexpr double straight_amplitude { 0.4 }; // m +inline constexpr double straight_length { 14.0 }; // m, main lobe +inline constexpr double curve_amplitude { 0.2 }; // m +inline constexpr double curve_length { 11.0 }; // m +inline constexpr double curve_radius { 1500.0 }; // m, below which a track counts as a curve for the shape +inline constexpr double end_margin { 2.0 }; // m between the buckle and the ends of the track +inline constexpr double most_amplitude { 1.0 }; // m +inline constexpr double least_length { 4.0 }; // m +inline constexpr double most_length { 60.0 }; // m +// how far the side lobes reach from the centre, in lengths of the main lobe +inline constexpr double reach_share { 1.5 }; + +struct shape { + double amplitude { 0.0 }; // of the main lobe, m: positive to the right of the path looking from its start to its end, negative to the left + double length { 0.0 }; // of the main lobe between the points it crosses the line, m; each side lobe is as long + double centre { 0.0 }; // of the main lobe, distance from the start of the path, m +}; + +inline bool active( shape const &Shape ) { + + return Shape.amplitude != 0.0 && Shape.length > 0.0; +} + +// the wave and the window at a distance from the centre, with their derivatives +struct parts { + double wave, wave1, wave2; + double window, window1, window2; +}; + +inline parts parts_at( shape const &Shape, double const Distance ) { + + auto const from { Distance - Shape.centre }; + auto const k { glm::pi() / Shape.length }; + // cos^2(b x) = ( 1 + cos( 2 b x ) ) / 2 reaching 0 at the ends of the side lobes + auto const b { glm::pi() / ( 2.0 * reach_share * Shape.length ) }; + return { + std::cos( k * from ), -k * std::sin( k * from ), -k * k * std::cos( k * from ), + 0.5 * ( 1.0 + std::cos( 2.0 * b * from ) ), -b * std::sin( 2.0 * b * from ), -2.0 * b * b * std::cos( 2.0 * b * from ) }; +} + +inline bool within( shape const &Shape, double const Distance ) { + + return active( Shape ) && std::abs( Distance - Shape.centre ) < reach_share * Shape.length; +} + +// displacement across the path at a distance along it, m +inline double offset( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * p.wave * p.window; +} + +// its first derivative along the path +inline double slope( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave1 * p.window + p.wave * p.window1 ); +} + +// and the second: the curvature the buckle adds to the path, 1/m, positive bending to the right +inline double bend( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave2 * p.window + 2.0 * p.wave1 * p.window1 + p.wave * p.window2 ); +} + +// the mean curvature over a stretch around a distance, as a bogie over its wheelbase feels it: the difference of the slopes at its ends +// over its length +inline double mean_bend( shape const &Shape, double const Distance, double const Base ) { + + if( Base <= 0.0 ) { + return bend( Shape, Distance ); + } + return ( slope( Shape, Distance + 0.5 * Base ) - slope( Shape, Distance - 0.5 * Base ) ) / Base; +} + +// and as a body on two bogies: it goes sideways by the mean of its pivots, so its lateral acceleration is v^2 times the mean of the +// curvatures at the pivots, each over the wheelbase of the bogie (without bogies: the pivots are the axles, with no base) +inline double body_bend( shape const &Shape, double const Distance, double const Pivots, double const Base ) { + + return 0.5 * ( mean_bend( Shape, Distance - 0.5 * Pivots, Base ) + mean_bend( Shape, Distance + 0.5 * Pivots, Base ) ); +} + +// how far from the centre the buckle reaches on each side +inline double reach( shape const &Shape ) { + + return active( Shape ) ? reach_share * Shape.length : 0.0; +} + +// the largest curvature of the buckle, 1/m, in the middle of the main lobe: pi^2 a / L^2 of the wave and 2/9 of it from the window +inline double peak_bend( double const Amplitude, double const Length ) { + + return ( 1.0 + 2.0 / ( 4.0 * reach_share * reach_share ) ) * glm::pi() * glm::pi() * std::abs( Amplitude ) / ( Length * Length ); +} + +// the heat + +inline constexpr double steel_modulus { 210e9 }; // Pa +inline constexpr double steel_expansion { 1.15e-5 }; // 1/K +inline constexpr double sun_heating { 17.0 }; // K a rail in full sun is warmer than the air: 30 F (Kish, Samavedam) +inline constexpr float neutral_default { 26.f }; // C, the rail stress-free temperature PLK lays its tracks at since 2025 +inline constexpr double area_60e1 { 76.70e-4 }; // m2 +inline constexpr double area_49e1 { 62.92e-4 }; +inline constexpr double area_s42 { 54.2e-4 }; + +// the rail section by the name of the rail profile, 60E1 if it tells nothing +inline double rail_area( std::string_view const Profile ) { + + auto const has = [ Profile ]( std::string_view const Part ) { + return std::search( Profile.begin(), Profile.end(), Part.begin(), Part.end(), []( char const Left, char const Right ) { + return std::tolower( static_cast( Left ) ) == std::tolower( static_cast( Right ) ); } ) != Profile.end(); }; + if( has( "49" ) ) { + return area_49e1; + } + if( has( "s42" ) ) { + return area_s42; + } + return area_60e1; +} + +// the force along a rail held from growing longer, N, pressing for Rise above the neutral temperature +inline double thermal_force( double const Area, double const Rise ) { + + return steel_modulus * Area * steel_expansion * Rise; +} + +// the temperature of a rail, C, from the air, the height of the sun over the horizon in degrees and the clouds (0 clear, 1 overcast; +// above 1 it rains, which cools as much) +inline double rail_temperature( double const Air, double const Sun, double const Overcast ) { + + auto const sun { std::max( 0.0, std::sin( glm::radians( Sun ) ) ) }; + return Air + sun_heating * sun * ( 1.0 - std::clamp( Overcast, 0.0, 1.0 ) ); +} + +// the state of the track, from the scenery +namespace grade { +inline constexpr int good { 0 }; // concrete sleepers, full ballast shoulder, consolidated +inline constexpr int average { 1 }; +inline constexpr int weak { 2 }; // timber sleepers, ballast missing, or the bed disturbed by tamping or sleeper renewal not yet consolidated +} + +struct cwr { + float neutral { neutral_default }; // C + int grade { grade::average }; + bool worked { false }; // works on the bed lately: weak whatever the grade +}; + +// the rise above the neutral temperature at which the track buckles: from low on under a passing train, which lifts it between the +// bogies and takes away part of its hold sideways, at high and above by itself +struct limits { + double low { 0.0 }; // K + double high { 0.0 }; +}; + +inline constexpr std::array grade_limits { { { 40.0, 55.0 }, { 32.0, 45.0 }, { 22.0, 32.0 } } }; + +// for the grade of the track, lowered in a curve, which presses outwards, and by an uneven line, which gives it a start +inline limits limits_of( cwr const &Track, double const Radius, double const Side ) { + + auto const kind { Track.worked ? grade::weak : std::clamp( Track.grade, grade::good, grade::weak ) }; + auto result { grade_limits[ kind ] }; + auto less { 0.0 }; + auto const radius { std::abs( Radius ) }; + if( radius > 0.0 && radius < 300.0 ) { + less += 6.0; + } + else if( radius > 0.0 && radius < 600.0 ) { + less += 3.0; + } + if( Side > 15.0 ) { + less += 3.0; + } + result.low -= less; + result.high -= less; + return result; +} + +// the share of the passes of a train which buckle the track at the rise: none below low, all at high +inline double chance( double const Rise, limits const &Limits ) { + + if( Limits.high <= Limits.low ) { + return Rise >= Limits.high ? 1.0 : 0.0; + } + return std::clamp( ( Rise - Limits.low ) / ( Limits.high - Limits.low ), 0.0, 1.0 ); +} + +enum class verdict { + none, + under_train, + by_itself +}; + +// with Train the track has a train going over it hard enough, Draw is the draw of the pass, 0 to 1 +inline verdict decide( double const Rise, limits const &Limits, bool const Train, double const Draw ) { + + if( Rise >= Limits.high ) { + return verdict::by_itself; + } + if( Train && Rise >= Limits.low && Draw < chance( Rise, Limits ) ) { + return verdict::under_train; + } + return verdict::none; +} + +// a train stirs the track up when it goes fast or brakes on it +inline constexpr double stirring_speed { 40.0 }; // km/h +inline bool stirs( double const Speed, bool const Braking ) { + + return Speed > stirring_speed || ( Braking && Speed > 5.0 ); +} + +// draws, the same for the same track and seed + +// FNV-1a, which std::hash isn't on every compiler +inline std::uint64_t name_hash( std::string_view const Name ) { + + std::uint64_t hash { 14695981039346656037ULL }; + for( auto const character : Name ) { + hash ^= static_cast( character ); + hash *= 1099511628211ULL; + } + return hash; +} + +// the splitmix64 finalizer, so close numbers give far apart draws +inline std::uint64_t scramble( std::uint64_t Value ) { + + Value += 0x9e3779b97f4a7c15ULL; + Value = ( Value ^ ( Value >> 30 ) ) * 0xbf58476d1ce4e5b9ULL; + Value = ( Value ^ ( Value >> 27 ) ) * 0x94d049bb133111ebULL; + return Value ^ ( Value >> 31 ); +} + +// what a draw is for, so the draws for one track don't go together +enum purpose : std::uint64_t { + pass = 1, + site = 2, + place = 3, + way = 4 +}; + +// a fraction 0 to 1 +inline double draw( std::uint64_t const Name, std::uint32_t const Seed, std::uint64_t const Purpose, std::uint64_t const Number = 0 ) { + + auto const value { scramble( scramble( scramble( Name ^ Purpose ) + Seed ) + Number ) }; + // the 53 high bits + return static_cast( value >> 11 ) / 9007199254740992.0; +} + +// where the track buckles by the temperature on its own: one place in so many metres of track, and the tracks worked on lately. +// Elsewhere the bed holds far beyond the limits of the grade (Sweden: 200 buckles in the hot summer of 2018 on 14 000 km) +inline constexpr double site_spacing { 10000.0 }; // m + +inline bool weak_spot( std::uint64_t const Name, std::uint32_t const Seed, double const Length, bool const Worked ) { + + return Worked || draw( Name, Seed, site ) < Length / site_spacing; +} + +// the entries in the scenery + +// buckle ;;[;] +struct declared { + float amplitude { 0.f }; // mm + float length { -1.f }; // m, negative: by the shape of the track + float centre { -1.f }; // m, negative: drawn + int side { 0 }; +}; + +inline bool given( declared const &Values ) { + + return Values.amplitude > 0.f; +} + +// the numbers of an entry like "400;18;60", NaN where left out +template +std::array read_numbers( std::string_view const Text ) { + + std::array result; + result.fill( std::numeric_limits::quiet_NaN() ); + auto rest { Text }; + for( auto &field : result ) { + auto const end { std::min( rest.find( ';' ), rest.size() ) }; + if( auto value { 0.f }; end > 0 && std::from_chars( rest.data(), rest.data() + end, value ).ec == std::errc {} && std::isfinite( value ) ) { + field = value; + } + if( end == rest.size() ) { + break; + } + rest.remove_prefix( end + 1 ); + } + return result; +} + +inline declared read_buckle( std::string_view const Text ) { + + auto const fields { read_numbers<4>( Text ) }; + declared result; + if( std::isfinite( fields[ 0 ] ) ) { + result.amplitude = std::clamp( fields[ 0 ], 0.f, static_cast( most_amplitude * 1000.0 ) ); + } + if( std::isfinite( fields[ 1 ] ) && fields[ 1 ] > 0.f ) { + result.length = std::clamp( fields[ 1 ], static_cast( least_length ), static_cast( most_length ) ); + } + if( std::isfinite( fields[ 2 ] ) && fields[ 2 ] >= 0.f ) { + result.centre = fields[ 2 ]; + } + if( std::isfinite( fields[ 3 ] ) ) { + result.side = ( fields[ 3 ] > 0.f ? 1 : fields[ 3 ] < 0.f ? -1 : 0 ); + } + return result; +} + +inline std::string write_buckle( declared const &Values ) { + + if( false == given( Values ) ) { + return {}; + } + std::ostringstream text; + text << "buckle " << Values.amplitude << ';'; + if( Values.length > 0.f ) { + text << Values.length; + } + text << ';'; + if( Values.centre >= 0.f ) { + text << Values.centre; + } + if( Values.side != 0 ) { + text << ';' << Values.side; + } + text << ' '; + return text.str(); +} + +// cwr ;[;] +inline cwr read_cwr( std::string_view const Text ) { + + auto const fields { read_numbers<3>( Text ) }; + cwr result; + if( std::isfinite( fields[ 0 ] ) ) { + result.neutral = std::clamp( fields[ 0 ], -20.f, 60.f ); + } + if( std::isfinite( fields[ 1 ] ) ) { + result.grade = std::clamp( static_cast( std::lround( fields[ 1 ] ) ), 0, 2 ); + } + if( std::isfinite( fields[ 2 ] ) ) { + result.worked = fields[ 2 ] > 0.f; + } + return result; +} + +inline std::string write_cwr( cwr const &Values ) { + + if( Values.neutral == neutral_default && Values.grade == grade::average && false == Values.worked ) { + return {}; + } + std::ostringstream text; + text << "cwr " << Values.neutral << ';' << Values.grade; + if( Values.worked ) { + text << ";1"; + } + text << ' '; + return text.str(); +} + +// the buckle of the values on a track of the length, which curves to the side Outward (-1 left, 1 right, 0 straight), with radius +// Radius (0 straight); None for one which doesn't fit into the track. Place and Way are draws for the centre and the side not given +inline shape resolve( declared const &Values, double const Length, int const Outward, double const Radius, double const Place, double const Way ) { + + if( false == given( Values ) ) { + return {}; + } + auto const curve { Outward != 0 && Radius > 0.0 && Radius < curve_radius }; + shape result; + result.length = Values.length > 0.f ? static_cast( Values.length ) : ( curve ? curve_length : straight_length ); + auto const first { reach_share * result.length + end_margin }; + auto const last { Length - reach_share * result.length - end_margin }; + if( last < first ) { + return {}; + } + result.centre = Values.centre >= 0.f ? std::clamp( static_cast( Values.centre ), first, last ) : first + ( last - first ) * Place; + auto const side { Values.side != 0 ? Values.side : Outward != 0 ? Outward : ( Way < 0.5 ? -1 : 1 ) }; + result.amplitude = side * 0.001 * Values.amplitude; + return result; +} + +// the buckle the temperature makes on a track: as large as a curve or a straight one makes +inline declared natural( bool const Curve ) { + + declared result; + result.amplitude = static_cast( 1000.0 * ( Curve ? curve_amplitude : straight_amplitude ) ); + result.length = static_cast( Curve ? curve_length : straight_length ); + return result; +} + +} // namespace track_buckle From b5f7811f645345ce399e7a978af0f6c7732aca5b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 11:48:52 +0100 Subject: [PATCH 16/59] feat(physics): the curvature of a buckled track in the criteria of derailment derailment::track_state::buckle_curvature [1/m], positive bending with the curve (either way on a straight track), taken whole (buckle_share 1.0): a buckle is a long wave the body follows as it does the curve. It adds to 1/R in the lateral acceleration the cant doesn't balance and in the angle of attack of the leading axle; where the buckle bends the line against the curve, out of the bend is into the curve, where the cant leans the vehicle too. The body feels the mean of the curvatures at its pivots, each bogie averaging it over its wheelbase (track_buckle::body_bend()). A coach (42 t, pivots 17.2 m) over a buckle 0.3 m by 20 m on a straight track: goes over at 30 and 60 km/h, off the rails from 125 km/h, the same within 2 km/h with steps of 0.002, 0.01 and 0.03 s; 0.6 m by 20 m from 89 km/h, the default buckle of a straight track (0.4 m by 14 m) from 57 km/h, a two-axle wagon (9 m) over 0.3 by 20 from 92 km/h. Out of a curve of 600 m the 0.3 m buckle derails it from 102 km/h, the curve alone from 169 km/h. --- McZapkie/derailment.cpp | 24 +++- McZapkie/derailment.h | 11 ++ tests/unit/test_track_buckle_derailment.cpp | 131 ++++++++++++++++++++ 3 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 tests/unit/test_track_buckle_derailment.cpp diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index 5cccc9f9c..9ddf31917 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -79,6 +79,22 @@ double unbalanced_acceleration(double const Velocity, double const Radius, doubl return Velocity * Velocity / std::abs(Radius) - cant; } +double line_curvature(track_state const &Track) { + auto const buckle{buckle_share * Track.buckle_curvature}; + if (false == curved(Track.radius)) { + return std::abs(buckle); + } + return 1.0 / std::abs(Track.radius) + buckle; +} + +double line_acceleration(track_state const &Track, double const Velocity) { + if (Track.buckle_curvature == 0.0) { + return unbalanced_acceleration(Velocity, Track.radius, Track.cant); + } + // bent against the curve, out of the bend is into the curve, where the cant leans the vehicle too + return Velocity * Velocity * line_curvature(Track) - gravity * std::sin(std::abs(Track.cant)); +} + double unloading_ratio(double const Acceleration, double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { return 2.0 / ContactSpacing * std::abs(Acceleration) / gravity * leaning_height(CentreOfGravity, Suspension); } @@ -157,7 +173,7 @@ wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Trac auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; auto const staticload{Vehicle.mass * gravity / (2.0 * axles)}; - auto const inertia{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant)}; + auto const inertia{Vehicle.mass * line_acceleration(Track, Velocity)}; auto const couplings{coupling_force(Vehicle, Track)}; auto const quasistatic{inertia + couplings}; // the sway and the uneven track push the worst way: towards the rail the vehicle already leans on @@ -167,8 +183,8 @@ wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Trac // the leading axle meets the rail at an angle in a curve, the creep force of its inner wheel at most the friction auto guiding{0.0}; - if (curved(Track.radius)) { - auto const attack{Vehicle.axle_base / (2.0 * std::abs(Track.radius))}; + if (auto const curvature{std::abs(line_curvature(Track))}; curvature > 0.0) { + auto const attack{0.5 * Vehicle.axle_base * curvature}; guiding = tread_friction * staticload * std::min(1.0, attack / saturated_attack); } result.y = std::abs(result.lateral) / axles + guiding; @@ -186,7 +202,7 @@ double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, } auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; // the couplings pull at the height of the buffers: as much of a lean as their moment gives - auto const moment{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant) * height + coupling_force(Vehicle, Track) * buffer_height}; + auto const moment{Vehicle.mass * line_acceleration(Track, Velocity) * height + coupling_force(Vehicle, Track) * buffer_height}; return std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity) * condition_of(Track).lateral; } diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 7d587517f..65058bd4a 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -124,6 +124,9 @@ struct track_state { double gauge{1.435}; // [m] double uneven_curvature{0.0}; // the lateral curvature of the unevenness under the vehicle [1/m] double uneven_cross{0.0}; // the cross level unevenness of the track [mm] + // the curvature a buckle of the track adds under the vehicle [1/m], see world/TrackBuckle.h: positive bending with + // the curve, on a straight track either way + double buckle_curvature{0.0}; int damage{0}; // dtrack_* flags }; @@ -135,6 +138,14 @@ struct track_condition { track_condition condition_of(track_state const &Track); // share of the vehicle that follows the short waves of an uneven track: the wheelsets and the bogies, the body not inline constexpr double uneven_share{0.3}; +// and the long wave of a buckle, which the body follows whole, as it does the curve +inline constexpr double buckle_share{1.0}; +// the curvature of the line under the vehicle [1/m], positive towards the centre of the curve: the curve, and a +// buckle on it. negative where a buckle bends the line the other way more than the curve does +double line_curvature(track_state const &Track); +// the lateral acceleration [m/s2] the cant doesn't balance on that line, positive out of the curve: +// unbalanced_acceleration() with a buckle +double line_acceleration(track_state const &Track, double Velocity); // the angle [rad] between the vehicle and the line of the force of the coupling at the end, in a curve: half the // angle between the two vehicles, whose middles are half their lengths apart along the curve diff --git a/tests/unit/test_track_buckle_derailment.cpp b/tests/unit/test_track_buckle_derailment.cpp new file mode 100644 index 000000000..1b72db4cc --- /dev/null +++ b/tests/unit/test_track_buckle_derailment.cpp @@ -0,0 +1,131 @@ +#include "stdafx.h" +#include "doctest.h" +#include "McZapkie/derailment.h" +#include "world/TrackBuckle.h" + +#include + +// a vehicle over a buckled track, by the criteria of derailment.h: the curvature of the buckle goes into the track +// under the vehicle as buckle_curvature (world/TrackBuckle.h: the body by the mean of its pivots, each bogie over its +// wheelbase), whole, as the curvature of the curve does + +namespace { + +// a four-axle coach: 42 t, 24.5 m over the buffers, the pivots 17.2 m and the axles of a bogie 2.5 m apart +derailment::vehicle_state coach() +{ + derailment::vehicle_state vehicle; + vehicle.mass = 42000.0; + vehicle.axles = 4; + vehicle.length = 24.5; + vehicle.axle_base = 2.5; + vehicle.centre_of_gravity = 1.4; + return vehicle; +} +double constexpr pivots{17.2}; + +// a two-axle wagon: 25 t, 14 m over the buffers, the axles 9 m apart, which are its pivots +derailment::vehicle_state wagon() +{ + derailment::vehicle_state vehicle; + vehicle.mass = 25000.0; + vehicle.axles = 2; + vehicle.length = 14.0; + vehicle.axle_base = 9.0; + vehicle.centre_of_gravity = 1.6; + return vehicle; +} + +struct rolling_stock { + derailment::vehicle_state vehicle; + double pivots; + double base; // of the bogies, 0 without +}; +rolling_stock const four_axle{coach(), pivots, 2.5}; +rolling_stock const two_axle{wagon(), 9.0, 0.0}; + +// Outward: the side out of the curve of Radius (-1 left, 1 right), 0 on a straight track +derailment::outcome ride(track_buckle::shape const &Shape, double const Radius, int const Outward, double const Speed, double const Step, rolling_stock const &Stock = four_axle) +{ + auto const &vehicle{Stock.vehicle}; + derailment::monitor monitor; + auto const velocity{Speed / 3.6}; + auto const reach{track_buckle::reach(Shape) + Stock.pivots}; + for (auto at = Shape.centre - reach - 5.0; at <= Shape.centre + reach + 5.0; at += velocity * Step) + { + derailment::track_state track; + track.radius = Radius; + auto const bend{track_buckle::body_bend(Shape, at, Stock.pivots, Stock.base)}; + // positive bending with the curve, whose centre is away from the outer side + track.buckle_curvature = (Outward != 0 ? -Outward * bend : bend); + auto const verdict{monitor.update(vehicle, track, velocity, velocity * Step)}; + if (verdict.result != derailment::outcome::none) + return verdict.result; + } + return derailment::outcome::none; +} + +// the lowest speed it leaves the rails at, km/h, to 0.5 km/h +double limit(track_buckle::shape const &Shape, double const Radius, int const Outward, double const Step, rolling_stock const &Stock = four_axle) +{ + auto low{5.0}; + auto high{300.0}; + while (high - low > 0.5) + { + auto const middle{0.5 * (low + high)}; + if (ride(Shape, Radius, Outward, middle, Step, Stock) != derailment::outcome::none) + high = middle; + else + low = middle; + } + return high; +} + +} // namespace + +TEST_CASE("a coach goes over a buckle slowly, and leaves the rails on it fast") +{ + // 0.3 m out over a main lobe of 20 m on a straight track: an equivalent radius of 110 m, felt by the body less + track_buckle::shape const shape{0.3, 20.0, 60.0}; + CHECK(ride(shape, 0.0, 0, 30.0, 0.01) == derailment::outcome::none); + CHECK(ride(shape, 0.0, 0, 60.0, 0.01) == derailment::outcome::none); + CHECK(ride(shape, 0.0, 0, 140.0, 0.01) != derailment::outcome::none); + auto const speed{limit(shape, 0.0, 0, 0.01)}; + MESSAGE("coach over a buckle 0.3 m by 20 m on a straight track: off the rails from ", speed, " km/h"); + CHECK(speed > 60.0); + CHECK(speed < 140.0); + // the same with any step + CHECK(limit(shape, 0.0, 0, 0.002) == doctest::Approx(speed).epsilon(2.0 / speed)); + CHECK(limit(shape, 0.0, 0, 0.03) == doctest::Approx(speed).epsilon(2.0 / speed)); + // either way on a straight track + track_buckle::shape const left{-0.3, 20.0, 60.0}; + CHECK(limit(left, 0.0, 0, 0.01) == doctest::Approx(speed).epsilon(1.0 / speed)); + // a larger buckle derails it slower + auto const large{limit(track_buckle::shape{0.6, 20.0, 60.0}, 0.0, 0, 0.01)}; + MESSAGE("0.6 m by 20 m: ", large, " km/h"); + CHECK(large < speed); + // the default one of a straight track, 0.4 m by 14 m + auto const natural{limit(track_buckle::shape{track_buckle::straight_amplitude, track_buckle::straight_length, 60.0}, 0.0, 0, 0.01)}; + MESSAGE("the default buckle of a straight track, 0.4 m by 14 m: ", natural, " km/h"); + CHECK(natural < speed); + // a body on two axles 9 m apart doesn't span the main lobe as one on bogies 17.2 m apart does: it follows the + // buckle closer, and goes off the rails slower + auto const short_wagon{limit(shape, 0.0, 0, 0.01, two_axle)}; + MESSAGE("a two-axle wagon over 0.3 m by 20 m: ", short_wagon, " km/h"); + CHECK(short_wagon < speed); + CHECK(ride(shape, 0.0, 0, 30.0, 0.01, two_axle) == derailment::outcome::none); +} + +TEST_CASE("a buckle out of a curve derails a coach slower than the same on a straight track") +{ + track_buckle::shape const shape{0.3, 20.0, 60.0}; + auto const straight{limit(shape, 0.0, 0, 0.01)}; + // a curve of 600 m without cant, the buckle to the right out of it (a curve to the left) + auto const curve{limit(track_buckle::shape{}, 600.0, 0, 0.01)}; + auto const outwards{limit(shape, 600.0, 1, 0.01)}; + MESSAGE("R 600 m: the curve alone from ", curve, " km/h, with the buckle out of it from ", outwards, " km/h, on a straight ", straight, " km/h"); + CHECK(outwards < straight); + CHECK(outwards < curve); + // one into the curve (not what the heat does) still lowers it, by its flanks which bend with the curve + CHECK(limit(track_buckle::shape{-0.3, 20.0, 60.0}, 600.0, 1, 0.01) < curve); +} From 7b41be312715b3f4f9c7f96376d3bb12ef0dab77 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 12:25:29 +0100 Subject: [PATCH 17/59] feat(physics): a vehicle passes on the curvature of a buckle under it TTrackShape::buckle_curvature, set by TDynamicObject next to the radius: the mean of the curvatures of the buckle at the outer axles, each averaged over the wheelbase of its bogie (TTrackFollower::BuckleCurvature(), TTrack::buckle_curvature()), positive bending with the curve. check_derailment() takes it into derailment::track_state::buckle_curvature, and a vehicle derailed with a buckle under it says so in the log ("derailed on buckled track"). --- McZapkie/MOVER.h | 2 ++ McZapkie/Mover.cpp | 6 ++++++ vehicle/DynObj.cpp | 2 ++ world/Track.h | 3 +++ world/TrackBuckle.cpp | 12 ++++++++++++ world/TrkFoll.cpp | 5 +++++ world/TrkFoll.h | 2 ++ 7 files changed, 32 insertions(+) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 63783419b..d4a7cb2b2 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -695,6 +695,8 @@ struct TTrackShape double uneven_curvature = 0.0; /// Cross level unevenness of the track [mm]. double uneven_cross = 0.0; + /// Curvature a buckle of the track adds under the body [1/m], positive with the curve, see world/TrackBuckle.h. + double buckle_curvature = 0.0; }; /// Per-segment track parameters: gauge, friction, category, load capacity, damage. diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2fa19e184..d73479058 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1545,6 +1545,7 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co track.gauge = TrackW; track.uneven_curvature = Shape.uneven_curvature; track.uneven_cross = Shape.uneven_cross; + track.buckle_curvature = Shape.buckle_curvature; track.damage = Track.DamageFlag; auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; @@ -1574,6 +1575,11 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve Name, Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Track.radius), cant, Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, Vehicle.ends[end::front].compression / 1000.0, Vehicle.ends[end::rear].compression / 1000.0, Track.damage, Track.uneven_cross)); + if (Track.buckle_curvature != 0.0) + { + ErrorLog(std::format("Bad driving: {} derailed on buckled track, the buckle bending the line by 1/{:.0f} m {} the curve", Name, 1.0 / std::abs(Track.buckle_curvature), + Track.buckle_curvature > 0.0 ? "with" : "against")); + } } void TMoverParameters::Derail(DerailReason const Reason) diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 66b1007df..ca4ca771f 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3230,6 +3230,8 @@ bool TDynamicObject::Update(double dt, double dt1) // the uneven track under the outer axles, for the criteria of derailment: its lateral curvature, and its cross level ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); ts.uneven_cross = MyTrack->uneven_underway().cross; + // a buckle of the track under the body: the mean of the curvatures at the outer axles, each over the wheelbase of its bogie + ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( MoverParameters->ADist ) + Axle1.BuckleCurvature( MoverParameters->ADist ) ); // TTrackParam tp; tp.Width = MyTrack->fTrackWidth; // McZapkie-250202 diff --git a/world/Track.h b/world/Track.h index 3fefde977..81c80785d 100644 --- a/world/Track.h +++ b/world/Track.h @@ -426,6 +426,9 @@ public: static void update_buckling( double const Deltatime ); // the radius of the path in the plan at the distance, 0 straight, and the side away from its centre: -1 left, 1 right, 0 straight double plan_radius( double const Distance, int &Outward ) const; + // the curvature the buckle adds at the distance, averaged over Base around it, 1/m: positive bending with the curve, on a straight + // track to the right of the path + double buckle_curvature( double const Distance, double const Base ) const; // closes the gaps and steps of cant between the ends of joined paths void share_joints(); double joint_depth() const; // mm diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp index b49dd5753..c8c20fe08 100644 --- a/world/TrackBuckle.cpp +++ b/world/TrackBuckle.cpp @@ -61,6 +61,18 @@ double TTrack::plan_radius( double const Distance, int &Outward ) const { return 1.0 / curvature; } +double TTrack::buckle_curvature( double const Distance, double const Base ) const { + + if( false == is_buckled() || false == track_buckle::within( m_buckle, Distance ) ) { + return 0.0; + } + auto const bend { track_buckle::mean_bend( m_buckle, Distance, Base ) }; + auto outward { 0 }; + plan_radius( Distance, outward ); + // the centre of the curve is away from the outer side + return outward != 0 ? -outward * bend : bend; +} + std::uint64_t TTrack::buckle_key() const { if( false == m_name.empty() && m_name != "none" ) { diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index 035e0bd96..ca215e3ba 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -272,6 +272,11 @@ 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; +} + bool TTrackFollower::ComputatePosition() { // ustalenie współrzędnych XYZ if (pCurrentSegment) // o ile jest tor diff --git a/world/TrkFoll.h b/world/TrkFoll.h index 62f386a95..f4741e3ec 100644 --- a/world/TrkFoll.h +++ b/world/TrkFoll.h @@ -43,6 +43,8 @@ public: return pCurrentSegment ? pCurrentSegment->uneven_bend( fCurrentDistance ) : glm::dvec3 { 0.0 }; }; // TTrack::rail_phase of the point Offset ahead of the axle along the vehicle double RailPhase( double const Offset ) const; + // TTrack::buckle_curvature at the axle, averaged over Base around it + double BuckleCurvature( double const Base ) const; bool Init(TTrack *pTrack, TDynamicObject *NewOwner, double fDir); void Reset(); void Render(float fNr); From 4d2c8c2d59a46dd58d2d9be006b95ca35e7832dd Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 12:35:35 +0100 Subject: [PATCH 18/59] feat(physics): the crush of the vehicle ends past the buffers, the override and the push off the track McZapkie/collision.{h,cpp} in eu07_core, plain functions of the vehicles and of the hit, for the collisions of physics.derailment new: - the force-crush curve of an end: a peak, a lower plateau as it folds, packing down past a depth, rigid past its limit (the shape of the FRA full scale tests); defaults for a wagon or a coach (3 / 2 MN), a locomotive (4 / 3 MN) and a crash zone of EN 15227 (2 MN over 0.8 m), optional keys of the .fiz per end - the hit on the stop of the buffers limited to the force the weaker end gives at: the motion of the pair integrated in slices over the step, the crush going to the weaker end, the elastic rest springing back with the old restitution. the momentum is kept, the force never goes past the crush force, and the depth doesn't depend on the step - the override: past 0.35 m of crush the lighter vehicle, or the one with its buffers 40 mm higher, climbs onto the other one, past 0.6 m both; interlocked anticlimbers hold them until a crush zone is used up - the push off the track: Y / Q of the leading wheel of an end pressed in, from the angle of the force in a curve and of the crushed end, and the pitch of the vehicle unloading it; 250 kN in a curve of 150 m (EN 15566) keeps an empty two-axle wagon on, 600 kN pushes it off - the buffers of the categories of EN 15551 the physical model of the coupling meets the buffers of a pair closer by the crush of its ends --- CMakeLists.txt | 1 + McZapkie/collision.cpp | 310 ++++++++++++++++++++++++++++++++++++ McZapkie/collision.h | 214 +++++++++++++++++++++++++ McZapkie/couplerphysics.cpp | 2 +- McZapkie/couplerphysics.h | 1 + 5 files changed, 527 insertions(+), 1 deletion(-) create mode 100644 McZapkie/collision.cpp create mode 100644 McZapkie/collision.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 76f359eab..d89b9a45d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -538,6 +538,7 @@ set(CORE_SOURCES "McZapkie/Mover.cpp" "McZapkie/couplerphysics.cpp" "McZapkie/derailment.cpp" +"McZapkie/collision.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp new file mode 100644 index 000000000..60bcf4a41 --- /dev/null +++ b/McZapkie/collision.cpp @@ -0,0 +1,310 @@ +/* +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 "collision.h" + +#include +#include +#include + +#include "derailment.h" + +namespace collision { + +namespace { + +// the hit is integrated in slices of this length at most, and in no more than so many of them [s] +constexpr double slice{0.0005}; +constexpr double slices_max{200.0}; + +// the force of a curve over a range of crush within one of its parts, the force linear in it there [J] +double linear_work(double const ForceFrom, double const ForceTo, double const Length) { + return 0.5 * (ForceFrom + ForceTo) * std::max(Length, 0.0); +} + +} // namespace + +double crush_curve::force(double const Crush) const { + if (Crush >= limit) { + return std::numeric_limits::infinity(); + } + if (Crush < onset) { + return peak; + } + if (Crush < densify) { + return plateau; + } + return plateau * (1.0 + hardening * (Crush - densify)); +} + +double crush_curve::energy(double const From, double const To) const { + auto const from{std::max(From, 0.0)}; + auto const to{std::min(To, limit)}; + if (to <= from) { + return 0.0; + } + auto work{0.0}; + // the peak + work += peak * std::max(0.0, std::min(to, onset) - from); + // the plateau + auto const plateaufrom{std::max(from, onset)}; + auto const plateauto{std::min(to, std::max(densify, onset))}; + work += plateau * std::max(0.0, plateauto - plateaufrom); + // packing down + auto const densefrom{std::max(from, std::max(densify, onset))}; + if (to > densefrom) { + work += linear_work(force(densefrom), plateau * (1.0 + hardening * (to - densify)), to - densefrom); + } + return work; +} + +crush_curve default_crush(vehicle_kind const Kind) { + switch (Kind) { + case vehicle_kind::locomotive: + return {4.0e6, 3.0e6, 0.05, 0.6, 2.0, 1.2}; + case vehicle_kind::crash_zone: + return {2.0e6, 2.0e6, 0.0, 0.8, 2.5, 1.2}; + case vehicle_kind::wagon: + case vehicle_kind::coach: + default: + return {3.0e6, 2.0e6, 0.05, 0.8, 2.0, 1.5}; + } +} + +vehicle_kind kind_of(bool const Powered, bool const Passenger, bool const CrashZone) { + if (CrashZone) { + return vehicle_kind::crash_zone; + } + if (Passenger) { + return vehicle_kind::coach; + } + return Powered ? vehicle_kind::locomotive : vehicle_kind::wagon; +} + +crush_curve crush_of(end_definition const &Definition, vehicle_kind const Kind) { + auto curve{default_crush(Definition.crash_zone.value_or(false) ? vehicle_kind::crash_zone : Kind)}; + curve.peak = std::max(Definition.peak.value_or(curve.peak), 1.0); + curve.plateau = std::max(Definition.plateau.value_or(curve.plateau), 1.0); + curve.onset = std::max(Definition.onset.value_or(curve.onset), 0.0); + curve.densify = std::max(Definition.densify.value_or(curve.densify), curve.onset); + curve.hardening = std::max(Definition.hardening.value_or(curve.hardening), 0.0); + curve.limit = std::max(Definition.limit.value_or(curve.limit), curve.onset); + return curve; +} + +bool anticlimber_of(end_definition const &Definition, vehicle_kind const Kind) { + return Definition.anticlimber.value_or(Definition.crash_zone.value_or(Kind == vehicle_kind::crash_zone)); +} + +double buffer_height(end_definition const &Definition, vehicle_kind const Kind, double const LoadShare) { + auto const wagon{Kind == vehicle_kind::wagon}; + auto const empty{Definition.buffer_height.value_or(wagon ? 1.065 : 1.040)}; + // the springs of a wagon give 125 mm under its full load + return wagon ? empty - 0.125 * std::clamp(LoadShare, 0.0, 1.0) : empty; +} + +buffer_rating rating(buffer_category const Category) { + switch (Category) { + case buffer_category::B: + return {0.105, 50.0e3}; + case buffer_category::C: + return {0.105, 70.0e3}; + case buffer_category::L: + return {0.150, 70.0e3}; + case buffer_category::passenger: + return {0.110, 30.0e3}; + case buffer_category::A: + default: + return {0.105, 30.0e3}; + } +} + +coupler_physics::spring_curve buffer_curve(buffer_category const Category, double const Progression) { + auto const buffer{rating(Category)}; + auto const progression{std::clamp(Progression, 0.0, 0.9)}; + // the energy of the curve to the end of the stroke is F_end * stroke * ((1 - p) / 2 + p / 4), of two buffers + auto const endforce{2.0 * buffer.energy / (buffer.stroke * ((1.0 - progression) / 2.0 + progression / 4.0))}; + return {endforce / buffer.stroke, buffer.stroke, progression}; +} + +std::optional buffer_category_of(char const Name) { + switch (Name) { + case 'A': + case 'a': + return buffer_category::A; + case 'B': + case 'b': + return buffer_category::B; + case 'C': + case 'c': + return buffer_category::C; + case 'L': + case 'l': + return buffer_category::L; + case 'P': + case 'p': + return buffer_category::passenger; + default: + return std::nullopt; + } +} + +hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input) { + hit_result result; + if (Input.velocity <= 0.0 || Input.mass1 <= 0.0 || Input.mass2 <= 0.0 || Input.dt <= 0.0) { + return result; + } + auto const mass{Input.mass1 * Input.mass2 / (Input.mass1 + Input.mass2)}; + auto const restitution{std::clamp(Input.restitution, 0.0, 0.95)}; + // the elastic hit on the steel at the closing velocity adds root * velocity to the force of the springs + auto const root{std::sqrt(std::max(Input.stiffness, 1.0) * mass)}; + auto const springs{std::max(Input.springs, 0.0)}; + // the closing velocity the step started with: the springs slow the pair over the step as well, the hit adds what + // they don't carry of the force the end gives at + auto velocity{Input.start_velocity > 0.0 ? std::max(Input.start_velocity, Input.velocity) : Input.velocity + springs * Input.dt / mass}; + // where the forces of the step alone would take the pair + auto const unhit{velocity - springs * Input.dt / mass}; + + auto crush1{First.crush}; + auto crush2{Second.crush}; + auto const elastic_limit = [&](double const Force) { return std::max(0.0, Force - springs) / root; }; + { + auto const force{std::min(First.curve.force(crush1), Second.curve.force(crush2))}; + if (false == std::isfinite(force) || velocity <= elastic_limit(force)) { + // the steel takes it all: the legacy elastic exchange + return result; + } + } + result.crushing = true; + + auto const slices{std::clamp(std::ceil(Input.dt / slice), 1.0, slices_max)}; + auto const length{Input.dt / slices}; + auto time{0.0}; + auto rebound{false}; + auto crushtime{0.0}; + while (Input.dt - time > 1e-12) { + auto const force1{First.curve.force(crush1)}; + auto const force2{Second.curve.force(crush2)}; + auto const force{std::min(force1, force2)}; + if (false == std::isfinite(force) || velocity <= elastic_limit(force)) { + // both ends crushed all the way, or the pair slowed down to what the steel takes back + rebound = true; + break; + } + auto const limit{elastic_limit(force)}; + auto step{std::min(length, Input.dt - time)}; + auto change{force * step / mass}; + if (velocity - change < limit) { + step = (velocity - limit) * mass / force; + change = velocity - limit; + } + auto const crush{(velocity - 0.5 * change) * step}; + // the weaker end gives, both alike when they're alike + if (std::abs(force1 - force2) <= 1e-9 * force) { + crush1 += 0.5 * crush; + crush2 += 0.5 * crush; + } + else if (force1 < force2) { + crush1 += crush; + } + else { + crush2 += crush; + } + velocity -= change; + time += step; + crushtime += step; + result.force = std::max(result.force, force); + } + + auto after{velocity}; + auto duration{crushtime}; + if (rebound) { + // the steel springs back with the restitution, the springs push the pair apart over the rest of the step + // under the force the weaker end gives at, as the slices stopped there + result.force = std::max(result.force, springs + velocity * root); + if (velocity > 0.0) { + duration += (1.0 + restitution) * velocity * mass / std::max(velocity * root, 1.0); + } + after = -restitution * velocity - springs * (Input.dt - time) / mass; + } + result.velocity = after; + result.impulse = mass * (unhit - after); + result.duration = std::min(duration, Input.dt); + result.crush1 = crush1 - First.crush; + result.crush2 = crush2 - Second.crush; + return result; +} + +override_result override_of(override_input const &Input) { + override_result result; + if (Input.anticlimbers) { + // interlocked, they keep the ends level until the crush zone of one of them is used up + auto const spent1{Input.zone1 <= 0.0 || Input.crush1 >= Input.zone1}; + auto const spent2{Input.zone2 <= 0.0 || Input.crush2 >= Input.zone2}; + if (false == spent1 && false == spent2) { + return result; + } + } + auto const crush{Input.crush1 + Input.crush2}; + if (crush > override_both) { + result.first = true; + result.second = true; + return result; + } + if (crush <= override_crush) { + return result; + } + if (Input.mass1 * override_mass_ratio < Input.mass2) { + result.first = true; + } + else if (Input.mass2 * override_mass_ratio < Input.mass1) { + result.second = true; + } + else if (false == Input.anticlimbers && std::abs(Input.height1 - Input.height2) >= override_height - 1e-9) { + // the higher one rides up + result.first = Input.height1 > Input.height2; + result.second = false == result.first; + } + return result; +} + +double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + if (Vehicle.mass <= 0.0 || End.force <= 0.0) { + return 0.0; + } + auto const axles{static_cast(std::max(Vehicle.axles, 1))}; + // the axles of the half of the vehicle at the end: its bogie, or its axle + auto const half{std::max(axles / 2.0, 1.0)}; + auto const wheelload{Vehicle.mass * gravity / (2.0 * axles)}; + auto const halflength{std::max(0.5 * Vehicle.length, 1.0)}; + auto const angle{straight_angle + derailment::coupling_angle(Vehicle.length, End.other_length, Radius) + crush_angle * std::max(End.crush, 0.0) / halflength}; + // in a curve the leading axle meets the rail at an angle, the creep force of its inner wheel at most the friction + auto guiding{0.0}; + if (std::abs(Radius) > 1e-3) { + auto const attack{Vehicle.axle_base / (2.0 * std::abs(Radius))}; + guiding = derailment::tread_friction * wheelload * std::min(1.0, attack / derailment::saturated_attack); + } + auto const lateral{End.force * angle / half + guiding}; + // the force off the height it's carried at pitches the vehicle: the bogie at the end pressed in takes the load off + auto const pivots{Vehicle.pivots > 0.0 ? Vehicle.pivots : halflength}; + auto const vertical{wheelload - End.force * eccentricity / (2.0 * half * pivots)}; + return vertical > 0.0 ? lateral / vertical : 1e9; +} + +bool pushed_monitor::update(bool const Holds, double const Duration) { + if (false == Holds) { + m_time = 0.0; + return false; + } + m_time += std::max(Duration, 0.0); + return m_time >= pushed_time - 1e-9; +} + +} // namespace collision diff --git a/McZapkie/collision.h b/McZapkie/collision.h new file mode 100644 index 000000000..dd3dad55e --- /dev/null +++ b/McZapkie/collision.h @@ -0,0 +1,214 @@ +/* +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 "couplerphysics.h" + +// what a collision of two vehicles does to them past their buffers (physics.derailment new in eu07.ini, see +// TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: +// +// crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the +// force the weaker end gives at. past it the end crushes for good: a short peak of force, then a lower plateau as +// the structure folds, then it packs down and stiffens (the force-crush curves of the full scale tests of the FRA: +// Tyrell et al., IMECE2002-33247). the hit is an impulse limited to that force over the step, so the force never +// goes past it and the depth of the crush is the same with any step; the depth stays with the end +// override: an end crushed deep enough no longer holds the other one down: the lighter of the two vehicles, or the +// one with its buffers higher (40 mm, the vertical offset of the design collision of EN 15227), climbs onto the +// other one and leaves the rails; past a deeper crush both do. interlocked anticlimbers hold them until the crush +// zone of an end is used up +// pushed off the track: the force pressing a vehicle's end acts at an angle to it, the more in a curve and the +// deeper the end is crushed, which gives a lateral force on its wheels; acting off the height of the centre of the +// vehicle it lifts its leading wheels. Y / Q over Nadal's limit for long enough and the flange climbs the rail +// (the light wagon between heavy ones goes first, in a curve sooner than on a straight track: EN 15566 takes +// 250 kN of the pair of buffers in a curve of 150 m as the safe push) +namespace collision { + +inline constexpr double gravity{9.81}; // [m/s2] + +// ---- the crush of an end + +// force-crush characteristic of the underframe at one end of a vehicle +struct crush_curve { + double peak{3.0e6}; // the force the crushing starts at [N] + double plateau{2.0e6}; // of the crushing past the onset [N] + double onset{0.05}; // the crush past which the peak drops to the plateau [m] + double densify{0.8}; // the crush past which the crushed structure packs down and stiffens [m] + double hardening{2.0}; // the growth of the force past it, to the plateau for each metre [1/m] + double limit{1.5}; // the end can't be crushed past it, it's rigid from there [m] + + // the force the end gives at with the crush [N]; past the limit there's no force it gives at + double force(double Crush) const; + // the work it takes to crush the end from the one depth to the other one [J] + double energy(double From, double To) const; +}; + +// what the vehicle is, for its defaults +enum class vehicle_kind { + wagon, // a freight wagon + coach, // a passenger coach, or a car of a unit + locomotive, + crash_zone // a vehicle built to EN 15227, with the energy absorbers and the anticlimbers at its ends +}; +// the defaults of the kind: a wagon or a coach gives at 1.5 times the force of the proof test of EN 12663 at the +// height of the buffers (2 MN), a locomotive at 4 MN; the plateau is the 2 MN of the crush of the cab car of the FRA +// test. the absorbers of a crash zone give a steady 2 MN over 0.8 m, as the deformation tubes and the crash buffers +// do (2 MN of the crash buffers in service) +crush_curve default_crush(vehicle_kind Kind); + +// the optional keys of the .fiz for an end (BuffCoupl): what's not given comes from the kind of the vehicle +struct end_definition { + std::optional peak; // FcrushPeak [N] + std::optional plateau; // FcrushPlateau [N] + std::optional onset; // CrushOnset [m] + std::optional densify; // CrushDensify [m] + std::optional hardening; // CrushHardening [1/m] + std::optional limit; // CrushLimit [m] + std::optional crash_zone; // CrashZone: built to EN 15227 + std::optional anticlimber; // AntiClimber + std::optional buffer_height; // BufferHeight, of the empty vehicle above the rail [m] +}; +vehicle_kind kind_of(bool Powered, bool Passenger, bool CrashZone); +crush_curve crush_of(end_definition const &Definition, vehicle_kind Kind); +bool anticlimber_of(end_definition const &Definition, vehicle_kind Kind); +// height of the buffers above the rail [m]: UIC 940 to 1065 mm. without a given one, a wagon has them at the top of +// the range empty and lower by 125 mm fully loaded on its springs, a locomotive or a coach at 1040 mm +double buffer_height(end_definition const &Definition, vehicle_kind Kind, double LoadShare); + +// ---- the buffers, EN 15551 + +enum class buffer_category { + A, // 105 mm, 30 kJ + B, // 105 mm, 50 kJ + C, // 105 mm, 70 kJ + L, // the long stroke, 150 mm + passenger // 110 mm, of the coaches +}; +struct buffer_rating { + double stroke{0.105}; // [m] + double energy{30.0e3}; // dynamic energy of one buffer [J] +}; +buffer_rating rating(buffer_category Category); +// the spring curve of the two buffers of an end side by side, of the progression given, which takes in their energy +// over the stroke +coupler_physics::spring_curve buffer_curve(buffer_category Category, double Progression); +std::optional buffer_category_of(char Name); + +// ---- the hit past the buffers + +// an end of the pair, as the hit sees it +struct end_state { + crush_curve curve; + double crush{0.0}; // the depth it's crushed to already [m] +}; + +struct hit_input { + double velocity{0.0}; // the pair closes in on the stop at [m/s] + double mass1{0.0}; // [kg] + double mass2{0.0}; + double restitution{0.2}; // coefficient of restitution of the elastic rest of the hit + double stiffness{1.0e8}; // of the steel parts of both ends in series, past the springs [N/m] + double springs{0.0}; // the force the springs of the pair carry at the stop over the step [N] + double dt{0.01}; // the length of the step [s] + // the closing velocity the pair started the step with, before the forces of the step [m/s]; without it (0), the + // velocity with what the springs took off it over the step + double start_velocity{0.0}; +}; + +struct hit_result { + bool crushing{false}; // false: the hit stays elastic, it's the legacy exchange of momentum + double impulse{0.0}; // the hit adds to the forces of the step, pushing the vehicles apart [N s] + double velocity{0.0}; // the closing velocity after the step [m/s], negative as they part + double force{0.0}; // the peak force between the ends, with the springs [N] + double duration{0.0}; // how long that force acted over the step [s] + double crush1{0.0}; // added to the end of the first vehicle [m] + double crush2{0.0}; // of the second one +}; + +// the hit of the step: the steel takes the hit elastically up to the force the weaker end gives at, past that the end +// crushes at that force until the pair closes in no faster than the steel takes back. the motion over the step is +// integrated in short slices, with the springs slowing the pair as well, so the crush doesn't depend on the step +hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input); + +// a crush of an end deeper than this is a damage worth the log [m] +inline constexpr double crush_mark{0.05}; +// the draw gear sits behind the headstock: crushed this deep, the coupling of the end is torn off [m] +inline constexpr double draw_gear_crush{0.15}; + +// ---- override + +// the crush of the contact of both ends past which the lighter (or the higher) vehicle climbs onto the other one, +// and past which both leave the rails [m] +inline constexpr double override_crush{0.35}; +inline constexpr double override_both{0.6}; +// the masses differ enough for the lighter one to climb +inline constexpr double override_mass_ratio{1.3}; +// the buffers differ in height enough for the higher one to climb: the vertical offset of the design collision of +// EN 15227 [m] +inline constexpr double override_height{0.04}; + +struct override_input { + double crush1{0.0}; // of the end of the first vehicle [m] + double crush2{0.0}; + double mass1{0.0}; // [kg] + double mass2{0.0}; + double height1{1.0}; // of its buffers [m] + double height2{1.0}; + bool anticlimbers{false}; // both ends have them, interlocked + double zone1{0.0}; // the crush zone of the end with the anticlimber, its densify [m] + double zone2{0.0}; +}; +struct override_result { + bool first{false}; // the first vehicle left the rails + bool second{false}; +}; +override_result override_of(override_input const &Input); + +// ---- pushed off the track + +// the angle of the force at the end of a vehicle to it on a straight track: the play of the wheelsets and of the +// bogies, the buffer heads off the middle [rad] +inline constexpr double straight_angle{0.006}; +// the crushed end no longer keeps the ends in line: the angle grows by this share of the crush to the half length +inline constexpr double crush_angle{0.1}; +// the height the force acts at off the height it's carried at, the buffers of the pair not at the same height [m] +inline constexpr double eccentricity{0.10}; +// the time Y / Q has to stay over the limit for the flange to climb the rail [s] +inline constexpr double pushed_time{0.05}; + +struct pushed_vehicle { + double mass{0.0}; // with the load, without the rotating masses [kg] + int axles{4}; + double length{0.0}; // over the buffers [m] + double pivots{0.0}; // the distance of the bogie pivots, of the axles without bogies [m] + double axle_base{0.0}; // the wheelbase of a bogie, of the vehicle without bogies [m] +}; +struct pushed_end { + double force{0.0}; // pressing the end in [N] + double other_length{0.0}; // of the vehicle at that end [m] + double crush{0.0}; // of the end [m] +}; +// Y / Q of the leading wheel at the end pressed in by the force, in a curve of the radius [m] (0 straight) +double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); + +// the time the condition held, without a break +class pushed_monitor { +public: + // true once the condition held for the time it takes the flange to climb, given how long it held in the step [s] + bool update(bool Holds, double Duration); + void reset() { m_time = 0.0; } + double time() const { return m_time; } + +private: + double m_time{0.0}; +}; + +} // namespace collision diff --git a/McZapkie/couplerphysics.cpp b/McZapkie/couplerphysics.cpp index f6a226b55..31afd26fe 100644 --- a/McZapkie/couplerphysics.cpp +++ b/McZapkie/couplerphysics.cpp @@ -235,7 +235,7 @@ pair_result update_pair(end_parameters const &First, end_parameters const &Secon else { State.draw_gear.reset(); } - auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)}; + auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap - std::max(Input.crush, 0.0), -Input.gap_rate)}; result.tension = pulled.force; result.compression = pushed.force; diff --git a/McZapkie/couplerphysics.h b/McZapkie/couplerphysics.h index 47789aba2..8d7f9b06e 100644 --- a/McZapkie/couplerphysics.h +++ b/McZapkie/couplerphysics.h @@ -112,6 +112,7 @@ struct pair_input { bool coupled{false}; bool adapter{false}; // an adapter on either end: the buffers don't meet, the coupler takes the push alone bool damage{false}; // the link can stretch and break (crash damage on) + double crush{0.0}; // the ends of both crushed for good (collision.h), the buffers meet that much closer [m] }; struct pair_result { From 369f58a04a29f76adf05cb526be508108aceac98 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 12:41:40 +0100 Subject: [PATCH 19/59] feat(physics): collisions crush the ends of the vehicles, override and push them off the track With physics.derailment new, CollisionDetect() hands a hit on the stop of the buffers harder than the steel takes elastically to crush_hit() (collision.h): - the weaker end crushes for good at its crush force, the vehicles take the limited impulse, the depth stays with the end (TCoupling::crush) and lets the buffers of the pair meet closer, in both models of the coupling - the crush lets the lighter vehicle, or the one with its buffers higher, climb onto the other one; the end crushed by 0.15 m tears off its draw gear, with the brake hose both parts of the train brake in emergency, and an automatic coupler torn off doesn't couple again - after the collisions of each step the force pressing the ends pushes a light vehicle off the track by Y / Q held for 0.05 s - off the rails in a collision the vehicle is upright off the rails as by the criteria of the speed: it slides with the friction of the ballast and keeps taking the hits and passing the forces on, instead of standing as a wall. CollisionDerail and the log tell the override from the push off; a crushed end logs the collision It works in CollisionDetect(), which both models of the coupling reach once their buffers go solid, so the trains of the AI the physical model of the coupling doesn't cover crush alike. Hits the steel takes, and the draw gear going solid, stay the legacy collision. physics.derailment old and off keep the legacy collisions: the rule of 15 km/h weighed by the masses, the chance of the coupler smashed, a derailed vehicle a wall; the tests of that rule run with old. The buffers of a category of EN 15551 and the crush, crash zone, anticlimber and buffer height of an end are new optional keys of BuffCoupl. --- McZapkie/MOVER.h | 31 ++ McZapkie/Mover.cpp | 368 +++++++++++++++- tests/unit/test_collisions.cpp | 648 ++++++++++++++++++++++++++++ tests/unit/test_controls.cpp | 9 + tests/unit/test_couplers.cpp | 17 + tests/unit/test_couplers_trains.cpp | 21 +- 6 files changed, 1086 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_collisions.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 63783419b..8c612cca0 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "hamulce.h" #include "couplerphysics.h" #include "derailment.h" +#include "collision.h" #include "scripting/ladderlogic.h" #include "vehicle/odometerreading.h" @@ -176,6 +177,10 @@ enum DerailReason COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem /// Trailing through a switch with a movable nose set the other way. TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem + /// Climbed onto the vehicle it hit, its end crushed (physics.derailment new). + COLLISION_OVERRIDE = 7, // najechanie + /// Pushed off the track by the force pressing its end (physics.derailment new). + COLLISION_PUSHED_OFF = 8, // wyciśnięcie z toru }; /*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ @@ -1288,6 +1293,15 @@ struct TCoupling // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end coupler_physics::end_parameters physics; coupler_physics::pair_state physics_state; + // the collisions past the buffers (physics.derailment new), see collision.h: the optional keys of this end, the depth + // it's crushed to for good [m], and the hit of the pair in the step: whether either vehicle handled it already, its + // peak force [N] and how long that acted [s] + collision::end_definition collision; + double crush{0.0}; + double closing{0.0}; // the velocity the buffers of the pair closed in at, at the start of the step [m/s] + bool hit_handled{false}; + double hit_force{0.0}; + double hit_duration{0.0}; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ @@ -2444,6 +2458,23 @@ class TMoverParameters // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other // derailment, which stops it as the legacy model does derailment::outcome Derailed{derailment::outcome::none}; + // physics.derailment 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; + collision::crush_curve crush_curve_at(int End) const; + double buffer_height_at(int End) const; + collision::pushed_monitor pushed_off_monitor; + // how the vehicle left the rails in a collision (physics.derailment new): overriding or pushed off, NONE otherwise + DerailReason CollisionDerail{NONE}; + // physics.derailment new: the hit of the end on the stop of its buffers, harder than the steel takes, crushes the + // weaker end and may let one vehicle climb onto the other one, see collision.h. returns: whether it did, and the + // velocities took the hit; the legacy collision takes the rest + bool crush_hit(int End, double dt); + // the force pressing the ends pushes the vehicle off the track (physics.derailment new) + void check_pushed_off(double dt); + // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of + // derailment.h have it + void derail_in_collision(DerailReason Reason, std::string const &Why); bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ bool EIMDirectionChangeAllow(void) const; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2fa19e184..00a4b775c 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1338,6 +1338,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; + // physics.derailment new: past the buffers the ends crush (collision.h); a hit the steel takes stays the legacy one + auto const crushing{Global.derailment == global_settings::derailment_model::physical}; + if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) + { + return; + } if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) { return; @@ -1373,7 +1379,8 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } } - if (Global.crash_damage) + // the new model crushes the ends and derails the vehicles by the crush, see crush_hit() + if (Global.crash_damage && false == crushing) { // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit()) if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) @@ -1409,13 +1416,15 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the // velocity once more, and the vehicles would bounce off the stop faster than they hit it auto const accelerationspike{physical ? 0.0 : 1.0}; - if (false == TestFlag(DamageFlag, dtrain_out)) + // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit + auto const wall = [crushing](TMoverParameters const &Vehicle) { return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || Vehicle.Derailed == derailment::outcome::none); }; + if (false == wall(*this)) { auto const accelerationchange{(velocity - V) / dt}; AccS += accelerationchange * accelerationspike; V = velocity; } - if (false == TestFlag(othervehicle->DamageFlag, dtrain_out)) + if (false == wall(*othervehicle)) { auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; @@ -1465,6 +1474,278 @@ void TMoverParameters::damage_coupler(int const End) WriteLog("Bad driving: " + Name + " broke a coupler"); } +// ************************************************************************************************* +// physics.derailment new: the collisions past the buffers, see collision.h +// ************************************************************************************************* +collision::vehicle_kind TMoverParameters::collision_kind() const +{ + auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; + auto const unit{(TrainType & (dt_EZT | dt_DMU)) != 0}; + auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })}; + // a coach heats its compartments; the crash zone is a matter of each end (crush_of()) + return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); +} + +collision::crush_curve TMoverParameters::crush_curve_at(int const End) const +{ + return collision::crush_of(Couplers[End].collision, collision_kind()); +} + +double TMoverParameters::buffer_height_at(int const End) const +{ + auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; + return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); +} + +void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why) +{ + if (false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + // upright, it slides on the sleepers and keeps passing the forces on + Derailed = derailment::outcome::off_rails; + CollisionDerail = Reason; + EventFlag = true; + MainSwitch(false, range_t::local); + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrot = 0.0; + SlippingWheels = false; + } + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + if (std::any_of(std::begin(Couplers), std::end(Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) + { + AlarmChainFlag = true; + } + derailment_monitor.reset(); + pushed_off_monitor.reset(); + ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why)); +} + +namespace +{ + +char const *end_name(int const End) +{ + return End == end::front ? "front" : "rear"; +} + +// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls +double compression_at(TCoupling const &Coupler, int const End) +{ + return std::max(0.0, (End == end::front ? -1.0 : 1.0) * Coupler.CForce); +} + +// the steel parts of both ends in series [N/m] +double steel_stiffness(TCoupling const &First, TCoupling const &Second) +{ + auto const first{std::max(First.physics.link_stiffness, 1.0)}; + auto const second{std::max(Second.physics.link_stiffness, 1.0)}; + return first * second / (first + second); +} + +// the hit of the pair in the step, for the push off the track: the peak force and how long it acted +void record_hit(TCoupling &Coupler, double const Force, double const Duration) +{ + Coupler.hit_force = std::max(Coupler.hit_force, Force); + Coupler.hit_duration = std::max(Coupler.hit_duration, Duration); +} + +} // namespace + +bool TMoverParameters::crush_hit(int const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + + auto const physical{coupler_physics_at(End)}; + // the buffers pressed all the way, not the draw gear pulled all the way, and the pair still closing in + auto const buffers{physical ? thiscoupler.physics_state.stop < 0 : thiscoupler.Dist < 0.0}; + auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + if (false == Global.crash_damage || false == buffers || closing <= 0.0) + { + return false; + } + // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it + auto const wall{TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; + auto const otherwall{TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; + if (wall && otherwall) + { + return false; + } + constexpr double immovable{1e12}; + auto const mass{wall ? immovable : TotalMass}; + auto const othermass{otherwall ? immovable : othervehicle->TotalMass}; + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + + auto const firstcurve{crush_curve_at(End)}; + auto const secondcurve{othervehicle->crush_curve_at(otherend)}; + auto const stiffness{steel_stiffness(thiscoupler, othercoupler)}; + auto const springs{compression_at(thiscoupler, End)}; + collision::hit_input input; + input.velocity = closing; + input.mass1 = mass; + input.mass2 = othermass; + input.restitution = std::sqrt(std::max(0.0, 1.0 - loss)); + input.stiffness = stiffness; + input.springs = springs; + input.dt = dt; + input.start_velocity = thiscoupler.closing; + auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; + if (false == hit.crushing) + { + // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push + // off the track + auto const reduced{mass * othermass / (mass + othermass)}; + auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))}; + auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)}; + auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))}; + record_hit(thiscoupler, peak, duration); + record_hit(othercoupler, peak, duration); + return false; + } + // the other vehicle doesn't take it again in this step + thiscoupler.hit_handled = true; + othercoupler.hit_handled = true; + + // the hit at the force the weaker end gives at pushes the vehicles apart: the velocities alone change, along this + // vehicle's axis as in CollisionDetect() + auto const otherdirection{DirPatch(End, otherend)}; + auto const apart{End == end::front ? -1.0 : 1.0}; + if (false == wall) + { + V += apart * hit.impulse / mass; + } + if (false == otherwall) + { + othervehicle->V -= apart * hit.impulse / othermass * otherdirection; + } + record_hit(thiscoupler, hit.force, hit.duration); + record_hit(othercoupler, hit.force, hit.duration); + + auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { + if (Before < collision::crush_mark && After >= collision::crush_mark) + { + ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name)); + } + }; + auto const before{thiscoupler.crush}; + auto const otherbefore{othercoupler.crush}; + thiscoupler.crush += hit.crush1; + othercoupler.crush += hit.crush2; + crushed(*this, End, before, thiscoupler.crush); + crushed(*othervehicle, otherend, otherbefore, othercoupler.crush); + + // the crushed headstock tears off the draw gear, with the brake hose: both parts of the train brake in emergency. + // the coupler of an end not coupled is gone as well, it doesn't couple any more + if (thiscoupler.CouplingFlag != coupling::faux && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) + { + auto const hose{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + damage_coupler(End); + if (hose) + { + othervehicle->AlarmChainFlag = true; + } + } + else if (thiscoupler.CouplingFlag == coupling::faux) + { + if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken) + { + damage_coupler(End); + } + if (othercoupler.crush >= collision::draw_gear_crush && false == othercoupler.broken) + { + othervehicle->damage_coupler(otherend); + } + } + + // the end crushed deep enough lets one vehicle climb onto the other one + collision::override_input climbing; + climbing.crush1 = thiscoupler.crush; + climbing.crush2 = othercoupler.crush; + climbing.mass1 = TotalMass - Mred; + climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; + climbing.height1 = buffer_height_at(End); + climbing.height2 = othervehicle->buffer_height_at(otherend); + climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); + climbing.zone1 = firstcurve.densify; + climbing.zone2 = secondcurve.densify; + auto const climbed{collision::override_of(climbing)}; + auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { + return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m", Climber.Name, Other.Name, closing * 3.6, thiscoupler.crush + othercoupler.crush); + }; + if (climbed.first) + { + derail_in_collision(COLLISION_OVERRIDE, why(*this, *othervehicle)); + } + if (climbed.second) + { + othervehicle->derail_in_collision(COLLISION_OVERRIDE, why(*othervehicle, *this)); + } + return true; +} + +void TMoverParameters::check_pushed_off(double const dt) +{ + if (Global.derailment != global_settings::derailment_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || + DebugModeFlag) + { + pushed_off_monitor.reset(); + return; + } + collision::pushed_vehicle vehicle; + vehicle.mass = TotalMass - Mred; + vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.length = Dim.L; + vehicle.pivots = BDist; + vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + + auto holds{false}; + auto duration{0.0}; + auto worst{0.0}; + auto worstforce{0.0}; + auto worstend{static_cast(end::front)}; + for (int end = end::front; end <= end::rear; ++end) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + auto const &coupler{Couplers[end]}; + collision::pushed_end pushed; + pushed.other_length = other->MoverParameters->Dim.L; + pushed.crush = coupler.crush; + // the steady push of the springs over the step, or the peak of a hit for as long as it lasted + for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}}) + { + pushed.force = force; + auto const ratio{collision::pushed_ratio(vehicle, pushed, RunningShape.R)}; + if (ratio < derailment::climbing_limit) + { + continue; + } + holds = true; + duration = std::max(duration, time); + if (ratio > worst) + { + worst = ratio; + worstforce = force; + worstend = end; + } + } + } + if (pushed_off_monitor.update(holds, duration)) + { + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f}", worstforce / 1000.0, end_name(worstend), Vel, + std::abs(RunningShape.R), std::min(worst, 99.0))); + } +} + namespace { @@ -1726,6 +2007,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt); } // liczone dL, predkosc i przyspieszenie @@ -1788,7 +2070,8 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh // simple mode skips calculation of vertical acceleration AccVert = 0.0; - if (true == TestFlag(DamageFlag, dtrain_out) && Vel < 1.0) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() + if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && Vel < 1.0) { V = 0.0; AccS = 0.0; @@ -1801,6 +2084,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt); } // liczone dL, predkosc i przyspieszenie auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu @@ -5456,8 +5740,15 @@ void TMoverParameters::ComputeTotalForce(double dt) // doliczenie sił z innych pojazdów for (int end = end::front; end <= end::rear; ++end) { + // a new step: the hit of the pair not taken by either vehicle yet + Couplers[end].hit_handled = false; + Couplers[end].hit_force = 0.0; + Couplers[end].hit_duration = 0.0; + Couplers[end].closing = 0.0; if (Neighbours[end].vehicle != nullptr) { + // the velocities before the step, the forces of all the vehicles come before their movement + Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); Couplers[end].CForce = CouplerForce(end, dt); FTrain += Couplers[end].CForce; } @@ -5674,7 +5965,10 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - auto const newdistance{initialdistance + 10.0 * distancedelta}; + // the ends crushed for good (physics.derailment new, see collision.h) let the buffers meet that much closer + auto const crushed{thiscoupler.crush + othercoupler.crush}; + auto const rawdistance{initialdistance + 10.0 * distancedelta}; + auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance}; auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)}; auto const absdV{std::abs(dV)}; @@ -5819,6 +6113,11 @@ void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other { return; } + // a coupler torn off by the crush of its end (physics.derailment new) doesn't catch + if (Global.derailment == global_settings::derailment_model::physical && (thiscoupler.broken || othercoupler.broken)) + { + return; + } // sprzeganie wagonow z samoczynnymi sprzegami auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; // potentially exclude incompatible control coupling @@ -5898,7 +6197,7 @@ double TMoverParameters::coupler_force_physical(int const End, double const dt) auto const previousgap{state.gap}; auto const previousdrawgear{state.draw_gear.deflection}; - auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage})}; + auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage, thiscoupler.crush + othercoupler.crush})}; SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); @@ -5952,7 +6251,8 @@ bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; // the other vehicle keeps the state of the pair alike othercoupler.physics_state.elongation = state.elongation; - if (hit.broken || hit.crushed) + // with physics.derailment new the crush of the ends past the buffers is crush_hit()'s + if (hit.broken || (hit.crushed && Global.derailment != global_settings::derailment_model::physical)) { damage_coupler(End); } @@ -11425,6 +11725,45 @@ void scale_strength(coupler_physics::link_strength &Link, double const Factor) Link.ultimate *= Factor; } +// the optional keys of the collisions past the buffers (physics.derailment new, see collision.h), what's not given +// comes from the kind of the vehicle: +// FcrushPeak, FcrushPlateau [kN] the force the end starts to crush at, and keeps crushing at +// CrushOnset, CrushDensify, CrushLimit [m] the crush the peak drops at, it packs down past, it can't go past +// CrushHardening [1/m] the growth of the force past CrushDensify, to the plateau for each metre +// CrashZone [yes/no] built to EN 15227: energy absorbers and anticlimbers; AntiClimber [yes/no] on its own +// BufferHeight [m] of the empty vehicle above the rail +// BufferCategory [A/B/C/L/P] the buffers of EN 15551 (P those of the coaches) in place of kB and DmaxB +collision::end_definition collision_definition(std::string const &Line) +{ + collision::end_definition definition; + auto const number = [&Line](std::string const &Key, double const Scale) -> std::optional { + auto value{0.0}; + if (extract_value(value, Key, Line, "") && value >= 0.0) + { + return value * Scale; + } + return std::nullopt; + }; + auto const flag = [&Line](std::string const &Key) -> std::optional { + auto value{false}; + if (extract_value(value, Key, Line, "")) + { + return value; + } + return std::nullopt; + }; + definition.peak = number("FcrushPeak", 1000.0); + definition.plateau = number("FcrushPlateau", 1000.0); + definition.onset = number("CrushOnset", 1.0); + definition.densify = number("CrushDensify", 1.0); + definition.hardening = number("CrushHardening", 1.0); + definition.limit = number("CrushLimit", 1.0); + definition.crash_zone = flag("CrashZone"); + definition.anticlimber = flag("AntiClimber"); + definition.buffer_height = number("BufferHeight", 1.0); + return definition; +} + } // namespace void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) @@ -11505,7 +11844,22 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); } + // the buffers of a category of EN 15551 in place of the springs given + auto const categoryname{extract_value("BufferCategory", line)}; + auto const category{categoryname.empty() ? std::nullopt : collision::buffer_category_of(categoryname.front())}; + auto const buffered{thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated}; + if (category && buffered) + { + auto const linear{collision::buffer_curve(*category, 0.0)}; + thiscoupler->SpringKB = linear.stiffness; + thiscoupler->DmaxB = linear.travel; + } thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); + if (category && buffered) + { + thiscoupler->physics.buffers = collision::buffer_curve(*category, thiscoupler->physics.buffers.progression); + } + thiscoupler->collision = collision_definition(line); if (Index == 0) { diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp new file mode 100644 index 000000000..c689c709f --- /dev/null +++ b/tests/unit/test_collisions.cpp @@ -0,0 +1,648 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "vehicle.h" +#include "McZapkie/collision.h" +#include "McZapkie/MOVER.h" +#include "utilities/Globals.h" + +#include +#include +#include +#include + +// collisions past the buffers with physics.derailment new (McZapkie/collision.h): the crush of the ends, the override, +// the push off the track, and what they do in trains of real vehicles + +using test::consist; +using test::definition; +using test::vehicle; +namespace cl = collision; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// the given setting of a global flag for the test, restored after it +class flag_setting { +public: + flag_setting(bool &Flag, bool Enabled) : m_flag{Flag}, m_previous{Flag} { m_flag = Enabled; } + ~flag_setting() { m_flag = m_previous; } + flag_setting(flag_setting const &) = delete; + flag_setting &operator=(flag_setting const &) = delete; + +private: + bool &m_flag; + bool m_previous; +}; + +// ---- the hit of two masses on the stop of their buffers, the way the vehicles take it + +struct pair_outcome { + double crush1{0.0}; + double crush2{0.0}; + double velocity1{0.0}; + double velocity2{0.0}; + double peak{0.0}; // force +}; + +// the first mass runs at the velocity into the second one standing, their buffers pressed all the way already; the +// springs carry the given force while pressed, stepped by Dt as the vehicles are: the springs over the step first, the +// hit after them +pair_outcome hit_pair(cl::end_state First, cl::end_state Second, double const Mass1, double const Mass2, double const Velocity, double const Springs, double const Dt) { + pair_outcome result; + auto velocity1{Velocity}; + auto velocity2{0.0}; + for (int step = 0; step < 1000000; ++step) { + velocity1 -= Springs * Dt / Mass1; + velocity2 += Springs * Dt / Mass2; + auto const closing{velocity1 - velocity2}; + if (closing <= 0.0) { + break; + } + cl::hit_input input; + input.velocity = closing; + input.mass1 = Mass1; + input.mass2 = Mass2; + input.restitution = 0.2; + input.stiffness = 1.4e8; + input.springs = Springs; + input.dt = Dt; + auto const hit{cl::hit(First, Second, input)}; + if (false == hit.crushing) { + // elastic: bounced apart with the restitution + auto const reduced{Mass1 * Mass2 / (Mass1 + Mass2)}; + auto const impulse{reduced * closing * (1.0 + input.restitution)}; + velocity1 -= impulse / Mass1; + velocity2 += impulse / Mass2; + break; + } + velocity1 -= hit.impulse / Mass1; + velocity2 += hit.impulse / Mass2; + First.crush += hit.crush1; + Second.crush += hit.crush2; + result.peak = std::max(result.peak, hit.force); + if (hit.velocity <= 0.0) { + break; + } + } + result.crush1 = First.crush; + result.crush2 = Second.crush; + result.velocity1 = velocity1; + result.velocity2 = velocity2; + return result; +} + +cl::crush_curve const wagon_curve{cl::default_crush(cl::vehicle_kind::wagon)}; +cl::crush_curve const locomotive_curve{cl::default_crush(cl::vehicle_kind::locomotive)}; + +// ---- trains of real vehicles + +bool derailed(TMoverParameters const &Vehicle) { + return TestFlag(Vehicle.DamageFlag, dtrain_out); +} + +double crush_of(TMoverParameters const &Vehicle) { + return std::max(Vehicle.Couplers[end::front].crush, Vehicle.Couplers[end::rear].crush); +} + +// a mixed freight train as the PoC has it: every third wagon from the given one an empty two-axle 3WL (10.5 t), the +// rest 430W coal wagons loaded full (80 t) +definition mixed_wagon(int const Index) { + return definition::fiz(Index % 3 == 1 ? "3wl_v2/3wl" : "430w_v2/430w"); +} + +vehicle &add_mixed(consist &Train, int const Index, int const Coupling, double const Velocity, double const Gap) { + auto &wagon{Train.add(mixed_wagon(Index), 0, Coupling, Velocity, Gap)}; + if (Index % 3 != 1) { + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + } + return wagon; +} + +struct crash_outcome { + int derailed{0}; + int overridden{0}; + int pushed{0}; + int crushed{0}; // ends crushed past the mark + int broken{0}; // couplings torn off + double crush{0.0}; // the deepest crush of an end + bool locomotive{false}; // it derailed + std::string list; // what happened to which vehicle, for the messages +}; + +// the PoC of G14: a locomotive (EU07, 80 t) with 12 mixed wagons running into the rear of 8 mixed wagons standing +// braked, in emergency, on a straight track or in a curve +crash_outcome freight_crash(double const Speed, double const Radius, double const Dt = 0.01) { + test::track track; + track.radius = Radius; + consist train; + // the standing train, the wagon it's hit at last; its brakes charged, then in emergency + constexpr int standing{8}; + for (int i = standing - 1; i >= 0; --i) { + add_mixed(train, i, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, track); + for (int i = 0; i < standing; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, track); + // the train running into it, its locomotive leading, a metre short of the hit + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, Speed, 1.0); + for (int i = 0; i < 12; ++i) { + add_mixed(train, i, consist::full_coupling, Speed, 0.0); + } + train.run(12.0, track, Dt); + + crash_outcome result; + for (std::size_t i = 0; i < train.size(); ++i) { + auto const &vehicle{train[i].mover()}; + auto const name{i < standing ? std::format("standing {}", standing - 1 - i) : i == standing ? std::string{"locomotive"} : std::format("running {}", i - standing - 1)}; + for (auto const end : {end::front, end::rear}) { + if (vehicle.Couplers[end].crush >= cl::crush_mark) { + ++result.crushed; + } + } + result.crush = std::max(result.crush, crush_of(vehicle)); + if (derailed(vehicle)) { + ++result.derailed; + result.overridden += vehicle.CollisionDerail == COLLISION_OVERRIDE; + result.pushed += vehicle.CollisionDerail == COLLISION_PUSHED_OFF; + result.locomotive = result.locomotive || i == standing; + result.list += std::format("{} ({:.1f} t) {}; ", name, vehicle.TotalMass / 1000.0, vehicle.CollisionDerail == COLLISION_OVERRIDE ? "overrode" : "pushed off"); + } + else if (crush_of(vehicle) >= cl::crush_mark) { + result.list += std::format("{} crushed {:.2f} m; ", name, crush_of(vehicle)); + } + } + for (std::size_t i = 0; i + 1 < train.size(); ++i) { + result.broken += train[i]->Couplers[end::rear].broken; + } + return result; +} + +// a locomotive running into a loaded coal wagon standing free, both on the rails: the crush of the pair after the hit +double locomotive_into_wagon(double const Speed, double const Dt) { + consist train; + auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + // behind the wagon, running forwards into its rear end + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, Speed, 0.5)}; + train.run(3.0, {}, Dt); + return wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush; +} + +} // namespace + +// ---- the crush curve + +TEST_CASE("collisions: the crush curve, a peak, a plateau, packing down, and the limit") { + auto const &curve{wagon_curve}; + CHECK(curve.force(0.0) == doctest::Approx(3.0e6)); + CHECK(curve.force(0.049) == doctest::Approx(3.0e6)); + CHECK(curve.force(0.05) == doctest::Approx(2.0e6)); + CHECK(curve.force(0.79) == doctest::Approx(2.0e6)); + // 2 / m past 0.8 m: a metre further it's three times the plateau + CHECK(curve.force(1.3) == doctest::Approx(2.0e6 * (1.0 + 2.0 * 0.5))); + CHECK_FALSE(std::isfinite(curve.force(1.5))); + // the energy is the area under it + CHECK(curve.energy(0.0, 0.05) == doctest::Approx(3.0e6 * 0.05)); + CHECK(curve.energy(0.0, 0.8) == doctest::Approx(3.0e6 * 0.05 + 2.0e6 * 0.75)); + CHECK(curve.energy(0.8, 1.3) == doctest::Approx(0.5 * (2.0e6 + 4.0e6) * 0.5)); + CHECK(curve.energy(0.0, 0.3) + curve.energy(0.3, 1.0) == doctest::Approx(curve.energy(0.0, 1.0))); + // past the limit there's nothing more to crush + CHECK(curve.energy(1.5, 3.0) == 0.0); + + // the kinds of vehicles; a crash zone gives a steady force with no peak + CHECK(locomotive_curve.peak > wagon_curve.peak); + auto const zone{cl::default_crush(cl::vehicle_kind::crash_zone)}; + CHECK(zone.force(0.0) == doctest::Approx(zone.force(0.5))); + // the keys of the .fiz override the defaults of the kind + cl::end_definition given; + given.plateau = 1.0e6; + given.crash_zone = true; + auto const own{cl::crush_of(given, cl::vehicle_kind::coach)}; + CHECK(own.plateau == doctest::Approx(1.0e6)); + CHECK(own.densify == doctest::Approx(zone.densify)); + CHECK(cl::anticlimber_of(given, cl::vehicle_kind::coach)); + CHECK_FALSE(cl::anticlimber_of({}, cl::vehicle_kind::locomotive)); +} + +TEST_CASE("collisions: the buffers of EN 15551, their stroke and energy") { + for (auto const category : {cl::buffer_category::A, cl::buffer_category::B, cl::buffer_category::C, cl::buffer_category::L, cl::buffer_category::passenger}) { + auto const rated{cl::rating(category)}; + for (auto const progression : {0.0, 0.5, 0.9}) { + auto const curve{cl::buffer_curve(category, progression)}; + CHECK(curve.travel == doctest::Approx(rated.stroke)); + // two buffers side by side + CHECK(curve.energy(curve.travel) == doctest::Approx(2.0 * rated.energy)); + } + } + CHECK(cl::rating(cl::buffer_category::A).energy < cl::rating(cl::buffer_category::C).energy); + CHECK(cl::buffer_category_of('C') == cl::buffer_category::C); + CHECK_FALSE(cl::buffer_category_of('X').has_value()); + // the triangle of category A: 2 x 30 kJ over 105 mm is about 1.1 MN at the end of the stroke, 570 kN a buffer + CHECK(cl::buffer_curve(cl::buffer_category::A, 0.0).end_force() == doctest::Approx(4.0 * 30.0e3 / 0.105)); +} + +// ---- the hit + +TEST_CASE("collisions: a hit the steel takes stays elastic, a harder one crushes the weaker end") { + cl::hit_input input; + input.mass1 = 80.0e3; + input.mass2 = 80.0e3; + input.stiffness = 1.4e8; + input.dt = 0.01; + // 40 t reduced: the steel takes 3 MN at 3 / sqrt(1.4e8 * 4e4) = 1.27 m/s + input.velocity = 1.0; + CHECK_FALSE(cl::hit({wagon_curve, 0.0}, {wagon_curve, 0.0}, input).crushing); + input.velocity = 5.0; + auto const hit{cl::hit({locomotive_curve, 0.0}, {wagon_curve, 0.0}, input)}; + REQUIRE(hit.crushing); + // the wagon gives, the locomotive doesn't; at its peak force for the whole step + CHECK(hit.crush1 == 0.0); + CHECK(hit.crush2 > 0.0); + CHECK(hit.force == doctest::Approx(3.0e6)); + CHECK(hit.impulse == doctest::Approx(3.0e6 * 0.01)); + CHECK(hit.duration == doctest::Approx(0.01)); + CHECK(hit.velocity == doctest::Approx(5.0 - 3.0e6 * 0.01 / 40.0e3)); + // with the springs carrying a part of the force, the hit adds the rest + input.springs = 1.0e6; + auto const sprung{cl::hit({locomotive_curve, 0.0}, {wagon_curve, 0.0}, input)}; + CHECK(sprung.impulse == doctest::Approx(2.0e6 * 0.01)); + // two alike crush alike + input.springs = 0.0; + auto const alike{cl::hit({wagon_curve, 0.0}, {wagon_curve, 0.0}, input)}; + CHECK(alike.crush1 == doctest::Approx(alike.crush2)); + // a wall: the end crushed all the way doesn't give, the other one does + auto const wall{cl::hit({wagon_curve, 2.0}, {wagon_curve, 0.0}, input)}; + CHECK(wall.crush1 == 0.0); + CHECK(wall.crush2 > 0.0); + // both crushed all the way: rigid, the legacy exchange + CHECK_FALSE(cl::hit({wagon_curve, 2.0}, {wagon_curve, 2.0}, input).crushing); +} + +TEST_CASE("collisions: the crush doesn't depend on the step, and it takes the energy of the hit") { + struct pair { + char const *name; + double mass1; + double mass2; + double velocity; + double springs; + }; + for (auto const &[name, mass1, mass2, velocity, springs] : { + pair{"80 t into 80 t at 25 km/h", 80.0e3, 80.0e3, 25.0 * kmh, 0.0}, + pair{"80 t into 80 t at 40 km/h, the springs at 1 MN", 80.0e3, 80.0e3, 40.0 * kmh, 1.0e6}, + pair{"80 t into 12 t at 40 km/h", 80.0e3, 12.0e3, 40.0 * kmh, 0.5e6}, + pair{"300 t into 80 t at 35 km/h, past the densification", 300.0e3, 80.0e3, 35.0 * kmh, 0.0}, + }) { + CAPTURE(name); + auto const fine{hit_pair({locomotive_curve, 0.0}, {wagon_curve, 0.0}, mass1, mass2, velocity, springs, 0.001)}; + REQUIRE(fine.crush2 > 0.05); + CHECK(fine.crush1 == 0.0); + for (auto const dt : {0.005, 0.01, 0.05}) { + CAPTURE(dt); + auto const coarse{hit_pair({locomotive_curve, 0.0}, {wagon_curve, 0.0}, mass1, mass2, velocity, springs, dt)}; + CHECK(coarse.crush2 == doctest::Approx(fine.crush2).epsilon(0.02)); + // the momentum stays with the pair + CHECK(mass1 * coarse.velocity1 + mass2 * coarse.velocity2 == doctest::Approx(mass1 * velocity)); + // never past the force the wagon gives at: its peak, or what it packed down to + CHECK(coarse.peak <= std::max(wagon_curve.peak, wagon_curve.force(coarse.crush2)) * (1.0 + 1e-9)); + } + if (springs == 0.0) { + // the energy of the relative motion goes into the crush, but for what the steel takes back + auto const reduced{mass1 * mass2 / (mass1 + mass2)}; + auto const kinetic{0.5 * reduced * velocity * velocity}; + auto const crushforce{wagon_curve.force(fine.crush2)}; + auto const elastic{crushforce * crushforce / (2.0 * 1.4e8)}; + CHECK(wagon_curve.energy(0.0, fine.crush2) == doctest::Approx(kinetic - elastic).epsilon(0.01)); + } + } +} + +TEST_CASE("collisions: the crush of two pairs of masses at the speeds of the table") { + // 80 t on 80 t: the steel takes the hit up to 1.3 m/s past the buffers; at 25 km/h the two ends alike crush by + // 0.4 m between them, the 0.97 MJ at 3 MN to 0.05 m each and at 2 MN past it (the buffers aren't here) + auto const slow{hit_pair({wagon_curve, 0.0}, {wagon_curve, 0.0}, 80.0e3, 80.0e3, 1.2, 0.0, 0.01)}; + CHECK(slow.crush1 + slow.crush2 == 0.0); + auto const hard{hit_pair({wagon_curve, 0.0}, {wagon_curve, 0.0}, 80.0e3, 80.0e3, 25.0 * kmh, 0.0, 0.01)}; + CHECK(hard.crush1 + hard.crush2 > 0.2); + CHECK(hard.crush1 + hard.crush2 < 0.5); +} + +// ---- override + +TEST_CASE("collisions: the lighter or the higher vehicle climbs onto the other one, both past a deeper crush") { + cl::override_input input; + input.mass1 = 80.0e3; + input.mass2 = 80.0e3; + input.height1 = 1.040; + input.height2 = 1.040; + SUBCASE("a shallow crush holds") { + input.crush1 = 0.3; + auto const result{cl::override_of(input)}; + CHECK_FALSE(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("alike: past 0.35 m they hold, past 0.6 m both climb") { + input.crush1 = 0.4; + CHECK_FALSE(cl::override_of(input).first); + input.crush2 = 0.25; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK(result.second); + } + SUBCASE("the lighter one climbs past 0.35 m") { + input.mass1 = 12.0e3; + input.crush1 = 0.4; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("40 mm higher, the higher one climbs") { + input.height2 = 1.000; + input.crush1 = 0.2; + input.crush2 = 0.2; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("interlocked anticlimbers hold them until the crush zone of an end is used up") { + input.anticlimbers = true; + input.zone1 = 0.8; + input.zone2 = 0.8; + input.height2 = 1.000; + input.mass1 = 40.0e3; + input.crush1 = 0.5; + input.crush2 = 0.5; + auto const held{cl::override_of(input)}; + CHECK_FALSE(held.first); + CHECK_FALSE(held.second); + input.crush1 = 0.85; + auto const spent{cl::override_of(input)}; + CHECK(spent.first); + CHECK(spent.second); + } +} + +// ---- pushed off the track + +TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of 150 m is pushed off past the safe push of EN 15566") { + // the vehicles of data/fiz: the 3WL empty (10.5 t, two axles 6 m apart), between 430W coal wagons + vehicle empty{definition::fiz("3wl_v2/3wl")}; + vehicle loaded{definition::fiz("430w_v2/430w")}; + cl::pushed_vehicle wagon; + wagon.mass = empty->TotalMass - empty->Mred; + wagon.axles = empty->NAxles; + wagon.length = empty->Dim.L; + wagon.pivots = empty->BDist; + wagon.axle_base = empty->ADist > 0.0 ? empty->ADist : empty->BDist; + REQUIRE(wagon.axles == 2); + cl::pushed_end end; + end.other_length = loaded->Dim.L; + auto const ratio = [&](double const Force, double const Radius) { + end.force = Force; + return cl::pushed_ratio(wagon, end, Radius); + }; + // 250 kN on the pair of buffers in a curve of 150 m is safe (EN 15566, 4.2); 600 kN pushes it off + CHECK(ratio(250.0e3, 150.0) < 1.2); + CHECK(ratio(250.0e3, 150.0) > 0.5); + CHECK(ratio(600.0e3, 150.0) > 1.2); + // the wider the curve the more it takes; on a straight track the empty wagon lifts off past 1.5 MN: the force + // pitching it takes the load off its leading wheels + CHECK(ratio(600.0e3, 500.0) < ratio(600.0e3, 150.0)); + CHECK(ratio(600.0e3, 0.0) < 1.2); + CHECK(ratio(1.5e6, 0.0) < 1.2); + CHECK(ratio(2.5e6, 0.0) > 1.2); + // a crushed end no longer holds the ends in line + end.crush = 0.5; + CHECK(ratio(1.5e6, 0.0) > 1.2); + end.crush = 0.0; + + // the loaded wagon, four axles, takes it + cl::pushed_vehicle heavy; + heavy.mass = loaded->TotalMass - loaded->Mred + 59.5e3; + heavy.axles = loaded->NAxles; + heavy.length = loaded->Dim.L; + heavy.pivots = loaded->BDist; + heavy.axle_base = loaded->ADist; + end.force = 600.0e3; + CHECK(cl::pushed_ratio(heavy, end, 150.0) < 0.5); + + // it has to hold for 0.05 s, however long the steps + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.03)); + CHECK_FALSE(monitor.update(false, 0.01)); + CHECK_FALSE(monitor.update(true, 0.03)); + CHECK(monitor.update(true, 0.03)); +} + +// ---- the model of eu07.ini + +TEST_CASE("collisions: the legacy rule with physics.derailment old, the crush with new") { + flag_setting const crashdamage{Global.crash_damage, true}; + struct collision { + char const *name; + char const *front; + char const *back; + double speed; // of the back one, running into the front one standing + bool frontout_old; + bool backout_old; + bool frontout_new; + bool backout_new; + }; + // the legacy rule: over 15 km/h weighed by the ratio of the masses. the crush: the light wagon is crushed deep and + // climbs onto the locomotive at 60 km/h; two locomotives at 25 km/h crush their ends 0.1-0.3 m and stay on the rails + for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new] : { + collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false}, + collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false}, + collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true}, + }) { + CAPTURE(name); + for (auto const model : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + auto const physical{model == global_settings::derailment_model::physical}; + CAPTURE(physical); + model_setting const setting{model}; + consist train; + train.add(definition::fiz(front)); + train.add(definition::fiz(back), 0, coupling::faux, speed, 20.0); + train.run(10.0); + CHECK(derailed(train[0].mover()) == (physical ? frontout_new : frontout_old)); + CHECK(derailed(train[1].mover()) == (physical ? backout_new : backout_old)); + auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + if (physical) { + MESSAGE(name, ": crush ", crush, " m"); + CHECK(crush > 0.05); + } + else { + CHECK(crush == 0.0); + } + } + } +} + +TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend on the step, nor on the model of the coupling") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + auto const fine{locomotive_into_wagon(30.0, 0.001)}; + auto const game{locomotive_into_wagon(30.0, 0.01)}; + auto const coarse{locomotive_into_wagon(30.0, 0.05)}; + MESSAGE(std::format("30 km/h, couplerphysics {}: crush {:.3f} / {:.3f} / {:.3f} m with dt 0.001 / 0.01 / 0.05 s", physics, fine, game, coarse)); + REQUIRE(fine > 0.05); + // the step of the game, and a step five times as long, which the buffers past the crush aren't made for + CHECK(game == doctest::Approx(fine).epsilon(0.1)); + CHECK(coarse == doctest::Approx(fine).epsilon(0.5)); + } + // the models of the coupling differ in their buffers, not past them + { + auto const legacy{locomotive_into_wagon(30.0, 0.01)}; + flag_setting const couplerphysics{Global.coupler_physics, true}; + flag_setting const everywhere{Global.coupler_physics_all, true}; + CHECK(locomotive_into_wagon(30.0, 0.01) == doctest::Approx(legacy).epsilon(0.3)); + } + // slow enough, the buffers take it all + CHECK(locomotive_into_wagon(5.0, 0.01) == 0.0); +} + +TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends crush; torn off, they don't couple again") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; + for (auto const speed : {20.0, 30.0, 45.0}) { + CAPTURE(speed); + vehicle moving{automatic, speed, "moving"}; + vehicle standing{automatic, 0.0, "standing"}; + test::pair pair{moving, end::front, standing, end::rear, 1.0}; + auto coupled{false}; + auto fast{false}; // coupled while closing in faster than the couplers catch + for (int i = 0; i < 1000; ++i) { + auto const closing{moving->CollisionVelocity(end::front, standing.mover(), end::rear)}; + pair.step(); + fast = fast || (pair.coupled() && false == coupled && closing > TMoverParameters::SafeCollisionVelocity); + coupled = coupled || pair.coupled(); + } + auto const crush{moving->Couplers[end::front].crush + standing->Couplers[end::rear].crush}; + MESSAGE(speed, " km/h: crush ", crush, " m, derailed ", derailed(moving.mover()), " ", derailed(standing.mover()), ", coupled later ", coupled); + CHECK_FALSE(fast); + CHECK(crush > 0.0); + // crushed past the draw gear, the coupler is gone; short of it, the wagons may roll together again slowly + // after the hit, and couple then + if (std::max(moving->Couplers[end::front].crush, standing->Couplers[end::rear].crush) >= cl::draw_gear_crush) { + CHECK_FALSE(coupled); + CHECK((moving->Couplers[end::front].broken || standing->Couplers[end::rear].broken)); + } + // the two alike: neither climbs onto the other until the crush is deep enough for both to + CHECK(derailed(moving.mover()) == derailed(standing.mover())); + CHECK(derailed(moving.mover()) == (crush > cl::override_both)); + } +} + +TEST_CASE("collisions: a vehicle off the rails by the new model stays in the chain of forces") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + consist train; + auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 10.0, 0.5)}; + wagon->derail_in_collision(COLLISION_PUSHED_OFF, "for the test"); + REQUIRE(derailed(wagon.mover())); + auto const before{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; + // the hit is over within a second, the friction of the derailed wagon slows the pair down over it + train.run(1.0); + auto const after{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; + // pushed along, not a wall the locomotive bounces off + CHECK(wagon.speed() > 1.0); + CHECK(locomotive.speed() > 0.0); + CHECK(after < before); + CHECK(after > 0.5 * before); + // and it slides on with the friction of the ballast, stopping before long + train.run(10.0); + CHECK(std::abs(wagon.speed()) < 0.1); +} + +TEST_CASE("collisions: a freight train running into a standing one, the cases of the PoC of G14") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + struct crash { + double speed; + double radius; + }; + for (auto const &[speed, radius] : {crash{10.0, 0.0}, crash{15.0, 0.0}, crash{15.0, 190.0}, crash{25.0, 0.0}, crash{25.0, 190.0}, crash{40.0, 0.0}, crash{40.0, 190.0}}) { + CAPTURE(speed); + CAPTURE(radius); + auto const result{freight_crash(speed, radius)}; + MESSAGE(std::format("{:.0f} km/h, R {:.0f}: {} derailed ({} overrode, {} pushed off), {} ends crushed (deepest {:.2f} m), {} couplings broken: {}", speed, radius, result.derailed, + result.overridden, result.pushed, result.crushed, result.crush, result.broken, result.list)); + if (speed <= 10.0) { + // the buffers take it + CHECK(result.derailed == 0); + CHECK(result.crushed == 0); + } + } +} + +TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + // two coaches of data/wagon.json (42.2 t) a unit, their ends crash zones with anticlimbers, unbraked + auto const unit = [](bool const Anticlimbers, double const Height) { + return definition::load("wagon").set("BuffCoupl", "CrashZone", "Yes").set("BuffCoupl", "AntiClimber", Anticlimbers ? "Yes" : "No").set("BuffCoupl", "BufferHeight", Height); + }; + auto const crash = [&](bool const Anticlimbers, double const Speed, double const Offset) { + consist train; + train.add(unit(Anticlimbers, 1.040)); + train.add(unit(Anticlimbers, 1.040)); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, coupling::faux, Speed, 1.0); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, consist::full_coupling, Speed); + train.run(6.0); + struct { + double crush; + double inner; + int derailed; + bool higher; + } result{train[1]->Couplers[end::rear].crush + train[2]->Couplers[end::front].crush, std::max(crush_of(train[0].mover()), crush_of(train[3].mover())), 0, + derailed(train[2].mover())}; + for (std::size_t i = 0; i < train.size(); ++i) { + result.derailed += derailed(train[i].mover()); + } + return result; + }; + SUBCASE("scenario 1: the crush stays in the zones, nothing climbs") { + auto const result{crash(true, 36.0, 0.04)}; + MESSAGE("36 km/h, 40 mm offset: crush ", result.crush, " m, the far ends ", result.inner, " m"); + CHECK(result.crush > 0.2); + CHECK(result.crush < 2.0 * 0.8); + CHECK(result.derailed == 0); + } + SUBCASE("the same units without the anticlimbers override") { + auto const result{crash(false, 36.0, 0.0)}; + CHECK(result.derailed >= 2); + } + SUBCASE("slower, without the anticlimbers, the higher one climbs") { + auto const result{crash(false, 32.0, 0.04)}; + MESSAGE("32 km/h, 40 mm offset: crush ", result.crush, " m"); + CHECK(result.crush > cl::override_crush); + CHECK(result.crush < cl::override_both); + CHECK(result.higher); + CHECK(result.derailed == 1); + auto const held{crash(true, 32.0, 0.04)}; + CHECK(held.derailed == 0); + } +} diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 4e5255ff4..f42ecd731 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -4,6 +4,7 @@ #include "drive.h" #include "McZapkie/hamulce.h" +#include "utilities/Globals.h" #include "utilities/utilities.h" // characterisation of the controls a driver and a crew use besides driving and braking: doors, direction and @@ -495,6 +496,14 @@ TEST_CASE("controls: a freight wagon loaded and braked") { } TEST_CASE("controls: a locomotive running into a standing wagon") { + // the legacy collisions of physics.derailment old: derailed, the wagon is a wall (test_collisions.cpp has the new) + struct legacy { + global_settings::derailment_model previous{Global.derailment}; + legacy() { Global.derailment = global_settings::derailment_model::old; } + ~legacy() { Global.derailment = previous; } + legacy(legacy const &) = delete; + legacy &operator=(legacy const &) = delete; + } const model; for (auto const speed : {5.0, 15.0, 40.0}) { CAPTURE(speed); scenario scenario{std::format("controls/collision/{} kmh", static_cast(speed)), motion()}; diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index bbb1c0dd9..c6a3f4a5d 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -49,6 +49,19 @@ private: bool m_previous{Global.crash_damage}; }; +// the legacy collisions of physics.derailment old for the test, restored after it: the rule of the safe closing speed +// weighed by the ratio of the masses (the crush of the ends of the new model is in test_collisions.cpp) +class legacy_collisions { +public: + legacy_collisions() { Global.derailment = global_settings::derailment_model::old; } + ~legacy_collisions() { Global.derailment = m_previous; } + legacy_collisions(legacy_collisions const &) = delete; + legacy_collisions &operator=(legacy_collisions const &) = delete; + +private: + global_settings::derailment_model m_previous{Global.derailment}; +}; + } // namespace // issue #86: automatic couplers used to catch at any closing speed, so the vehicles never collided nor derailed @@ -202,6 +215,7 @@ TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it" TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor once the hit has slowed it down") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; test::pair pair{moving, end::front, standing, end::rear, 1.0}; @@ -268,6 +282,7 @@ TEST_CASE("couplers: the automatic coupling locked by a hit is unlocked once the TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicles apart, uncoupled and on the rails") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; auto moving{automatic_wagon(20.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; test::pair pair{moving, end::front, standing, end::rear, 1.0}; @@ -281,6 +296,7 @@ TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicl TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over the limit adjusted for their mass ratio") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; SUBCASE("equal masses: both derail") { auto moving{automatic_wagon(30.0, "moving")}; @@ -318,6 +334,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t TEST_CASE("couplers: wagons running head-on into each other couple only up to the safe closing speed") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; SUBCASE("7 + 7 km/h, the couplers catch") { auto first{automatic_wagon(7.0, "first")}; diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index 926964dbe..e17a8f86d 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -3,6 +3,7 @@ #include "consist.h" #include "scenario.h" +#include "utilities/Globals.h" #include "utilities/utilities.h" // characterisation of the couplers between vehicles: coupling and uncoupling by hand (Attach, DettachStatus, @@ -14,6 +15,22 @@ using test::definition; using test::scenario; using namespace test::channels; +namespace { + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +} // namespace + TEST_CASE("couplers: coupled by hand, touching or apart, of the same kind or not") { consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; @@ -147,7 +164,9 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { TEST_CASE("couplers: collisions fast enough to derail") { // a locomotive running into a standing wagon from behind, and a wagon running backwards into a standing - // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail + // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail. the legacy rule of + // physics.derailment old: the new model crushes the ends (test_collisions.cpp) + model_setting const legacy{global_settings::derailment_model::old}; struct collision { char const *name; char const *frontpath; From b182e560e18a05dccffc32d02a025890153b6af9 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 13:04:55 +0100 Subject: [PATCH 20/59] test(scenarios): a curve of td.scn buckles with an event ahead of the timetable train eu07_td_buckle_event: 30 mm out of the curve tdo_n222 at 10:35, laid again during the game; the EU07 keeps on the rails and stops at Przystanek. eu07_td_buckle_derails: 600 mm over a main lobe of 8 m; the EU07 runs into it at 46 km/h and overturns, the log says it derailed on buckled track. --- .../cases/eu07_td_buckle_derails.json | 19 +++++++++++++++++++ .../scenarios/cases/eu07_td_buckle_event.json | 19 +++++++++++++++++++ tests/scenarios/cases/td_buckle_event.scn | 11 +++++++++++ 3 files changed, 49 insertions(+) create mode 100644 tests/scenarios/cases/eu07_td_buckle_derails.json create mode 100644 tests/scenarios/cases/eu07_td_buckle_event.json create mode 100644 tests/scenarios/cases/td_buckle_event.scn diff --git a/tests/scenarios/cases/eu07_td_buckle_derails.json b/tests/scenarios/cases/eu07_td_buckle_derails.json new file mode 100644 index 000000000..5caaa60b6 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_derails.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event: 600 mm out of the curve over a main lobe of 8 m (an equivalent radius of 9 m, about 30 m for the body on axles 11 m apart). The AI doesn't see it and runs into it at the 46 km/h it has there: the locomotive leaves the rails on the buckle and stops short of Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "600 8" + }, + "ini": ["gfxrenderer null"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Track \"tdo_n222\" buckled \\(event autotest_buckle\\): 600 mm to the (left|right) at [0-9.]+ m, main lobe 8.0 m" }, + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ derailed on buckled track" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "distance", "max": 1100 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_buckle_event.json b/tests/scenarios/cases/eu07_td_buckle_event.json new file mode 100644 index 000000000..192fa9b5a --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_event.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles with a trackbuckle event (30 mm out of the curve, as the heat does: an equivalent radius of 330 m, too little to derail it). The track is laid again during the game and the train keeps on it to Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "30" + }, + "ini": ["gfxrenderer null"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Track \"tdo_n222\" buckled \\(event autotest_buckle\\): 30 mm to the (left|right)" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }, + { "type": "log_lacks", "pattern": "Bad driving" } + ] +} diff --git a/tests/scenarios/cases/td_buckle_event.scn b/tests/scenarios/cases/td_buckle_event.scn new file mode 100644 index 000000000..b9d47d434 --- /dev/null +++ b/tests/scenarios/cases/td_buckle_event.scn @@ -0,0 +1,11 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: +// td_timetable.scn (the timetable train from track 1 of Stacja1 to Przystanek), and at 10:35, as the train leaves, +// the curve tdo_n222 (R 600 m, about 950 m ahead of it) buckles in the heat out of the curve with the +// trackbuckle event of {{amplitude}} mm (see world/TrackBuckle.h) +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end +event autotest_buckle trackbuckle 0 tdo_n222 {{amplitude}} endevent +node -1 0 autotest_buckle_launcher eventlauncher 0 0 0 -1 none 1035 autotest_buckle end From a69589f2d39889a268303a66fa95605110dc0c08 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 13:12:48 +0100 Subject: [PATCH 21/59] test(scenarios): an EN57-2000 hitting a standing one at 20 km/h crushes the cab ends and stays on the rails With physics.derailment new: too fast for the automatic couplers, past the buffers the ends crush, too little for either unit to climb onto the other. The case of #86 at 50 km/h keeps passing: there the rear car of the standing unit overrides. --- tests/scenarios/cases/en57_2000_crush_new.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 tests/scenarios/cases/en57_2000_crush_new.json diff --git a/tests/scenarios/cases/en57_2000_crush_new.json b/tests/scenarios/cases/en57_2000_crush_new.json new file mode 100644 index 000000000..e13c2299d --- /dev/null +++ b/tests/scenarios/cases/en57_2000_crush_new.json @@ -0,0 +1,17 @@ +{ + "description": "G14 stage 2: an EN57-2000 unit without a driver runs at 20 km/h into a standing one on td.scn, with physics.derailment new. Too fast for the automatic couplers to catch: past the buffers the cab ends crush, a few decimetres, too little for either unit to climb onto the other, so both stay on the rails; the run ends on the 60 s test timeout.", + "base_scenery": "td.scn", + "ini": ["crashdamage yes", "physics.derailment new"], + "fragment": "td_automatic_coupler_hit.scn", + "vars": { + "velocity": "20", + "offset": "0" + }, + "expect": "timeout", + "duration": 60, + "timeout": 300, + "checks": [ + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ and autotest_\\S+ collided at \\d+ km/h, the \\w+ end of autotest_\\S+ crushed" }, + { "type": "log_lacks", "pattern": "Bad driving: autotest_\\S+ derailed" } + ] +} From 65fa4a1cc60078825fdb91110bba38fe5926ed0b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 13:32:08 +0100 Subject: [PATCH 22/59] fix(physics): the traffic of the roads keeps the legacy collisions; the log of a crush tells what it went by Found running line 107 with every train driven by the AI: two cars of its traffic (Fiat 126p, Skoda 1100) met head-on at 119 km/h. With physics.derailment new they bounced off each other elastically: their couplers have no steel to speak of, so the steel took the hit and the legacy rule of 15 km/h was off. The crush of the ends is for rail vehicles now; road vehicles keep the legacy rule and derail as before. The log of a crushed end, of an override and of a push off the track tells the masses and the kinds of the vehicles, the crush and the force each end gives at, the force of the hit and of the springs, the closing velocity and the force, time and Y/Q of a push. --- McZapkie/Mover.cpp | 42 +++++++++++++++++++++++++++++----- tests/unit/test_collisions.cpp | 17 ++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 00a4b775c..b946d4aca 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1338,8 +1338,9 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; - // physics.derailment new: past the buffers the ends crush (collision.h); a hit the steel takes stays the legacy one - auto const crushing{Global.derailment == global_settings::derailment_model::physical}; + // physics.derailment new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays + // the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule + auto const crushing{Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) { return; @@ -1532,6 +1533,22 @@ char const *end_name(int const End) return End == end::front ? "front" : "rear"; } +char const *kind_name(collision::vehicle_kind const Kind) +{ + switch (Kind) + { + case collision::vehicle_kind::locomotive: + return "locomotive"; + case collision::vehicle_kind::coach: + return "coach"; + case collision::vehicle_kind::crash_zone: + return "crash zone"; + case collision::vehicle_kind::wagon: + default: + return "wagon"; + } +} + // the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls double compression_at(TCoupling const &Coupler, int const End) { @@ -1627,10 +1644,18 @@ bool TMoverParameters::crush_hit(int const End, double const dt) record_hit(thiscoupler, hit.force, hit.duration); record_hit(othercoupler, hit.force, hit.duration); + // what the log tells of the pair, for the analysis of a crush + auto const pair = [&]() { + return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, " + "closing at {:.1f} km/h at the start of the step", + Name, TotalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name, + othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush, + secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6); + }; auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { if (Before < collision::crush_mark && After >= collision::crush_mark) { - ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name)); + ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name, pair())); } }; auto const before{thiscoupler.crush}; @@ -1676,7 +1701,8 @@ bool TMoverParameters::crush_hit(int const End, double const dt) climbing.zone2 = secondcurve.densify; auto const climbed{collision::override_of(climbing)}; auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { - return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m", Climber.Name, Other.Name, closing * 3.6, thiscoupler.crush + othercoupler.crush); + return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, + thiscoupler.crush + othercoupler.crush, climbing.height1 * 1000.0, climbing.height2 * 1000.0, climbing.anticlimbers ? "yes" : "no", pair()); }; if (climbed.first) { @@ -1741,8 +1767,12 @@ void TMoverParameters::check_pushed_off(double const dt) } if (pushed_off_monitor.update(holds, duration)) { - derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f}", worstforce / 1000.0, end_name(worstend), Vel, - std::abs(RunningShape.R), std::min(worst, 99.0))); + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in for {:.3f} s, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " + "springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)", + worstforce / 1000.0, end_name(worstend), pushed_off_monitor.time(), Vel, std::abs(RunningShape.R), std::min(worst, 99.0), + vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0, + compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, + Couplers[end::front].crush, Couplers[end::rear].crush)); } } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index c689c709f..f4af0151c 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -555,6 +555,23 @@ TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends cru } } +TEST_CASE("collisions: road vehicles keep the legacy rule") { + // the traffic of a scenery: cars and buses have no underframe to crush; over 15 km/h weighed by the masses they + // derail, as with physics.derailment old (found running line 107: two cars of its traffic, 119 km/h head-on) + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const model : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + model_setting const setting{model}; + consist road; + road.add(definition::fiz("road/man/nl293")); + road.add(definition::fiz("road/man/nl293"), 0, coupling::faux, 40.0, 5.0); + road.run(5.0); + CHECK(derailed(road[0].mover())); + CHECK(derailed(road[1].mover())); + CHECK(road[0]->Couplers[end::rear].crush == 0.0); + CHECK(road[1]->CollisionDerail == NONE); + } +} + TEST_CASE("collisions: a vehicle off the rails by the new model stays in the chain of forces") { model_setting const physical{global_settings::derailment_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; From 6111773f5368f95be9a12984155367cdbd43e6ab Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 18:57:04 +0100 Subject: [PATCH 23/59] test(physics): count the steps of the derailment tests in integers, read the distances checked SonarCloud: a float loop counter (S2193) and the optional read after REQUIRE taken for a garbage value (S836). --- tests/unit/test_derailment.cpp | 2 +- tests/unit/test_derailment_vehicle.cpp | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 4fa314fcd..201c2e3bc 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -143,7 +143,7 @@ TEST_CASE("derailment: the decision and the place don't depend on the step") { auto const coarse{run(1.05 * critical, 0.5)}; REQUIRE(fine.has_value()); REQUIRE(coarse.has_value()); - CHECK(std::abs(*coarse - *fine) <= 1.05 * critical * 0.5); + CHECK(std::abs(coarse.value() - fine.value()) <= 1.05 * critical * 0.5); } TEST_CASE("derailment: a peak shorter than the window doesn't derail") { diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 23e395fdc..690284ba2 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -5,6 +5,8 @@ #include "McZapkie/MOVER.h" #include "utilities/Globals.h" +#include + // a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of McZapkie/derailment.h checked by // TMoverParameters::check_derailment(), and what the vehicle comes to off the rails @@ -82,13 +84,14 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { SUBCASE("the same with steps of 0.01 and 0.05 s") { for (auto const dt : {0.01, 0.05}) { CAPTURE(dt); + auto const steps{static_cast(std::lround(1.0 / dt))}; vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; - for (auto time = 0.0; time < 1.0; time += dt) { + for (auto step = 0; step < steps; ++step) { eu07vehicle.step(curve, dt); } CHECK(eu07vehicle->Derailed == dr::outcome::overturned); vehicle slower{definition::fiz("4e_v1/4e"), critical - 2.0}; - for (auto time = 0.0; time < 1.0; time += dt) { + for (auto step = 0; step < steps; ++step) { slower.step(curve, dt); } CHECK(slower->Derailed == dr::outcome::none); From f2d9926e6689972abc33e190f8fe9e58f6b0ac98 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 18:57:08 +0100 Subject: [PATCH 24/59] test(track): count the steps along a buckle in integers SonarCloud S2193: no float loop counters. --- tests/unit/test_track_buckle.cpp | 7 ++++--- tests/unit/test_track_buckle_derailment.cpp | 6 +++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_track_buckle.cpp b/tests/unit/test_track_buckle.cpp index df26c74ab..589ed125d 100644 --- a/tests/unit/test_track_buckle.cpp +++ b/tests/unit/test_track_buckle.cpp @@ -180,8 +180,9 @@ TEST_CASE("the buckle has its amplitude in the middle, side lobes the other way CHECK(track_buckle::bend(shape, 60.0) == doctest::Approx(-peak)); // none larger anywhere, and the curvature with no jumps auto previous{track_buckle::bend(shape, 35.0)}; - for (auto at = 35.0; at <= 85.0; at += 0.01) + for (auto step = 0; step <= 5000; ++step) { + auto const at{35.0 + 0.01 * step}; auto const bend{track_buckle::bend(shape, at)}; CHECK(std::abs(bend) <= peak * 1.0001); CHECK(std::abs(bend - previous) < 0.01 * peak); @@ -230,8 +231,8 @@ TEST_CASE("a bogie feels the curvature of the buckle averaged over its wheelbase CHECK(std::abs(across) < 0.5 * peak); // the most the body feels, at any place, is less than a bogie does auto most{0.0}; - for (auto at = 20.0; at <= 80.0; at += 0.05) - most = std::max(most, std::abs(track_buckle::body_bend(shape, at, 17.0, 2.5))); + for (auto step = 0; step <= 1200; ++step) + most = std::max(most, std::abs(track_buckle::body_bend(shape, 20.0 + 0.05 * step, 17.0, 2.5))); CHECK(most < 0.95 * peak); CHECK(most > 0.3 * peak); } diff --git a/tests/unit/test_track_buckle_derailment.cpp b/tests/unit/test_track_buckle_derailment.cpp index 1b72db4cc..2f5d99592 100644 --- a/tests/unit/test_track_buckle_derailment.cpp +++ b/tests/unit/test_track_buckle_derailment.cpp @@ -51,8 +51,12 @@ derailment::outcome ride(track_buckle::shape const &Shape, double const Radius, derailment::monitor monitor; auto const velocity{Speed / 3.6}; auto const reach{track_buckle::reach(Shape) + Stock.pivots}; - for (auto at = Shape.centre - reach - 5.0; at <= Shape.centre + reach + 5.0; at += velocity * Step) + auto const start{Shape.centre - reach - 5.0}; + auto const advance{velocity * Step}; + auto const steps{static_cast(std::floor((2.0 * (reach + 5.0)) / advance))}; + for (auto step = 0; step <= steps; ++step) { + auto const at{start + step * advance}; derailment::track_state track; track.radius = Radius; auto const bend{track_buckle::body_bend(Shape, at, Stock.pivots, Stock.base)}; From 8070f79a3a7a1a175e7c1eb63183a41c1097a0e6 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 20:09:57 +0100 Subject: [PATCH 25/59] feat(physics): physics.collisions new|old|monitor, apart from the model of the derailment The crush of the ends, the override and the push off the track went by physics.derailment new. They have a switch of their own now, physics.collisions, new by default: the derailment in a curve and the collisions can each be new or the legacy ones. old is exactly the legacy rule of the safe closing speed weighed by the masses. monitor runs as old, and for a hit on the buffers the crush model would not take elastically it logs once what the crush of the whole hit would be (collision monitor: the closing speed, the crush of each end, the force, whether the draw gear tears off and which vehicle would ride up onto the other one), without changing anything. The push off the track is not monitored: it builds up from the crushed ends of the new model. The road vehicles keep the legacy rule with any value. The tests that pin the legacy collisions pin physics.collisions old. --- McZapkie/MOVER.h | 21 +++-- McZapkie/Mover.cpp | 80 ++++++++++++++----- McZapkie/collision.h | 2 +- .../scenarios/cases/en57_2000_crush_new.json | 4 +- tests/unit/test_collisions.cpp | 79 +++++++++++++----- tests/unit/test_controls.cpp | 8 +- tests/unit/test_couplers.cpp | 8 +- tests/unit/test_couplers_trains.cpp | 12 +-- utilities/Globals.cpp | 11 +++ utilities/Globals.h | 21 +++++ 10 files changed, 180 insertions(+), 66 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 8c612cca0..7e708d5c8 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -177,9 +177,9 @@ enum DerailReason COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem /// Trailing through a switch with a movable nose set the other way. TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem - /// Climbed onto the vehicle it hit, its end crushed (physics.derailment new). + /// Climbed onto the vehicle it hit, its end crushed (physics.collisions new). COLLISION_OVERRIDE = 7, // najechanie - /// Pushed off the track by the force pressing its end (physics.derailment new). + /// Pushed off the track by the force pressing its end (physics.collisions new). COLLISION_PUSHED_OFF = 8, // wyciśnięcie z toru }; @@ -1293,7 +1293,7 @@ struct TCoupling // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end coupler_physics::end_parameters physics; coupler_physics::pair_state physics_state; - // the collisions past the buffers (physics.derailment new), see collision.h: the optional keys of this end, the depth + // the collisions past the buffers (physics.collisions new), see collision.h: the optional keys of this end, the depth // it's crushed to for good [m], and the hit of the pair in the step: whether either vehicle handled it already, its // peak force [N] and how long that acted [s] collision::end_definition collision; @@ -1302,6 +1302,8 @@ struct TCoupling bool hit_handled{false}; double hit_force{0.0}; double hit_duration{0.0}; + // physics.collisions monitor: the log told of the crush of this hit of the pair already + bool crush_monitored{false}; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ @@ -2458,19 +2460,22 @@ class TMoverParameters // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other // derailment, which stops it as the legacy model does derailment::outcome Derailed{derailment::outcome::none}; - // physics.derailment new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the + // 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; collision::crush_curve crush_curve_at(int End) const; double buffer_height_at(int End) const; collision::pushed_monitor pushed_off_monitor; - // how the vehicle left the rails in a collision (physics.derailment new): overriding or pushed off, NONE otherwise + // how the vehicle left the rails in a collision (physics.collisions new): overriding or pushed off, NONE otherwise DerailReason CollisionDerail{NONE}; - // physics.derailment new: the hit of the end on the stop of its buffers, harder than the steel takes, crushes the + // physics.collisions monitor: how many crushes the log told of, of the hits of this vehicle on the others + int crush_reports{0}; + // physics.collisions new: the hit of the end on the stop of its buffers, harder than the steel takes, crushes the // weaker end and may let one vehicle climb onto the other one, see collision.h. returns: whether it did, and the - // velocities took the hit; the legacy collision takes the rest + // velocities took the hit; the legacy collision takes the rest. physics.collisions monitor: the log tells what the + // crush of the whole hit would be, once for a hit, nothing changes, and it returns false bool crush_hit(int End, double dt); - // the force pressing the ends pushes the vehicle off the track (physics.derailment new) + // the force pressing the ends pushes the vehicle off the track (physics.collisions new) void check_pushed_off(double dt); // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of // derailment.h have it diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index b946d4aca..f33bbb8ed 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1338,13 +1338,19 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; - // physics.derailment new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays + // physics.collisions new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays // the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule - auto const crushing{Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; + auto const rails{TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; + auto const crushing{Global.collisions == global_settings::collision_model::physical && rails}; if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) { return; } + // physics.collisions monitor: the legacy collision follows, the log tells what the crush would be + if (Global.collisions == global_settings::collision_model::monitor && rails) + { + crush_hit(End, dt); + } if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) { return; @@ -1476,7 +1482,7 @@ void TMoverParameters::damage_coupler(int const End) } // ************************************************************************************************* -// physics.derailment new: the collisions past the buffers, see collision.h +// physics.collisions new: the collisions past the buffers, see collision.h // ************************************************************************************************* collision::vehicle_kind TMoverParameters::collision_kind() const { @@ -1585,8 +1591,12 @@ bool TMoverParameters::crush_hit(int const End, double const dt) auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; if (false == Global.crash_damage || false == buffers || closing <= 0.0) { + // the hit is over, the next one is another one for the monitor + thiscoupler.crush_monitored = false; + othercoupler.crush_monitored = false; return false; } + auto const monitor{Global.collisions == global_settings::collision_model::monitor}; // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it auto const wall{TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; auto const otherwall{TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; @@ -1610,9 +1620,46 @@ bool TMoverParameters::crush_hit(int const End, double const dt) input.restitution = std::sqrt(std::max(0.0, 1.0 - loss)); input.stiffness = stiffness; input.springs = springs; - input.dt = dt; + // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts + input.dt = monitor ? 1.0 : dt; input.start_velocity = thiscoupler.closing; auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; + // the override, by the crush of both ends + auto const climbing_of = [&](double const Crush1, double const Crush2) { + collision::override_input climbing; + climbing.crush1 = Crush1; + climbing.crush2 = Crush2; + climbing.mass1 = TotalMass - Mred; + climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; + climbing.height1 = buffer_height_at(End); + climbing.height2 = othervehicle->buffer_height_at(otherend); + climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); + climbing.zone1 = firstcurve.densify; + climbing.zone2 = secondcurve.densify; + return climbing; + }; + if (monitor) + { + if (hit.crushing && false == thiscoupler.crush_monitored) + { + thiscoupler.crush_monitored = true; + othercoupler.crush_monitored = true; + ++crush_reports; + auto const crush1{thiscoupler.crush + hit.crush1}; + auto const crush2{othercoupler.crush + hit.crush2}; + auto const climbed{collision::override_of(climbing_of(crush1, crush2))}; + auto const torn{std::max(crush1, crush2) >= collision::draw_gear_crush}; + std::string const outcome{climbed.first && climbed.second ? std::string{"both would leave the rails"} + : climbed.first ? Name + " would ride up onto " + othervehicle->Name + : climbed.second ? othervehicle->Name + " would ride up onto " + Name + : std::string{"both would stay on the rails"}}; + WriteLog(std::format("collision monitor: {} and {} collided at {:.0f} km/h: the {} end of {} ({:.1f} t {}) would crush by {:.2f} m, the {} end of {} ({:.1f} t {}) by {:.2f} m, " + "at {:.0f} kN; draw gear {}; {}", + Name, othervehicle->Name, closing * 3.6, end_name(End), Name, TotalMass / 1000.0, kind_name(collision_kind()), crush1, end_name(otherend), othervehicle->Name, + othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), crush2, hit.force / 1000.0, torn ? "torn off" : "holds", outcome)); + } + return false; + } if (false == hit.crushing) { // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push @@ -1689,16 +1736,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) } // the end crushed deep enough lets one vehicle climb onto the other one - collision::override_input climbing; - climbing.crush1 = thiscoupler.crush; - climbing.crush2 = othercoupler.crush; - climbing.mass1 = TotalMass - Mred; - climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; - climbing.height1 = buffer_height_at(End); - climbing.height2 = othervehicle->buffer_height_at(otherend); - climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); - climbing.zone1 = firstcurve.densify; - climbing.zone2 = secondcurve.densify; + auto const climbing{climbing_of(thiscoupler.crush, othercoupler.crush)}; auto const climbed{collision::override_of(climbing)}; auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, @@ -1717,7 +1755,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) void TMoverParameters::check_pushed_off(double const dt) { - if (Global.derailment != global_settings::derailment_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || + if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) { pushed_off_monitor.reset(); @@ -5995,7 +6033,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - // the ends crushed for good (physics.derailment new, see collision.h) let the buffers meet that much closer + // the ends crushed for good (physics.collisions new, see collision.h) let the buffers meet that much closer auto const crushed{thiscoupler.crush + othercoupler.crush}; auto const rawdistance{initialdistance + 10.0 * distancedelta}; auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance}; @@ -6143,8 +6181,8 @@ void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other { return; } - // a coupler torn off by the crush of its end (physics.derailment new) doesn't catch - if (Global.derailment == global_settings::derailment_model::physical && (thiscoupler.broken || othercoupler.broken)) + // a coupler torn off by the crush of its end (physics.collisions new) doesn't catch + if (Global.collisions == global_settings::collision_model::physical && (thiscoupler.broken || othercoupler.broken)) { return; } @@ -6281,8 +6319,8 @@ bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; // the other vehicle keeps the state of the pair alike othercoupler.physics_state.elongation = state.elongation; - // with physics.derailment new the crush of the ends past the buffers is crush_hit()'s - if (hit.broken || (hit.crushed && Global.derailment != global_settings::derailment_model::physical)) + // with physics.collisions new the crush of the ends past the buffers is crush_hit()'s + if (hit.broken || (hit.crushed && Global.collisions != global_settings::collision_model::physical)) { damage_coupler(End); } @@ -11755,7 +11793,7 @@ void scale_strength(coupler_physics::link_strength &Link, double const Factor) Link.ultimate *= Factor; } -// the optional keys of the collisions past the buffers (physics.derailment new, see collision.h), what's not given +// the optional keys of the collisions past the buffers (physics.collisions new, see collision.h), what's not given // comes from the kind of the vehicle: // FcrushPeak, FcrushPlateau [kN] the force the end starts to crush at, and keeps crushing at // CrushOnset, CrushDensify, CrushLimit [m] the crush the peak drops at, it packs down past, it can't go past diff --git a/McZapkie/collision.h b/McZapkie/collision.h index dd3dad55e..b51fc6561 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "couplerphysics.h" -// what a collision of two vehicles does to them past their buffers (physics.derailment new in eu07.ini, see +// what a collision of two vehicles does to them past their buffers (physics.collisions new in eu07.ini, see // TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: // // crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the diff --git a/tests/scenarios/cases/en57_2000_crush_new.json b/tests/scenarios/cases/en57_2000_crush_new.json index e13c2299d..9de8c1688 100644 --- a/tests/scenarios/cases/en57_2000_crush_new.json +++ b/tests/scenarios/cases/en57_2000_crush_new.json @@ -1,7 +1,7 @@ { - "description": "G14 stage 2: an EN57-2000 unit without a driver runs at 20 km/h into a standing one on td.scn, with physics.derailment new. Too fast for the automatic couplers to catch: past the buffers the cab ends crush, a few decimetres, too little for either unit to climb onto the other, so both stay on the rails; the run ends on the 60 s test timeout.", + "description": "G14 stage 2: an EN57-2000 unit without a driver runs at 20 km/h into a standing one on td.scn, with physics.collisions new. Too fast for the automatic couplers to catch: past the buffers the cab ends crush, a few decimetres, too little for either unit to climb onto the other, so both stay on the rails; the run ends on the 60 s test timeout.", "base_scenery": "td.scn", - "ini": ["crashdamage yes", "physics.derailment new"], + "ini": ["crashdamage yes", "physics.collisions new"], "fragment": "td_automatic_coupler_hit.scn", "vars": { "velocity": "20", diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index f4af0151c..c08c714dc 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -11,7 +11,7 @@ #include #include -// collisions past the buffers with physics.derailment new (McZapkie/collision.h): the crush of the ends, the override, +// collisions past the buffers with physics.collisions new (McZapkie/collision.h): the crush of the ends, the override, // the push off the track, and what they do in trains of real vehicles using test::consist; @@ -23,16 +23,16 @@ namespace { constexpr double kmh{1.0 / 3.6}; -// the given model of derailment for the test, restored after it +// the given model of collisions for the test, restored after it class model_setting { public: - explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } - ~model_setting() { Global.derailment = m_previous; } + explicit model_setting(global_settings::collision_model Model) : m_previous{Global.collisions} { Global.collisions = Model; } + ~model_setting() { Global.collisions = m_previous; } model_setting(model_setting const &) = delete; model_setting &operator=(model_setting const &) = delete; private: - global_settings::derailment_model m_previous; + global_settings::collision_model m_previous; }; // the given setting of a global flag for the test, restored after it @@ -453,7 +453,7 @@ TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of // ---- the model of eu07.ini -TEST_CASE("collisions: the legacy rule with physics.derailment old, the crush with new") { +TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush with new") { flag_setting const crashdamage{Global.crash_damage, true}; struct collision { char const *name; @@ -464,18 +464,22 @@ TEST_CASE("collisions: the legacy rule with physics.derailment old, the crush wi bool backout_old; bool frontout_new; bool backout_new; + int monitored; // the hits the monitor tells of }; // the legacy rule: over 15 km/h weighed by the ratio of the masses. the crush: the light wagon is crushed deep and // climbs onto the locomotive at 60 km/h; two locomotives at 25 km/h crush their ends 0.1-0.3 m and stay on the rails - for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new] : { - collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false}, - collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false}, - collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true}, + // the monitor tells of each hit once: the wagon derailed by the legacy rule is a wall, which the locomotive behind + // it hits once more; the locomotives derailed both stay where they are + for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new, monitored] : { + collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false, 2}, + collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false, 1}, + collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true, 1}, }) { CAPTURE(name); - for (auto const model : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { - auto const physical{model == global_settings::derailment_model::physical}; - CAPTURE(physical); + // monitor: the legacy rule, and the log tells of the crush once + for (auto const model : {global_settings::collision_model::old, global_settings::collision_model::physical, global_settings::collision_model::monitor}) { + auto const physical{model == global_settings::collision_model::physical}; + CAPTURE(name_of(model)); model_setting const setting{model}; consist train; train.add(definition::fiz(front)); @@ -491,12 +495,46 @@ TEST_CASE("collisions: the legacy rule with physics.derailment old, the crush wi else { CHECK(crush == 0.0); } + CHECK(train[0]->crush_reports + train[1]->crush_reports == (model == global_settings::collision_model::monitor ? monitored : 0)); + } + } +} + +TEST_CASE("collisions: the names of the models in eu07.ini") { + using model = global_settings::collision_model; + CHECK(collision_model_of("new") == model::physical); + CHECK(collision_model_of("old") == model::old); + CHECK(collision_model_of("monitor") == model::monitor); + // a name it doesn't know is the default + CHECK(collision_model_of("physical") == model::physical); + CHECK(global_settings{}.collisions == model::physical); + for (auto const value : {model::old, model::physical, model::monitor}) { + CHECK(collision_model_of(name_of(value)) == value); + } + CHECK(name_of(model::physical) == "new"); +} + +TEST_CASE("collisions: the model of the collisions goes apart from the one of the derailment") { + // the crush with the legacy draw of the derailment in a curve, the legacy collisions with the criteria + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const derailment : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + for (auto const collisions : {global_settings::collision_model::old, global_settings::collision_model::physical}) { + auto const previous{Global.derailment}; + Global.derailment = derailment; + model_setting const setting{collisions}; + consist train; + train.add(definition::fiz("4e_v1/4e")); + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + train.run(10.0); + Global.derailment = previous; + auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + CHECK((crush > 0.05) == (collisions == global_settings::collision_model::physical)); } } } TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend on the step, nor on the model of the coupling") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; for (auto const physics : {false, true}) { CAPTURE(physics); @@ -523,7 +561,7 @@ TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend } TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends crush; torn off, they don't couple again") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; auto const automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; for (auto const speed : {20.0, 30.0, 45.0}) { @@ -557,9 +595,9 @@ TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends cru TEST_CASE("collisions: road vehicles keep the legacy rule") { // the traffic of a scenery: cars and buses have no underframe to crush; over 15 km/h weighed by the masses they - // derail, as with physics.derailment old (found running line 107: two cars of its traffic, 119 km/h head-on) + // derail, as with physics.collisions old (found running line 107: two cars of its traffic, 119 km/h head-on) flag_setting const crashdamage{Global.crash_damage, true}; - for (auto const model : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + for (auto const model : {global_settings::collision_model::old, global_settings::collision_model::physical, global_settings::collision_model::monitor}) { model_setting const setting{model}; consist road; road.add(definition::fiz("road/man/nl293")); @@ -569,11 +607,12 @@ TEST_CASE("collisions: road vehicles keep the legacy rule") { CHECK(derailed(road[1].mover())); CHECK(road[0]->Couplers[end::rear].crush == 0.0); CHECK(road[1]->CollisionDerail == NONE); + CHECK(road[0]->crush_reports + road[1]->crush_reports == 0); } } TEST_CASE("collisions: a vehicle off the rails by the new model stays in the chain of forces") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; consist train; auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; @@ -595,7 +634,7 @@ TEST_CASE("collisions: a vehicle off the rails by the new model stays in the cha } TEST_CASE("collisions: a freight train running into a standing one, the cases of the PoC of G14") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; struct crash { double speed; @@ -616,7 +655,7 @@ TEST_CASE("collisions: a freight train running into a standing one, the cases of } TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; // two coaches of data/wagon.json (42.2 t) a unit, their ends crash zones with anticlimbers, unbraked auto const unit = [](bool const Anticlimbers, double const Height) { diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index f42ecd731..ba9404482 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -496,11 +496,11 @@ TEST_CASE("controls: a freight wagon loaded and braked") { } TEST_CASE("controls: a locomotive running into a standing wagon") { - // the legacy collisions of physics.derailment old: derailed, the wagon is a wall (test_collisions.cpp has the new) + // the legacy collisions of physics.collisions old: derailed, the wagon is a wall (test_collisions.cpp has the new) struct legacy { - global_settings::derailment_model previous{Global.derailment}; - legacy() { Global.derailment = global_settings::derailment_model::old; } - ~legacy() { Global.derailment = previous; } + global_settings::collision_model previous{Global.collisions}; + legacy() { Global.collisions = global_settings::collision_model::old; } + ~legacy() { Global.collisions = previous; } legacy(legacy const &) = delete; legacy &operator=(legacy const &) = delete; } const model; diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index c6a3f4a5d..19421c52b 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -49,17 +49,17 @@ private: bool m_previous{Global.crash_damage}; }; -// the legacy collisions of physics.derailment old for the test, restored after it: the rule of the safe closing speed +// the legacy collisions of physics.collisions old for the test, restored after it: the rule of the safe closing speed // weighed by the ratio of the masses (the crush of the ends of the new model is in test_collisions.cpp) class legacy_collisions { public: - legacy_collisions() { Global.derailment = global_settings::derailment_model::old; } - ~legacy_collisions() { Global.derailment = m_previous; } + legacy_collisions() { Global.collisions = global_settings::collision_model::old; } + ~legacy_collisions() { Global.collisions = m_previous; } legacy_collisions(legacy_collisions const &) = delete; legacy_collisions &operator=(legacy_collisions const &) = delete; private: - global_settings::derailment_model m_previous{Global.derailment}; + global_settings::collision_model m_previous{Global.collisions}; }; } // namespace diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index e17a8f86d..cbe002bb1 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -17,16 +17,16 @@ using namespace test::channels; namespace { -// the given model of derailment for the test, restored after it +// the given model of collisions for the test, restored after it class model_setting { public: - explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } - ~model_setting() { Global.derailment = m_previous; } + explicit model_setting(global_settings::collision_model Model) : m_previous{Global.collisions} { Global.collisions = Model; } + ~model_setting() { Global.collisions = m_previous; } model_setting(model_setting const &) = delete; model_setting &operator=(model_setting const &) = delete; private: - global_settings::derailment_model m_previous; + global_settings::collision_model m_previous; }; } // namespace @@ -165,8 +165,8 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { TEST_CASE("couplers: collisions fast enough to derail") { // a locomotive running into a standing wagon from behind, and a wagon running backwards into a standing // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail. the legacy rule of - // physics.derailment old: the new model crushes the ends (test_collisions.cpp) - model_setting const legacy{global_settings::derailment_model::old}; + // physics.collisions old: the new model crushes the ends (test_collisions.cpp) + model_setting const legacy{global_settings::collision_model::old}; struct collision { char const *name; char const *frontpath; diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 746105ad6..faf2d5660 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -896,6 +896,16 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.collisions") + { + // new: the crush of the ends past the buffers (McZapkie/collision.h), old: the legacy rule, monitor: the legacy + // rule, and the crush to the log + std::string model; + ParseOne(Parser, model, 1); + collisions = collision_model_of(model); + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1794,6 +1804,7 @@ global_settings::export_as_text( std::ostream &Output ) const { derailment == derailment_model::old ? "old" : derailment == derailment_model::off ? "off" : "new" } ); + export_as_text( Output, "physics.collisions", std::string{ name_of( collisions ) } ); 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 19dabab53..03fb2ff09 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -296,6 +296,12 @@ struct global_settings { // it; off, it stays on the rails at any speed enum class derailment_model { off, old, physical }; derailment_model derailment = derailment_model::physical; + // the collisions of rail vehicles past their buffers (physics.collisions in eu07.ini): new, the ends crush, a vehicle + // may ride up onto the other one or be pushed off the track (McZapkie/collision.h); old, the legacy rule of the safe + // closing speed weighed by the masses; monitor, the legacy rule decides and the log tells what the crush would be + // (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; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; @@ -445,6 +451,21 @@ template <> void global_settings::export_as_text( std::ostream &Output, std::string const Key, bool const &Value ) const; +// the models of physics.collisions by their names in eu07.ini: new (the default, also for a name it doesn't know), old, +// monitor +inline global_settings::collision_model collision_model_of( std::string_view const Name ) { + if( Name == "old" ) { return global_settings::collision_model::old; } + if( Name == "monitor" ) { return global_settings::collision_model::monitor; } + return global_settings::collision_model::physical; +} +inline std::string_view name_of( global_settings::collision_model const Model ) { + switch( Model ) { + case global_settings::collision_model::old: { return "old"; } + case global_settings::collision_model::monitor: { return "monitor"; } + default: { return "new"; } + } +} + extern global_settings& GetGlobalSettings(); #define Global (GetGlobalSettings()) From c83c987e3f2725390c8178c8f01abdbb1ee23d9a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 20:11:10 +0100 Subject: [PATCH 26/59] feat(physics): physics.derailment monitor tells what the criteria would do, the legacy draw decides With monitor the run goes as with old: the legacy draw derails a vehicle too fast in a curve, with the legacy effects. The criteria of derailment.h are evaluated as with new, and where they would derail a vehicle the log gets one line (derailment monitor:) with the data of the entry of a real derailment: the vehicle, the track, the speed, the radius, the cant, the lateral acceleration, D, Y/Q, the mass, the centre of gravity, the forces of the couplings, the damage flags and the cross level. Once for a vehicle on a track, so one run of a scenery shows what new would do without changing its course. The entry of a derailment by the criteria names the track as well; derailment::report() writes both. The names of the models in eu07.ini go through derailment_model_of() and name_of(), read and written back alike. --- McZapkie/MOVER.h | 11 ++++- McZapkie/Mover.cpp | 30 ++++++++----- McZapkie/derailment.cpp | 10 +++++ McZapkie/derailment.h | 7 +++ tests/unit/test_derailment.cpp | 21 +++++++++ tests/unit/test_derailment_vehicle.cpp | 62 ++++++++++++++++++++++++++ tests/unit/vehicle.cpp | 1 + tests/unit/vehicle.h | 1 + utilities/Globals.cpp | 15 ++----- utilities/Globals.h | 22 ++++++++- vehicle/DynObj.cpp | 1 + 11 files changed, 155 insertions(+), 26 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 63783419b..1d2280bcc 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -712,6 +712,8 @@ struct TTrackParam int DamageFlag = 0; /// Maximum allowed velocity on this segment (used by AI driver). double Velmax; /*dla uzytku maszynisty w ai_driver*/ + /// Name of the track, for the log; nullptr where there is none. + std::string const *Name = nullptr; }; /// Traction-supply parameters at the vehicle's current location. @@ -2049,6 +2051,10 @@ class TMoverParameters // the criteria of derailment (physics.derailment new), and the distance travelled since they were checked [m] derailment::monitor derailment_monitor; double derailment_distance = 0.0; + // physics.derailment monitor: the name of the track the criteria were last reported on (one report on a track), and + // how many reports there were + std::optional derailment_reported; + int derailment_reports = 0; odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) std::pair EnergyMeter; // energy from grid [kWh] double V = 0.0; // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) @@ -2435,10 +2441,11 @@ class TMoverParameters // was a broken coupler to repair bool repair_coupler(int const End); void Derail(DerailReason Reason); - // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m] + // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m]; monitor: what + // they would do, to the log void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); // the vehicle leaves the rails, as the criteria of derailment.h found - void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track); + void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName = nullptr); // height of the centre of gravity above the rail with the load [m] double centre_of_gravity() const; // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2fa19e184..2dfb8d484 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1548,13 +1548,26 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co track.damage = Track.DamageFlag; auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; - if (verdict.result != derailment::outcome::none) + if (verdict.result == derailment::outcome::none) { - derail(verdict, vehicle, track); + return; } + if (Global.derailment == global_settings::derailment_model::physical) + { + derail(verdict, vehicle, track, Track.Name); + return; + } + // physics.derailment monitor: the legacy draw decides, the log tells what the criteria would do, once on a track + if (derailment_reported.has_value() && *derailment_reported == Track.Name) + { + return; + } + derailment_reported = Track.Name; + ++derailment_reports; + WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{})); } -void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track) +void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) { if (false == SetFlag(DamageFlag, dtrain_out)) { @@ -1568,12 +1581,7 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve { AlarmChainFlag = true; } - auto const cant{1000.0 * derailment::contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; - ErrorLog(std::format("Bad driving: {} {} at {:.0f} km/h, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" - " (mass {:.1f} t, centre of gravity {:.2f} m, couplings pushing {:.0f} / {:.0f} kN, track damage {}, cross level {:.0f} mm)", - Name, Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Track.radius), cant, - Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, Vehicle.ends[end::front].compression / 1000.0, - Vehicle.ends[end::rear].compression / 1000.0, Track.damage, Track.uneven_cross)); + ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{})); } void TMoverParameters::Derail(DerailReason const Reason) @@ -1703,7 +1711,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap Derail(END_OF_TRACK); // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria // once the step's distance is known, below - if (Global.derailment == global_settings::derailment_model::old && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) + if ((Global.derailment == global_settings::derailment_model::old || Global.derailment == global_settings::derailment_model::monitor) && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) Derail(TOO_HIGH_SPEED); // wykolejanie na poszerzeniu toru if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) @@ -1716,7 +1724,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // dL:=(V+AccS*dt/2)*dt; // przyrost dlugosci czyli przesuniecie dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} - if (Global.derailment == global_settings::derailment_model::physical) + if (Global.derailment == global_settings::derailment_model::physical || Global.derailment == global_settings::derailment_model::monitor) { // over the distance of this step and of the simpler ones of the frame before it check_derailment(Shape, Track, derailment_distance + std::abs(dL)); diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index 5cccc9f9c..48e61aee5 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include namespace derailment { @@ -231,4 +232,13 @@ double sliding_friction(outcome const Outcome) { } } +std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double const Velocity, std::string_view const TrackName) { + auto const cant{1000.0 * contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; + return std::format("{} at {:.0f} km/h on track {}, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" + " (mass {:.1f} t, centre of gravity {:.2f} m, couplings pushing {:.0f} / {:.0f} kN, track damage {}, cross level {:.0f} mm)", + Verdict.result == outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(Velocity) * 3.6, TrackName.empty() ? "(none)" : TrackName, + std::abs(Track.radius), cant, Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, + Vehicle.ends[0].compression / 1000.0, Vehicle.ends[1].compression / 1000.0, Track.damage, Track.uneven_cross); +} + } // namespace derailment diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 7d587517f..00088e0d7 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include +#include // the criteria of a vehicle leaving the rails, as plain functions of what the vehicle and the track under it are // like, so the collisions and the buckled track can use them as well as the speed in a curve does @@ -202,4 +204,9 @@ inline constexpr double off_rails_friction{0.3}; inline constexpr double overturned_friction{0.5}; double sliding_friction(outcome Outcome); +// what the criteria found, for the log: "overturned at 113 km/h on track t1, curve radius 300 m, cant 0 mm: lateral +// acceleration ..., wheel unloading ..., Y/Q ... (mass ..., centre of gravity ..., couplings pushing ... / ... kN, +// track damage ..., cross level ... mm)" +std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double Velocity, std::string_view TrackName); + } // namespace derailment diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 201c2e3bc..f078d7c6e 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -278,3 +278,24 @@ TEST_CASE("derailment: the damage flags of the track make the ride rougher, not CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) - dr::body_acceleration(eu07vehicle, good, 30.0) == doctest::Approx(1.1 * dr::vibration)); } } + +TEST_CASE("derailment: the report of the log") { + dr::verdict verdict; + verdict.result = dr::outcome::overturned; + verdict.acceleration = 3.31; + verdict.unloading = 1.02; + verdict.flange_ratio = 0.55; + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.centre_of_gravity = 1.65; + vehicle.ends[1].compression = 50000.0; + dr::track_state track; + track.radius = -300.0; + track.damage = 31; + auto const text{dr::report(verdict, vehicle, track, 113.0 / 3.6, "track_7")}; + CHECK(text == + "overturned at 113 km/h on track track_7, curve radius 300 m, cant 0 mm: lateral acceleration 3.31 m/s2, wheel unloading 1.02, Y/Q 0.55 (mass 80.0 t, centre of gravity 1.65 m," + " couplings pushing 0 / 50 kN, track damage 31, cross level 0 mm)"); + verdict.result = dr::outcome::off_rails; + CHECK(dr::report(verdict, vehicle, track, 20.0, "").starts_with("derailed, the flange climbed the rail at 72 km/h on track (none),")); +} diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 690284ba2..b425fcd2c 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -164,3 +164,65 @@ TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { } CHECK(still); } + +TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what the criteria would do") { + model_setting const monitor{global_settings::derailment_model::monitor}; + test::track curve; + curve.radius = 300.0; + curve.name = "curve_1"; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + // over the speed the criteria overturn the EU07 at, under the threshold of the legacy draw (112 km/h) + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + REQUIRE(critical + 2.0 < 112.0); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + // once on a track, however long it stays over the criteria + CHECK(eu07vehicle->derailment_reports == 1); + REQUIRE(eu07vehicle->derailment_reported.has_value()); + CHECK(*eu07vehicle->derailment_reported == &curve.name); + // and once more on the next one + test::track next{curve}; + next.name = "curve_2"; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(next); + } + CHECK(eu07vehicle->derailment_reports == 2); + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + + SUBCASE("under the criteria nothing is told") { + vehicle slower{definition::fiz("4e_v1/4e"), critical - 5.0}; + for (int step = 0; step < 100; ++step) { + slower.step(curve); + } + CHECK(slower->derailment_reports == 0); + } + SUBCASE("far over the legacy threshold the legacy draw derails it, the legacy way") { + vehicle faster{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + faster.step(curve); + } + CHECK(TestFlag(faster->DamageFlag, dtrain_out)); + CHECK(faster->Derailed == dr::outcome::none); + CHECK(faster->V == doctest::Approx(0.0).epsilon(0.01)); + } +} + +TEST_CASE("derailment: the names of the models in eu07.ini") { + using model = global_settings::derailment_model; + CHECK(derailment_model_of("new") == model::physical); + CHECK(derailment_model_of("old") == model::old); + CHECK(derailment_model_of("off") == model::off); + CHECK(derailment_model_of("no") == model::off); + CHECK(derailment_model_of("monitor") == model::monitor); + // a name it doesn't know is the default + CHECK(derailment_model_of("physical") == model::physical); + CHECK(global_settings{}.derailment == model::physical); + // written back the way it's read + for (auto const value : {model::off, model::old, model::physical, model::monitor}) { + CHECK(derailment_model_of(name_of(value)) == value); + } + CHECK(name_of(model::physical) == "new"); +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 100344369..61609d3ba 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -179,6 +179,7 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { TTrackParam param; param.Width = Track.width; param.friction = Track.friction; + param.Name = &Track.name; // the vehicle's own kind of way: a road vehicle on rails derails as soon as it moves if (Track.category != 0) { param.CategoryFlag = Track.category; diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index 784a4486d..1e7db3599 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -68,6 +68,7 @@ struct track { double width{1.435}; double radius{0.0}; // of a curve [m], 0 straight double cant{0.0}; // [rad] + std::string name; // for the log }; // the catenary of the Polish railways [V] diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 746105ad6..bef7e5ab2 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -884,15 +884,11 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& if (token == "physics.derailment") { - // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed + // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed, + // monitor: the legacy draw, and the criteria to the log std::string model; ParseOne(Parser, model, 1); - if (model == "old") - derailment = derailment_model::old; - else if (model == "off" || model == "no") - derailment = derailment_model::off; - else - derailment = derailment_model::physical; + derailment = derailment_model_of(model); return true; } @@ -1790,10 +1786,7 @@ global_settings::export_as_text( std::ostream &Output ) const { couplerphysics = "all"; } export_as_text( Output, "couplerphysics", couplerphysics ); - export_as_text( Output, "physics.derailment", std::string{ - derailment == derailment_model::old ? "old" : - derailment == derailment_model::off ? "off" : - "new" } ); + export_as_text( Output, "physics.derailment", std::string{ name_of( derailment ) } ); 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 19dabab53..b5ff2b3a2 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -293,8 +293,9 @@ struct global_settings { // a vehicle too fast in a curve (physics.derailment in eu07.ini): new, it overturns or its flange climbs the rail // by the criteria of McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops - // it; off, it stays on the rails at any speed - enum class derailment_model { off, old, physical }; + // it; off, it stays on the rails at any speed; monitor, the legacy draw decides and the log tells where the criteria + // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was + enum class derailment_model { off, old, physical, monitor }; derailment_model derailment = derailment_model::physical; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; @@ -445,6 +446,23 @@ template <> void global_settings::export_as_text( std::ostream &Output, std::string const Key, bool const &Value ) const; +// the models of physics.derailment by their names in eu07.ini: new (the default, also for a name it doesn't know), old, off +// or no, monitor +inline global_settings::derailment_model derailment_model_of(std::string_view const Name) { + if( Name == "old" ) { return global_settings::derailment_model::old; } + if( Name == "off" || Name == "no" ) { return global_settings::derailment_model::off; } + if( Name == "monitor" ) { return global_settings::derailment_model::monitor; } + return global_settings::derailment_model::physical; +} +inline std::string_view name_of( global_settings::derailment_model const Model ) { + switch( Model ) { + case global_settings::derailment_model::old: { return "old"; } + case global_settings::derailment_model::off: { return "off"; } + case global_settings::derailment_model::monitor: { return "monitor"; } + default: { return "new"; } + } +} + extern global_settings& GetGlobalSettings(); #define Global (GetGlobalSettings()) diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 66b1007df..39ab5c4b6 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3237,6 +3237,7 @@ bool TDynamicObject::Update(double dt, double dt1) tp.CategoryFlag = MyTrack->iCategoryFlag & 15; tp.DamageFlag = MyTrack->iDamageFlag; tp.QualityFlag = MyTrack->iQualityFlag; + tp.Name = &MyTrack->name(); // couplers if( MoverParameters->Couplers[0].CouplingFlag != coupling::faux From 0074197c1d60c4a19815e802afbe3f6aadb74a96 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 20:11:11 +0100 Subject: [PATCH 27/59] feat(physics): physics.trackcheck logs the tracks of a scenery the criteria of derailment find suspicious With physics.trackcheck yes (no by default) every rail track is checked once the scenery loaded, and the suspicious ones are logged, a line for each (trackcheck:), with a summary of the count of each kind: a speed limit over the speed a reference vehicle overturns or climbs the rail at in the curve (an EU07 and a 4-axle coach from the defaults of derailment.h, no .fiz needed; a track without a limit of its own gets 125 km/h and is counted apart), cant held on a straight track, cant over 160 mm, a curve under 40 m with a limit over 40 km/h, and unevenness out of the plausible range. The damage flags are only counted by their value: the sceneries set them for the jolts. The radius is the tightest of the design geometry of the path, so curves given by their control points only count as well. The check is a plain function of the data of the tracks with a log sink (world/TrackCheck.h, in eu07_core), tested on its own; derailment::climbing_speed() gives the speed the flange climbs at, none where it doesn't. --- CMakeLists.txt | 1 + McZapkie/derailment.cpp | 23 +++ McZapkie/derailment.h | 6 + simulation/simulationstateserializer.cpp | 3 + tests/unit/test_derailment.cpp | 44 ++++++ tests/unit/test_derailment_vehicle.cpp | 1 + tests/unit/test_track_check.cpp | 158 +++++++++++++++++++ utilities/Globals.cpp | 7 + utilities/Globals.h | 3 + world/Track.cpp | 63 ++++++++ world/Track.h | 3 + world/TrackCheck.cpp | 184 +++++++++++++++++++++++ world/TrackCheck.h | 96 ++++++++++++ 13 files changed, 592 insertions(+) create mode 100644 tests/unit/test_track_check.cpp create mode 100644 world/TrackCheck.cpp create mode 100644 world/TrackCheck.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 76f359eab..64872ab14 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -538,6 +538,7 @@ set(CORE_SOURCES "McZapkie/Mover.cpp" "McZapkie/couplerphysics.cpp" "McZapkie/derailment.cpp" +"world/TrackCheck.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index 48e61aee5..ed55754b9 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -232,6 +232,29 @@ double sliding_friction(outcome const Outcome) { } } +std::optional climbing_speed(vehicle_state const &Vehicle, track_state const &Track) { + auto const climbs = [&](double const Velocity) { return flange_forces(Vehicle, Track, Velocity).ratio() >= climbing_limit; }; + // from the speed the cant balances, where the vehicle starts to lean on the outer rail + auto const balancing{curved(Track.radius) ? std::sqrt(gravity * std::abs(Track.radius) * std::sin(std::abs(Track.cant))) : 0.0}; + if (climbs(balancing)) { + return balancing; + } + // in steps of 1 m/s up to the first speed it climbs at, which needn't hold above it, then halving the step + constexpr double fastest{200.0}; + for (auto low{balancing}; low < fastest; low += 1.0) { + auto high{std::min(low + 1.0, fastest)}; + if (false == climbs(high)) { + continue; + } + for (int iteration = 0; iteration < 30; ++iteration) { + auto const middle{0.5 * (low + high)}; + (climbs(middle) ? high : low) = middle; + } + return high; + } + return std::nullopt; +} + std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double const Velocity, std::string_view const TrackName) { auto const cant{1000.0 * contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; return std::format("{} at {:.0f} km/h on track {}, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 00088e0d7..fd9ad6daa 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include #include @@ -204,6 +205,11 @@ inline constexpr double off_rails_friction{0.3}; inline constexpr double overturned_friction{0.5}; double sliding_friction(outcome Outcome); +// the lowest speed [m/s] from the one the cant balances at which the flange of the leading axle climbs the rail (Y / Q +// at the climbing limit); none when it doesn't climb up to 200 m/s: a lone vehicle on a good track mostly overturns +// first, its Y / Q goes to the ratio of the contact spacing to the height of the centre of gravity at speed +std::optional climbing_speed(vehicle_state const &Vehicle, track_state const &Track); + // what the criteria found, for the log: "overturned at 113 km/h on track t1, curve radius 300 m, cant 0 mm: lateral // acceleration ..., wheel unloading ..., Y/Q ... (mass ..., centre of gravity ..., couplings pushing ... / ... kN, // track damage ..., cross level ... mm)" diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 9d1e94869..3a4edb7b1 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -445,6 +445,9 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc Scratchpad.binary.terrain_binaryfiles.clear(); simulation::Paths.InitTracks(); + if( Global.track_check ) { + simulation::Paths.CheckTracks(); + } // the roads tie up their own lanes where they gain or lose some, the junctions tie the lanes of the roads together, // what's left loose after that gets closed by the roads simulation::Roads.InitLanes(); diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index f078d7c6e..3afca6a26 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -279,6 +279,50 @@ TEST_CASE("derailment: the damage flags of the track make the ride rougher, not } } +TEST_CASE("derailment: the speed the flange climbs the rail at") { + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.axles = 4; + vehicle.length = 16.0; + vehicle.axle_base = 3.0; + vehicle.centre_of_gravity = 1.65; + dr::track_state track; + track.radius = 300.0; + SUBCASE("a lone vehicle on a good track overturns first: its Y/Q stays under the limit") { + CHECK_FALSE(dr::climbing_speed(vehicle, track).has_value()); + } + SUBCASE("on a twisted track it climbs, at the speed Y/Q reaches the limit") { + // 50 mm of cross level takes half the load off the wheel + track.uneven_cross = 50.0; + auto const speed{dr::climbing_speed(vehicle, track)}; + REQUIRE(speed.has_value()); + CHECK(*speed > 0.0); + CHECK(dr::flange_forces(vehicle, track, *speed).ratio() >= dr::climbing_limit); + CHECK(dr::flange_forces(vehicle, track, *speed - 0.01).ratio() < dr::climbing_limit); + SUBCASE("the cant moves it up") { + track.cant = std::asin(0.1 / 1.5); + auto const canted{dr::climbing_speed(vehicle, track)}; + REQUIRE(canted.has_value()); + CHECK(*canted > *speed); + } + } + SUBCASE("pushed hard enough it climbs at a standstill: from the speed the cant balances") { + // an empty 3WL between heavy vehicles pushing 1 MN in a curve of 150 m, on 40 mm of cross level + vehicle.mass = 10500.0; + vehicle.axles = 2; + vehicle.length = 9.0; + vehicle.axle_base = 5.0; + vehicle.centre_of_gravity = 1.1; + vehicle.ends[0] = {1000000.0, 16.0}; + vehicle.ends[1] = {1000000.0, 16.0}; + track.radius = 150.0; + track.uneven_cross = 40.0; + auto const speed{dr::climbing_speed(vehicle, track)}; + REQUIRE(speed.has_value()); + CHECK(*speed == 0.0); + } +} + TEST_CASE("derailment: the report of the log") { dr::verdict verdict; verdict.result = dr::outcome::overturned; diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index b425fcd2c..6e8e4661a 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -220,6 +220,7 @@ TEST_CASE("derailment: the names of the models in eu07.ini") { // a name it doesn't know is the default CHECK(derailment_model_of("physical") == model::physical); CHECK(global_settings{}.derailment == model::physical); + CHECK_FALSE(global_settings{}.track_check); // written back the way it's read for (auto const value : {model::off, model::old, model::physical, model::monitor}) { CHECK(derailment_model_of(name_of(value)) == value); diff --git a/tests/unit/test_track_check.cpp b/tests/unit/test_track_check.cpp new file mode 100644 index 000000000..ce0424d81 --- /dev/null +++ b/tests/unit/test_track_check.cpp @@ -0,0 +1,158 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackCheck.h" + +#include +#include +#include +#include + +// physics.trackcheck: the geometry of the rail tracks of a scenery the criteria of derailment find suspicious, see +// world/TrackCheck.h + +namespace tc = track_check; + +namespace { + +bool has(tc::findings const &Found, tc::kind const Kind) { + return std::find(Found.kinds.begin(), Found.kinds.end(), Kind) != Found.kinds.end(); +} + +tc::track curve(double const Radius, double const Velocity, double const Cant = 0.0) { + tc::track track; + track.name = "t1"; + track.radius = Radius; + track.velocity = Velocity; + track.cant = {Cant, Cant}; + return track; +} + +double overturning(double const Radius, double const Cant = 0.0) { + auto const &eu07{tc::default_references().front().vehicle}; + return derailment::overturning_speed(Radius, std::asin(Cant / 1500.0), eu07.centre_of_gravity, 1.435) * 3.6; +} + +} // namespace + +TEST_CASE("trackcheck: the default vehicles") { + auto const &references{tc::default_references()}; + REQUIRE(references.size() == 2); + CHECK(references[0].name == "EU07"); + CHECK(references[0].vehicle.centre_of_gravity == doctest::Approx(1.65).epsilon(0.01)); + CHECK(references[1].vehicle.centre_of_gravity == doctest::Approx(1.42).epsilon(0.01)); + // the EU07 overturns at 108 km/h in a curve of 300 m without cant + CHECK(overturning(300.0) == doctest::Approx(108.0).epsilon(0.02)); +} + +TEST_CASE("trackcheck: the speed limit of a curve") { + auto const critical{overturning(300.0)}; + SUBCASE("under the speeds of the vehicles nothing") { + CHECK(tc::check(curve(300.0, critical - 10.0)).empty()); + } + SUBCASE("over the overturning speed of the EU07") { + auto const found{tc::check(curve(300.0, critical + 5.0))}; + CHECK(has(found, tc::kind::overturning)); + CHECK_FALSE(has(found, tc::kind::overturning_default)); + CHECK(found.text.find("over the overturning speed of EU07") != std::string::npos); + CHECK(found.text.find("speed limit 113 km/h") != std::string::npos); + } + SUBCASE("the cant raises it") { + CHECK(tc::check(curve(300.0, critical + 5.0, 100.0)).empty()); + } + SUBCASE("without a speed limit of its own the default one goes, counted apart") { + auto const found{tc::check(curve(300.0, -1.0))}; + CHECK(has(found, tc::kind::overturning_default)); + CHECK_FALSE(has(found, tc::kind::overturning)); + CHECK(found.text.find("default speed 125 km/h") != std::string::npos); + CHECK(found.text.find("speed limit none") != std::string::npos); + } + SUBCASE("a closed track (speed 0) is not checked") { + CHECK(tc::check(curve(100.0, 0.0)).empty()); + } + SUBCASE("nor the speed of a switch") { + auto track{curve(150.0, 100.0)}; + track.plain = false; + CHECK(tc::check(track).empty()); + } + SUBCASE("the cant at the end with the less of it") { + auto track{curve(300.0, critical + 5.0, 100.0)}; + track.cant[0] = 0.0; + CHECK(has(tc::check(track), tc::kind::overturning)); + } +} + +TEST_CASE("trackcheck: the cant") { + SUBCASE("the same cant at both ends of a straight track") { + auto const found{tc::check(curve(0.0, 100.0, 60.0))}; + CHECK(has(found, tc::kind::cant_on_straight)); + CHECK(found.text.starts_with("cant 60 / 60 mm on a straight track")); + } + SUBCASE("a transition has it at one end only") { + auto track{curve(0.0, 100.0, 60.0)}; + track.cant[0] = 0.0; + CHECK(tc::check(track).empty()); + } + SUBCASE("a few mm are left alone") { + CHECK(tc::check(curve(0.0, 100.0, 4.0)).empty()); + } + SUBCASE("over 160 mm") { + auto const found{tc::check(curve(1000.0, 60.0, 170.0))}; + CHECK(has(found, tc::kind::cant_excess)); + CHECK(found.kinds.size() == 1); + CHECK(tc::check(curve(1000.0, 60.0, 150.0)).empty()); + } +} + +TEST_CASE("trackcheck: a tight curve") { + CHECK(has(tc::check(curve(30.0, 50.0)), tc::kind::tight_curve)); + CHECK_FALSE(has(tc::check(curve(30.0, 30.0)), tc::kind::tight_curve)); + CHECK_FALSE(has(tc::check(curve(60.0, 50.0)), tc::kind::tight_curve)); +} + +TEST_CASE("trackcheck: the unevenness") { + auto track{curve(0.0, 100.0)}; + track.uneven.value = 14.f; + track.uneven.side = 20.f; + track.uneven.cross = 20.f; + CHECK(tc::check(track).empty()); + track.uneven.side = 40.f; + track.uneven.cross = 26.f; + auto const found{tc::check(track)}; + CHECK(has(found, tc::kind::uneven)); + CHECK(found.text.starts_with("uneven side 40, cross 26 mm out of range")); +} + +TEST_CASE("trackcheck: the scan of a scenery") { + std::vector tracks; + tracks.push_back(curve(300.0, 140.0)); + tracks.back().name = "fast"; + tracks.push_back(curve(0.0, 100.0)); + tracks.back().name = "worn"; + tracks.back().damage = 31; + tracks.push_back(curve(0.0, 100.0, 50.0)); + tracks.back().name = "leaning"; + tracks.back().damage = 31; + tracks.push_back(curve(0.0, 100.0)); + tracks.back().name = "fine"; + tracks.back().damage = 2; + + std::vector log; + auto const summary{tc::scan(tracks, [&](std::string const &Line) { log.push_back(Line); })}; + CHECK(summary.tracks == 4); + CHECK(summary.suspicious == 2); + CHECK(summary.count(tc::kind::overturning) == 1); + CHECK(summary.count(tc::kind::cant_on_straight) == 1); + CHECK(summary.count(tc::kind::tight_curve) == 0); + // the damage flags are counted, not told track by track + CHECK(summary.damage.at(31) == 2); + CHECK(summary.damage.at(2) == 1); + REQUIRE(log.size() == 4); + CHECK(log[0].starts_with("trackcheck: fast: speed limit 140 km/h over the overturning speed of EU07")); + CHECK(log[1].starts_with("trackcheck: leaning: cant 50 / 50 mm on a straight track")); + CHECK(log[1].ends_with("damage 31)")); + CHECK(log[2].starts_with("trackcheck: 4 rail tracks checked, 2 suspicious: overturning 1; flange climbing 0;")); + CHECK(log[3] == "trackcheck: damage flags: 2 on 1; 31 on 2"); + for (auto const &line : log) { + CHECK(line.starts_with("trackcheck: ")); + } +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index bef7e5ab2..8b134503a 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -892,6 +892,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.trackcheck") + { + ParseOne(Parser, track_check, 1); + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1787,6 +1793,7 @@ global_settings::export_as_text( std::ostream &Output ) const { } export_as_text( Output, "couplerphysics", couplerphysics ); export_as_text( Output, "physics.derailment", std::string{ name_of( derailment ) } ); + export_as_text( Output, "physics.trackcheck", track_check ); 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 b5ff2b3a2..174be4675 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -297,6 +297,9 @@ struct global_settings { // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was enum class derailment_model { off, old, physical, monitor }; derailment_model derailment = derailment_model::physical; + // 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; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; diff --git a/world/Track.cpp b/world/Track.cpp index 947a5836c..3f18ee226 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Track.h" #include "world/TrackRails.h" +#include "world/TrackCheck.h" #include "simulation/simulation.h" #include "scene/scene.h" #include "utilities/Globals.h" @@ -4164,6 +4165,68 @@ path_table::InitTracks() { TTrack::fetch_default_profiles(); } +namespace { + +// the tightest radius of the curve of a path in the plan [m], from the circles through its design points about 5 m apart +// (without the unevenness, whose short waves would bend it): the curve the axles of a vehicle follow, whether the track +// gives the radius or only its control points. 0 for a straight one; a radius over 15 km is taken for one, as +// TDynamicObject::Update() takes it +double tightest_radius(TSegment const &Segment) { + + auto const length { Segment.GetLength() }; + if( length < 0.5 ) { + return 0.0; + } + auto const intervals { std::max( 2, static_cast( std::ceil( length / 5.0 ) ) ) }; + auto const flat = [&]( int const Index ) { + auto const point { Segment.FastGetPoint( static_cast( Index ) / intervals ) }; + return glm::dvec2 { point.x, point.z }; }; + auto tightest { 0.0 }; + for( int index = 1; index < intervals; ++index ) { + auto const a { flat( index - 1 ) }; + auto const b { flat( index ) }; + auto const c { flat( index + 1 ) }; + auto const ab { b - a }; + auto const ac { c - a }; + auto const area2 { std::abs( ab.x * ac.y - ab.y * ac.x ) }; + if( area2 < 1e-9 ) { + continue; + } + auto const radius { glm::length( ab ) * glm::length( c - b ) * glm::length( ac ) / ( 2.0 * area2 ) }; + if( radius < 15000.0 && ( tightest == 0.0 || radius < tightest ) ) { + tightest = radius; + } + } + return tightest; +} + +} // namespace + +void +path_table::CheckTracks() const { + + std::vector tracks; + for( auto *path : sequence() ) { + if( path == nullptr || ( path->iCategoryFlag & 1 ) == 0 || path->Segment == nullptr ) { + continue; + } + track_check::track track; + track.name = path->name(); + track.velocity = path->VelocityGet(); + track.plain = ( path->eType == tt_Normal ); + track.radius = track.plain ? tightest_radius( *path->Segment ) : 0.0; + float roll1 { 0.f }, roll2 { 0.f }; + path->Segment->GetRolls( roll1, roll2 ); + track.gauge = path->fTrackWidth; + auto const spacing { 1000.0 * derailment::contact_spacing( track.gauge ) }; + track.cant = { spacing * std::sin( roll1 ), spacing * std::sin( roll2 ) }; + track.damage = path->iDamageFlag; + track.uneven = path->m_uneven; + tracks.emplace_back( std::move( track ) ); + } + track_check::scan( tracks, []( std::string const &Line ) { WriteLog( Line ); } ); +} + // legacy method, sends list of occupied paths over network void path_table::TrackBusyList() const { diff --git a/world/Track.h b/world/Track.h index 033bee610..3e03e4011 100644 --- a/world/Track.h +++ b/world/Track.h @@ -523,6 +523,9 @@ public: // legacy method, initializes tracks after deserialization from scenario file void InitTracks(); + // physics.trackcheck: logs the geometry of the rail tracks the checks of world/TrackCheck.h find suspicious + void + CheckTracks() const; // legacy method, sends list of occupied paths over network void TrackBusyList() const; diff --git a/world/TrackCheck.cpp b/world/TrackCheck.cpp new file mode 100644 index 000000000..22bc61861 --- /dev/null +++ b/world/TrackCheck.cpp @@ -0,0 +1,184 @@ +/* +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 "world/TrackCheck.h" + +#include +#include +#include + +namespace track_check { + +namespace { + +constexpr double kmh{3.6}; + +reference make_reference(std::string const &Name, double const Mass, double const Length, double const AxleBase, double const BodyHeight, derailment::vehicle_class const Class) { + reference result; + result.name = Name; + result.vehicle.mass = Mass; + result.vehicle.axles = 4; + result.vehicle.length = Length; + result.vehicle.axle_base = AxleBase; + result.vehicle.centre_of_gravity = derailment::default_centre_of_gravity(BodyHeight, Class); + return result; +} + +// the cant [rad] of the given height of the outer rail [mm] +double cant_angle(double const Cant, double const Gauge) { + return std::asin(std::clamp(std::abs(Cant) / (1000.0 * derailment::contact_spacing(Gauge)), 0.0, 1.0)); +} + +void append(std::string &Text, std::string const &Part) { + if (false == Text.empty()) { + Text += "; "; + } + Text += Part; +} + +// the values of the unevenness past the range, as "side 40, cross 30" +std::string uneven_excess(track_uneven::attribute const &Uneven, settings const &Settings) { + std::string result; + auto const test = [&](char const *Name, float const Value, double const Most) { + if (Value > Most) { + if (false == result.empty()) { + result += ", "; + } + result += std::format("{} {:g}", Name, Value); + } + }; + test("value", Uneven.value, Settings.most_uneven); + test("up", Uneven.up, Settings.most_uneven); + test("side", Uneven.side, Settings.most_uneven); + test("cross", Uneven.cross, Settings.most_cross); + test("dip", Uneven.dip, Settings.most_uneven); + test("branch", Uneven.branch, Settings.most_uneven); + test("branch up", Uneven.branchup, Settings.most_uneven); + test("branch side", Uneven.branchside, Settings.most_uneven); + return result; +} + +} // namespace + +std::vector const &default_references() { + static std::vector const references{ + make_reference("EU07", 80000.0, 15.915, 3.0, 4.348, derailment::vehicle_class::powered), + make_reference("coach", 40000.0, 24.5, 2.5, 4.05, derailment::vehicle_class::unpowered), + }; + return references; +} + +std::string_view name_of(kind const Kind) { + switch (Kind) { + case kind::overturning: + return "overturning"; + case kind::climbing: + return "flange climbing"; + case kind::overturning_default: + return "overturning at the default speed"; + case kind::climbing_default: + return "flange climbing at the default speed"; + case kind::cant_on_straight: + return "cant on a straight"; + case kind::cant_excess: + return "cant too high"; + case kind::tight_curve: + return "tight curve too fast"; + case kind::uneven: + return "uneven out of range"; + default: + return "?"; + } +} + +findings check(track const &Track, std::vector const &References, settings const &Settings) { + findings result; + auto const found = [&](kind const Kind, std::string const &Text) { + if (std::find(result.kinds.begin(), result.kinds.end(), Kind) == result.kinds.end()) { + result.kinds.push_back(Kind); + } + append(result.text, Text); + }; + auto const curved{Track.radius > 0.0}; + auto const given{Track.velocity >= 0.0}; + auto const velocity{given ? Track.velocity : Settings.default_velocity}; + + if (Track.plain) { + // the speed in the curve, with the cant both ends have at the least + if (curved && velocity > 0.0) { + auto const cant{std::min(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; + derailment::track_state track; + track.radius = Track.radius; + track.cant = cant_angle(cant, Track.gauge); + track.gauge = Track.gauge; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(track.radius, track.cant, reference.vehicle.centre_of_gravity, track.gauge) * kmh}; + if (overturning > 0.0 && velocity > overturning) { + found(given ? kind::overturning : kind::overturning_default, + std::format("{} {:.0f} km/h over the overturning speed of {} {:.0f} km/h", given ? "speed limit" : "default speed", velocity, reference.name, overturning)); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, track)}; climbing.has_value() && velocity > *climbing * kmh) { + found(given ? kind::climbing : kind::climbing_default, + std::format("{} {:.0f} km/h over the flange climbing speed of {} {:.0f} km/h", given ? "speed limit" : "default speed", velocity, reference.name, *climbing * kmh)); + } + } + } + // cant held over the whole of a straight track: a transition has it at one end only + if (false == curved && std::abs(Track.cant[0]) > Settings.straight_cant && std::abs(Track.cant[1]) > Settings.straight_cant && Track.cant[0] * Track.cant[1] > 0.0) { + found(kind::cant_on_straight, std::format("cant {:.0f} / {:.0f} mm on a straight track", Track.cant[0], Track.cant[1])); + } + if (curved && velocity > Settings.tight_velocity && Track.radius < Settings.tight_radius) { + found(kind::tight_curve, std::format("radius {:.0f} m with a {} of {:.0f} km/h", Track.radius, given ? "speed limit" : "default speed", velocity)); + } + } + if (auto const most{std::max(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; most > Settings.most_cant) { + found(kind::cant_excess, std::format("cant {:.0f} mm over {:.0f} mm", most, Settings.most_cant)); + } + if (auto const excess{uneven_excess(Track.uneven, Settings)}; false == excess.empty()) { + found(kind::uneven, std::format("uneven {} mm out of range", excess)); + } + if (false == result.empty()) { + result.text += std::format(" (radius {:.0f} m, cant {:.0f} / {:.0f} mm, speed limit {}, damage {})", Track.radius, Track.cant[0], Track.cant[1], + given ? std::format("{:.0f} km/h", Track.velocity) : std::string{"none"}, Track.damage); + } + return result; +} + +summary scan(std::vector const &Tracks, sink const &Log, std::vector const &References, settings const &Settings) { + summary result; + for (auto const &track : Tracks) { + ++result.tracks; + if (track.damage != 0) { + ++result.damage[track.damage]; + } + auto const found{check(track, References, Settings)}; + if (found.empty()) { + continue; + } + ++result.suspicious; + for (auto const kind : found.kinds) { + ++result.counts[static_cast(kind)]; + } + Log(std::format("trackcheck: {}: {}", track.name.empty() ? std::string{"(none)"} : track.name, found.text)); + } + std::string counts; + for (std::size_t kind = 0; kind < result.counts.size(); ++kind) { + append(counts, std::format("{} {}", name_of(static_cast(kind)), result.counts[kind])); + } + Log(std::format("trackcheck: {} rail tracks checked, {} suspicious: {}", result.tracks, result.suspicious, counts)); + std::string damage; + for (auto const &[flags, count] : result.damage) { + append(damage, std::format("{} on {}", flags, count)); + } + Log(std::format("trackcheck: damage flags: {}", damage.empty() ? std::string{"none"} : damage)); + return result; +} + +} // namespace track_check diff --git a/world/TrackCheck.h b/world/TrackCheck.h new file mode 100644 index 000000000..d07b3cb49 --- /dev/null +++ b/world/TrackCheck.h @@ -0,0 +1,96 @@ +/* +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 "McZapkie/derailment.h" +#include "world/TrackUneven.h" + +#include +#include +#include +#include +#include +#include + +// the check of the geometry of the rail tracks of a scenery (physics.trackcheck yes in eu07.ini): what the criteria of +// derailment (McZapkie/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery +// loaded, so a run can tell a faulty scenery from a faulty simulation. one line for a track with all it found +// ("trackcheck: : ..."), and a summary with the count of each kind. the damage flags are only counted: sceneries +// set them for the jolts of a worn track (damage 31 on every track of line 107) +namespace track_check { + +// a rail track as the check sees it +struct track { + std::string name; + double velocity{-1.0}; // the speed limit of the track [km/h], negative when it gives none + double radius{0.0}; // the tightest radius of its curve [m], 0 on a straight one + std::array cant{0.0, 0.0}; // at its ends [mm], positive raising the right rail + double gauge{1.435}; // [m] + int damage{0}; // dtrack_* flags + bool plain{true}; // a plain track, its speed and curve checked; a switch or a crossing has the paths and the + // speeds of its position, only its unevenness and its damage are + track_uneven::attribute uneven; +}; + +// a vehicle the speed limit of a curve is checked for +struct reference { + std::string name; + derailment::vehicle_state vehicle; +}; +// the default vehicles of derailment.h: an EU07 (4 axles, 80 t, 15.9 m, bogies of 3 m, the centre of gravity of its +// 4.35 m high body) and a 4-axle coach (40 t, 24.5 m, bogies of 2.5 m, 4.05 m high), alone, without a .fiz +std::vector const &default_references(); + +struct settings { + // the speed limit of a track which gives none [km/h]: the top speed of the EU07, the trains the default vehicles + // make up run no faster + double default_velocity{125.0}; + double most_cant{160.0}; // [mm], 150 the most of the Polish rules (Id-1), and a margin + double straight_cant{5.0}; // the cant both ends of a straight track have, past which it's cant without a curve [mm] + double tight_radius{40.0}; // a curve tighter than this [m] + double tight_velocity{40.0}; // with a speed limit over this [km/h] + double most_uneven{30.0}; // the value, up, side and dip of the unevenness [mm]: Id-14 lets the poorest track 28 mm + double most_cross{25.0}; // the cross level [mm]: 20 mm in class C of Id-14 +}; + +enum class kind { + overturning, // the speed limit is over the speed a reference vehicle overturns at + climbing, // or over the one its flange climbs the rail at + overturning_default, // the same with the default speed limit, of a track which gives none + climbing_default, + cant_on_straight, // both ends of a straight track have the same cant + cant_excess, // over the most cant + tight_curve, // a curve tighter than the tight radius with a speed limit over the tight velocity + uneven, // the unevenness out of the plausible range + count_ +}; +std::string_view name_of(kind Kind); + +// what the check found on a track +struct findings { + std::vector kinds; + std::string text; // what the log line tells after the name of the track, empty when nothing + bool empty() const { return kinds.empty(); } +}; +findings check(track const &Track, std::vector const &References = default_references(), settings const &Settings = {}); + +struct summary { + int tracks{0}; // checked + int suspicious{0}; // with a line of their own + std::array(kind::count_)> counts{}; + std::map damage; // the tracks of each value of the damage flags, none for 0 + int count(kind const Kind) const { return counts[static_cast(Kind)]; } +}; + +using sink = std::function; +// checks the tracks, logs a line for each one found suspicious and the summary +summary scan(std::vector const &Tracks, sink const &Log, std::vector const &References = default_references(), settings const &Settings = {}); + +} // namespace track_check From 0f61567bcb84cc809618ebe5f7e1aeae1ddebded Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 00:26:18 +0100 Subject: [PATCH 28/59] fix(physics): only the energy of a hit past the buffers of EN 15551 crushes the ends Found running every scenario of the install with physics.collisions new: two locomotives (SU45 117 t, SM42 84 t) put down by calkowo_v2_kontenera inside each other crushed both their ends at 5 km/h right after the start, deeper hit after hit, until both overrode (0.60 m); in baltyk_sdm the coaches of a train pushed into a vehicle derailed at the end of the track (a wall) crushed at 5-8 km/h. Some 50 kJ of relative motion, which the buffers take in with room to spare. The crush went by the closing velocity at the stop of the buffers alone: buffers pressed all the way from the start of the contact (put down overlapping, or knocked onto each other by a hit elsewhere) left the whole hit to the underframes, every step anew. Each pair now counts the energy of its contact (collision::contact_energy): what the springs of the buffers take in while they're pressed and the pair closes in, kept down to what they hold once they spring back, reset when they part. A hit may crush only what it brings to the stop past what the buffers of EN 15551 of both ends would take in, by their BufferCategory (the key now also gives that energy) or 30 kJ a buffer by default: budget = 1/2 mu v^2 - max(0, capacity - absorbed) collision::hit() stops the crush once its work reaches the budget, the rest springs back. The crush of a whole hit thus never takes more than the hit brought past the buffers; a train behind pushing the pair on brings in more through the velocity of the next step. The monitor goes by the same budget. The log of a crush tells the energies. Pressing alone, a locomotive pushing a braked train at a stand, and vehicles put down overlapping don't crush. The crash cases keep crushing: the hits of two masses, EU07 into a 430W, the EN 15227 units at 36 km/h and the 15 km/h PoC cases as before; at 25-40 km/h fewer ends deep in the trains crush (the buffers of the couplings there take in their energy). --- McZapkie/MOVER.h | 2 + McZapkie/Mover.cpp | 23 ++- McZapkie/collision.cpp | 74 ++++++- McZapkie/collision.h | 65 +++++- tests/unit/test_collisions.cpp | 354 +++++++++++++++++++++++++++++++++ 5 files changed, 503 insertions(+), 15 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 7e708d5c8..a2ae1368c 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1304,6 +1304,8 @@ struct TCoupling double hit_duration{0.0}; // physics.collisions monitor: the log told of the crush of this hit of the pair already bool crush_monitored{false}; + // the energy the contact of the pair brought to its buffers, for the budget of the crush + collision::contact_energy contact; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index f33bbb8ed..1efeb597c 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1623,6 +1623,11 @@ bool TMoverParameters::crush_hit(int const End, double const dt) // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts input.dt = monitor ? 1.0 : dt; input.start_velocity = thiscoupler.closing; + // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in + auto const reduced{mass * othermass / (mass + othermass)}; + auto const capacity{collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; + auto const hitvelocity{std::max(closing, thiscoupler.closing)}; + input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity); auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; // the override, by the crush of both ends auto const climbing_of = [&](double const Crush1, double const Crush2) { @@ -1664,7 +1669,6 @@ bool TMoverParameters::crush_hit(int const End, double const dt) { // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push // off the track - auto const reduced{mass * othermass / (mass + othermass)}; auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))}; auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)}; auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))}; @@ -1691,13 +1695,19 @@ bool TMoverParameters::crush_hit(int const End, double const dt) record_hit(thiscoupler, hit.force, hit.duration); record_hit(othercoupler, hit.force, hit.duration); + // the energy the crush took, for both vehicles' count of the contact + thiscoupler.contact.crushed(hit.work); + othercoupler.contact.crushed(hit.work); // what the log tells of the pair, for the analysis of a crush + auto const kinetic{0.5 * reduced * hitvelocity * hitvelocity}; auto const pair = [&]() { return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, " - "closing at {:.1f} km/h at the start of the step", + "closing at {:.1f} km/h at the start of the step; energy {:.0f} kJ of the motion and {:.0f} kJ in the buffers, past the {:.0f} kJ they take in, " + "{:.0f} kJ crushed in the contact", Name, TotalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name, othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush, - secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6); + secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0, + thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0); }; auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { if (Before < collision::crush_mark && After >= collision::crush_mark) @@ -5819,9 +5829,15 @@ void TMoverParameters::ComputeTotalForce(double dt) Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); Couplers[end].CForce = CouplerForce(end, dt); FTrain += Couplers[end].CForce; + // what the buffers of the pair take in, for the budget of the crush (physics.collisions new and monitor) + auto &coupler{Couplers[end]}; + coupler.contact.update(coupler.Dist < 0.0, coupler.CheckCollision, coupler.closing, compression_at(coupler, end), std::max(0.0, -coupler.Dist), dt); } else + { Couplers[end].CForce = 0; + Couplers[end].contact.reset(); + } } FStand += Fb; @@ -11928,6 +11944,7 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde thiscoupler->physics.buffers = collision::buffer_curve(*category, thiscoupler->physics.buffers.progression); } thiscoupler->collision = collision_definition(line); + thiscoupler->collision.buffers = category; if (Index == 0) { diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp index 60bcf4a41..0abdfdd3b 100644 --- a/McZapkie/collision.cpp +++ b/McZapkie/collision.cpp @@ -156,6 +156,51 @@ std::optional buffer_category_of(char const Name) { } } +buffer_category default_buffers(vehicle_kind const Kind) { + return Kind == vehicle_kind::coach ? buffer_category::passenger : buffer_category::A; +} + +double buffer_capacity(end_definition const &Definition, vehicle_kind const Kind) { + // two buffers side by side + return 2.0 * rating(Definition.buffers.value_or(default_buffers(Kind))).energy; +} + +void contact_energy::update(bool const Pressed, bool const Solid, double const Closing, double const Force, double const Compression, double const Dt) { + if (false == Pressed) { + // the buffers apart, the contact is over + reset(); + return; + } + if (Solid) { + // pressed all the way, the buffers take in nothing more + return; + } + auto const force{std::max(Force, 0.0)}; + if (Closing > 0.0) { + m_absorbed += force * Closing * std::max(Dt, 0.0); + } + else if (Closing < 0.0) { + // springing back, they hold no more than their springs pressed in so far + m_absorbed = std::min(m_absorbed, 0.5 * force * std::max(Compression, 0.0)); + } +} + +void contact_energy::crushed(double const Work) { + m_crushed += std::max(Work, 0.0); +} + +double contact_energy::budget(double const Mass, double const Closing, double const Capacity) const { + auto const closing{std::max(Closing, 0.0)}; + // what the buffers of EN 15551 would still take in: the springs of the .fiz taking in more leave no more energy past + // the buffers than the hit has + return 0.5 * std::max(Mass, 0.0) * closing * closing - std::max(0.0, Capacity - m_absorbed); +} + +void contact_energy::reset() { + m_absorbed = 0.0; + m_crushed = 0.0; +} + hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input) { hit_result result; if (Input.velocity <= 0.0 || Input.mass1 <= 0.0 || Input.mass2 <= 0.0 || Input.dt <= 0.0) { @@ -177,7 +222,7 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const auto const elastic_limit = [&](double const Force) { return std::max(0.0, Force - springs) / root; }; { auto const force{std::min(First.curve.force(crush1), Second.curve.force(crush2))}; - if (false == std::isfinite(force) || velocity <= elastic_limit(force)) { + if (false == std::isfinite(force) || velocity <= elastic_limit(force) || false == (Input.budget > 0.0)) { // the steel takes it all: the legacy elastic exchange return result; } @@ -189,6 +234,8 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const auto time{0.0}; auto rebound{false}; auto crushtime{0.0}; + auto work{0.0}; + auto cap{0.0}; // the force the crush went at last while (Input.dt - time > 1e-12) { auto const force1{First.curve.force(crush1)}; auto const force2{Second.curve.force(crush2)}; @@ -205,7 +252,19 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const step = (velocity - limit) * mass / force; change = velocity - limit; } - auto const crush{(velocity - 0.5 * change) * step}; + auto crush{(velocity - 0.5 * change) * step}; + auto spent{false}; + if (work + force * crush > Input.budget) { + // the energy of the hit past the buffers runs out in the slice: the crush goes as far as it takes, the + // buffers of EN 15551 would take in the rest + auto const share{std::clamp((Input.budget - work) / std::max(force * crush, 1e-12), 0.0, 1.0)}; + step *= share; + change *= share; + crush *= share; + spent = true; + } + work += force * crush; + cap = force; // the weaker end gives, both alike when they're alike if (std::abs(force1 - force2) <= 1e-9 * force) { crush1 += 0.5 * crush; @@ -221,14 +280,20 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const time += step; crushtime += step; result.force = std::max(result.force, force); + if (spent) { + result.spent = true; + rebound = true; + break; + } } auto after{velocity}; auto duration{crushtime}; if (rebound) { // the steel springs back with the restitution, the springs push the pair apart over the rest of the step - // under the force the weaker end gives at, as the slices stopped there - result.force = std::max(result.force, springs + velocity * root); + // under the force the weaker end gives at, as the slices stopped there. a crush stopped at the budget: the + // buffers of EN 15551 would have taken in the rest, its force no more than what crushes the end + result.force = std::max(result.force, result.spent ? std::min(springs + velocity * root, cap) : springs + velocity * root); if (velocity > 0.0) { duration += (1.0 + restitution) * velocity * mass / std::max(velocity * root, 1.0); } @@ -239,6 +304,7 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const result.duration = std::min(duration, Input.dt); result.crush1 = crush1 - First.crush; result.crush2 = crush2 - Second.crush; + result.work = work; return result; } diff --git a/McZapkie/collision.h b/McZapkie/collision.h index b51fc6561..4964759af 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include "couplerphysics.h" @@ -17,7 +18,8 @@ http://mozilla.org/MPL/2.0/. // TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: // // crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the -// force the weaker end gives at. past it the end crushes for good: a short peak of force, then a lower plateau as +// force the weaker end gives at. only the energy the hit brings past what the buffers of EN 15551 of both ends take +// in can crush them (contact_energy): a hit the buffers would take, or the push of a train at a stand, never does. past it the end crushes for good: a short peak of force, then a lower plateau as // the structure folds, then it packs down and stiffens (the force-crush curves of the full scale tests of the FRA: // Tyrell et al., IMECE2002-33247). the hit is an impulse limited to that force over the step, so the force never // goes past it and the depth of the crush is the same with any step; the depth stays with the end @@ -64,6 +66,15 @@ enum class vehicle_kind { // do (2 MN of the crash buffers in service) crush_curve default_crush(vehicle_kind Kind); +// the buffers of EN 15551, by their category +enum class buffer_category { + A, // 105 mm, 30 kJ + B, // 105 mm, 50 kJ + C, // 105 mm, 70 kJ + L, // the long stroke, 150 mm + passenger // 110 mm, of the coaches +}; + // the optional keys of the .fiz for an end (BuffCoupl): what's not given comes from the kind of the vehicle struct end_definition { std::optional peak; // FcrushPeak [N] @@ -75,6 +86,7 @@ struct end_definition { std::optional crash_zone; // CrashZone: built to EN 15227 std::optional anticlimber; // AntiClimber std::optional buffer_height; // BufferHeight, of the empty vehicle above the rail [m] + std::optional buffers; // BufferCategory }; vehicle_kind kind_of(bool Powered, bool Passenger, bool CrashZone); crush_curve crush_of(end_definition const &Definition, vehicle_kind Kind); @@ -85,13 +97,6 @@ double buffer_height(end_definition const &Definition, vehicle_kind Kind, double // ---- the buffers, EN 15551 -enum class buffer_category { - A, // 105 mm, 30 kJ - B, // 105 mm, 50 kJ - C, // 105 mm, 70 kJ - L, // the long stroke, 150 mm - passenger // 110 mm, of the coaches -}; struct buffer_rating { double stroke{0.105}; // [m] double energy{30.0e3}; // dynamic energy of one buffer [J] @@ -101,6 +106,45 @@ buffer_rating rating(buffer_category Category); // over the stroke coupler_physics::spring_curve buffer_curve(buffer_category Category, double Progression); std::optional buffer_category_of(char Name); +// the buffers of an end without the category given: of category A, those of a coach of its own category (EN 15551, +// 30 kJ a buffer either way) +buffer_category default_buffers(vehicle_kind Kind); +// the energy the two buffers of an end take in over their stroke, of the category given or the default of the kind [J] +double buffer_capacity(end_definition const &Definition, vehicle_kind Kind); + +// ---- the energy of a hit, for the crush + +// the energy budget of the crush in a contact of two ends. what a hit brings to the stop of the buffers is the kinetic +// energy of the relative motion of the pair there, and what its buffers took in on the way (the springs of the .fiz, +// which may take less than the buffers of EN 15551 would). the buffers of EN 15551 of both ends take in their +// capacity of it first, the crush may take only the rest: +// budget = 1/2 mu v^2 - max(0, capacity - absorbed) +// over the steps of a crush the crush done already is in neither term, so the crush of the whole hit never takes more +// than the hit brought past the buffers. the train behind the pair pushing it on through the crush brings in more: +// it's in the velocity the pair closes in with in the next step. the buffers take in in the stroke under way: the +// buffers pressed and the pair closing in. springing back they keep what they still hold, so a train pushing at a +// stand never builds up what it feeds into their damping. the buffers pressed all the way from the start of the +// contact took in nothing: vehicles put down inside each other, or knocked onto each other by a hit elsewhere, bring +// in only the kinetic energy they close in with +class contact_energy { +public: + // the step of the pair: whether its buffers press, and all the way; the closing velocity [m/s] and the force + // pressing the buffers [N] at the start of the step; how far they're pressed in [m]; the length of the step [s] + void update(bool Pressed, bool Solid, double Closing, double Force, double Compression, double Dt); + // the crush of the hit took the energy [J] + void crushed(double Work); + // the energy the crush may take now, closing in at the velocity [m/s] with the reduced mass [kg], the buffers of + // both ends taking in the capacity [J]; zero or less, the hit stays elastic + double budget(double Mass, double Closing, double Capacity) const; + // what the buffers took in in the stroke under way [J], and the crush in the contact + double absorbed() const { return m_absorbed; } + double crush_work() const { return m_crushed; } + void reset(); + +private: + double m_absorbed{0.0}; + double m_crushed{0.0}; +}; // ---- the hit past the buffers @@ -121,6 +165,9 @@ struct hit_input { // the closing velocity the pair started the step with, before the forces of the step [m/s]; without it (0), the // velocity with what the springs took off it over the step double start_velocity{0.0}; + // the energy the crush may take at most [J] (contact_energy::budget()); none left, the hit stays elastic, and the + // crush stops once it took it, the rest springs back as the buffers would have taken it + double budget{std::numeric_limits::infinity()}; }; struct hit_result { @@ -131,6 +178,8 @@ struct hit_result { double duration{0.0}; // how long that force acted over the step [s] double crush1{0.0}; // added to the end of the first vehicle [m] double crush2{0.0}; // of the second one + double work{0.0}; // the crush took [J] + bool spent{false}; // the crush stopped at the budget }; // the hit of the step: the steel takes the hit elastically up to the force the weaker end gives at, past that the end diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index c08c714dc..0aa7cb037 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "doctest.h" #include "consist.h" +#include "drive.h" #include "vehicle.h" #include "McZapkie/collision.h" #include "McZapkie/MOVER.h" @@ -206,6 +207,49 @@ double locomotive_into_wagon(double const Speed, double const Dt) { return wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush; } +// the energy the crush of both ends of the pair took, by their curves [J] +double crush_energy(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { + return First.crush_curve_at(FirstEnd).energy(0.0, First.Couplers[FirstEnd].crush) + Second.crush_curve_at(SecondEnd).energy(0.0, Second.Couplers[SecondEnd].crush); +} + +// what the buffers of EN 15551 of the two ends take in [J] +double capacity_of(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { + return cl::buffer_capacity(First.Couplers[FirstEnd].collision, First.collision_kind()) + cl::buffer_capacity(Second.Couplers[SecondEnd].collision, Second.collision_kind()); +} + +// the kinetic energy of the relative motion of two vehicles closing in at the velocity [J] +double relative_energy(TMoverParameters const &First, TMoverParameters const &Second, double const Velocity) { + auto const mass{First.TotalMass * Second.TotalMass / (First.TotalMass + Second.TotalMass)}; + return 0.5 * mass * Velocity * Velocity; +} + +struct contact_outcome { + double crush{0.0}; // of both ends [m] + double energy{0.0}; // the crush took [J] + double available{0.0}; // the kinetic energy of the hit past the buffers of EN 15551 [J] + bool derailed{false}; // either vehicle +}; + +// the second vehicle runs into the rear end of the first one standing, Gap metres short of the hit (negative: the +// buffers pressed that far already), unbraked and alone on the track +contact_outcome contact(definition const &Front, definition const &Back, double const Speed, double const Gap, double const Seconds = 5.0, double const Dt = 0.01) { + consist train; + auto &front{train.add(Front)}; + auto &back{train.add(Back, 0, coupling::faux, Speed, Gap)}; + train.run(Seconds, {}, Dt); + contact_outcome result; + result.crush = front->Couplers[end::rear].crush + back->Couplers[end::front].crush; + result.energy = crush_energy(front.mover(), end::rear, back.mover(), end::front); + result.available = std::max(0.0, relative_energy(front.mover(), back.mover(), Speed * kmh) - capacity_of(front.mover(), end::rear, back.mover(), end::front)); + result.derailed = derailed(front.mover()) || derailed(back.mover()); + return result; +} + +// a coach of data/wagon.json of the given mass without its rotating masses +definition coach(double const Mass) { + return definition::load("wagon").set("Param", "M", Mass); +} + } // namespace // ---- the crush curve @@ -702,3 +746,313 @@ TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { CHECK(held.derailed == 0); } } + +// ---- the energy of the hit: what the buffers of EN 15551 take in never crushes (found running every scenario of the +// install: calkowo_v2_kontenera, baltyk_sdm) + +TEST_CASE("collisions: the buffers of EN 15551 of an end take in their energy, of the category given or by the kind") { + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::wagon) == doctest::Approx(60.0e3)); + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::locomotive) == doctest::Approx(60.0e3)); + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::coach) == doctest::Approx(60.0e3)); + CHECK(cl::default_buffers(cl::vehicle_kind::coach) == cl::buffer_category::passenger); + cl::end_definition category_c; + category_c.buffers = cl::buffer_category::C; + CHECK(cl::buffer_capacity(category_c, cl::vehicle_kind::wagon) == doctest::Approx(140.0e3)); + // the key of the .fiz + vehicle wagon{definition::load("wagon").set("BuffCoupl", "BufferCategory", "B")}; + REQUIRE(wagon->Couplers[end::front].collision.buffers.has_value()); + CHECK(*wagon->Couplers[end::front].collision.buffers == cl::buffer_category::B); + CHECK(cl::buffer_capacity(wagon->Couplers[end::rear].collision, wagon->collision_kind()) == doctest::Approx(100.0e3)); +} + +TEST_CASE("collisions: the budget of a contact, by what the hit brings to the buffers") { + cl::contact_energy contact; + // not touching: nothing + contact.update(false, false, 1.0, 0.0, 0.0, 0.01); + CHECK(contact.absorbed() == 0.0); + // pressed in, closing: the springs take in their work + contact.update(true, false, 1.0, 1.0e6, 0.05, 0.01); + CHECK(contact.absorbed() == doctest::Approx(10.0e3)); + // pressed all the way, they take in nothing more + contact.update(true, true, 1.0, 1.4e6, 0.3, 0.01); + CHECK(contact.absorbed() == doctest::Approx(10.0e3)); + // the kinetic energy and what the buffers took, past their capacity + CHECK(contact.budget(40.0e3, 2.0, 60.0e3) == doctest::Approx(0.5 * 40.0e3 * 4.0 + 10.0e3 - 60.0e3)); + // the springs of the .fiz taking in more than the buffers of EN 15551: no more than the kinetic energy + CHECK(contact.budget(40.0e3, 2.0, 5.0e3) == doctest::Approx(0.5 * 40.0e3 * 4.0)); + // springing back they hold no more than their springs pressed in + contact.update(true, false, -0.5, 0.2e6, 0.02, 0.01); + CHECK(contact.absorbed() == doctest::Approx(0.5 * 0.2e6 * 0.02)); + // a train pushing at a stand: the oscillation of the pair never builds the energy up + for (int i = 0; i < 6000; ++i) { + auto const closing{0.05 * std::sin(i * 0.3)}; + contact.update(true, false, closing, 0.3e6 + 1.0e6 * closing, 0.03, 0.01); + } + CHECK(contact.absorbed() < 0.5 * 0.35e6 * 0.03 + 0.35e6 * 0.05 * 0.01 * 12.0); + // parted: a new contact + contact.crushed(5.0e3); + CHECK(contact.crush_work() == doctest::Approx(5.0e3)); + contact.update(false, false, 0.0, 0.0, 0.0, 0.01); + CHECK(contact.absorbed() == 0.0); + CHECK(contact.crush_work() == 0.0); +} + +TEST_CASE("collisions: the crush of a hit takes no more than its energy past the buffers, with any step") { + // two masses at the stop of their buffers from the start (nothing taken in by the springs), the budget of the + // crush taken anew in every step of the hit, as the vehicles take it + struct masses { + double mass1; + double mass2; + }; + constexpr double capacity{120.0e3}; + constexpr double springs{1.2e6}; + for (auto const &[mass1, mass2] : {masses{80.0e3, 80.0e3}, masses{117.0e3, 84.0e3}, masses{300.0e3, 20.0e3}, masses{36.0e3, 41.6e3}}) { + auto const reduced{mass1 * mass2 / (mass1 + mass2)}; + for (auto const speed : {2.0, 5.0, 8.0, 12.0, 20.0, 30.0, 45.0, 60.0}) { + for (auto const dt : {0.001, 0.003, 0.01, 0.02, 0.03}) { + CAPTURE(mass1); + CAPTURE(mass2); + CAPTURE(speed); + CAPTURE(dt); + cl::end_state first{locomotive_curve, 0.0}; + cl::end_state second{wagon_curve, 0.0}; + auto velocity1{speed * kmh}; + auto velocity2{0.0}; + auto work{0.0}; + for (int step = 0; step < 100000; ++step) { + auto const start{velocity1 - velocity2}; + velocity1 -= springs * dt / mass1; + velocity2 += springs * dt / mass2; + auto const closing{velocity1 - velocity2}; + if (closing <= 0.0) { + break; + } + cl::hit_input input; + input.velocity = closing; + input.start_velocity = start; + input.mass1 = mass1; + input.mass2 = mass2; + input.stiffness = 1.4e8; + input.springs = springs; + input.dt = dt; + input.budget = 0.5 * reduced * start * start - capacity; + auto const hit{cl::hit(first, second, input)}; + if (false == hit.crushing) { + break; + } + CHECK(hit.work <= input.budget * (1.0 + 1e-9) + 1e-6); + work += hit.work; + first.crush += hit.crush1; + second.crush += hit.crush2; + velocity1 -= hit.impulse / mass1; + velocity2 += hit.impulse / mass2; + if (hit.velocity <= 0.0) { + break; + } + } + auto const available{std::max(0.0, 0.5 * reduced * (speed * kmh) * (speed * kmh) - capacity)}; + auto const crushed{locomotive_curve.energy(0.0, first.crush) + wagon_curve.energy(0.0, second.crush)}; + CHECK(work <= available + 1.0); + CHECK(crushed <= available * 1.001 + 1.0); + if (available <= 0.0) { + CHECK(first.crush + second.crush == 0.0); + } + } + } + } +} + +TEST_CASE("collisions: the crush of two vehicles takes no more than the energy of the hit past the buffers, with any step") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + struct pair_of { + char const *name; + definition front; + definition back; + }; + for (auto const &[name, front, back] : {pair_of{"EU07 into EU07", definition::fiz("4e_v1/4e"), definition::fiz("4e_v1/4e")}, + pair_of{"SU45 into SM42", definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, + pair_of{"EU07 into a wagon", definition::fiz("430w_v2/430w"), definition::fiz("4e_v1/4e")}}) { + for (auto const speed : {2.0, 5.0, 10.0, 15.0, 20.0, 30.0, 45.0, 60.0}) { + for (auto const dt : {0.001, 0.01, 0.03}) { + CAPTURE(name); + CAPTURE(speed); + CAPTURE(dt); + auto const result{contact(front, back, speed, 0.5, 4.0, dt)}; + // the explicit steps of the springs before the stop rate what they took in a little off. at 0.03 s, 0.5 m a + // step at 60 km/h, the legacy movement of the vehicles past the stop gives the hit energy of its own (the + // crush goes past what it is at 0.01 s and 0.001 s): the budget doesn't bind there, every step of the hit + // is within it (the test of the hit of two masses above), the same crush as before the budget + CHECK(result.energy <= result.available * (dt > 0.02 ? 1.15 : 1.05) + 5.0e3); + if (result.available <= 0.0) { + CHECK(result.crush == 0.0); + } + } + } + } +} + +TEST_CASE("collisions: two locomotives (117 t and 84 t) touching at walking speed don't crush (calkowo_v2_kontenera)") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const su45{definition::fiz("su45_v2/301d")}; + auto const sm42{definition::fiz("sm42_v1/6d1")}; + { + vehicle check{su45}; + CHECK(check->TotalMass == doctest::Approx(117.0e3).epsilon(0.02)); + } + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + for (auto const speed : {5.0, 5.8, 6.0}) { + CAPTURE(speed); + // a hit from a metre away + { + auto const result{contact(sm42, su45, speed, 1.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + // put down by the scenery with the buffers pressed in, up to past their stop, closing in: the log of the run + // had 5.8 km/h at the stop, both ends crushed, deeper hit after hit until both overrode + for (auto const overlap : {0.1, 0.4, 1.0}) { + CAPTURE(overlap); + auto const result{contact(sm42, su45, speed, -overlap, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + } +} + +TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor run into a wall (baltyk_sdm)") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const light{coach(32.0e3)}; + auto const heavy{coach(37.6e3)}; + { + vehicle check{light}; + MESSAGE("the coaches: ", check->TotalMass / 1000.0, " t and ", vehicle{heavy}->TotalMass / 1000.0, " t"); + } + for (auto const speed : {5.0, 8.0}) { + CAPTURE(speed); + // a hit from a metre away, and one with the buffers pressed all the way already, as the coach knocked onto the + // other one by the hit of the train on the vehicle derailed at the end of the track + for (auto const gap : {1.0, -0.25}) { + CAPTURE(gap); + auto const result{contact(light, heavy, speed, gap)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + // the vehicle derailed the legacy way is a wall that the coach runs into + for (auto const gap : {1.0, -0.25}) { + CAPTURE(gap); + consist train; + auto &wall{train.add(light)}; + wall->Derail(END_OF_TRACK); + REQUIRE(derailed(wall.mover())); + auto &running{train.add(heavy, 0, coupling::faux, 5.0, gap)}; + train.run(5.0); + CHECK(wall->Couplers[end::rear].crush + running->Couplers[end::front].crush == 0.0); + CHECK(running->CollisionDerail == NONE); + } +} + +TEST_CASE("collisions: a locomotive pushing a standing braked train at full power doesn't crush") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track const line{0.15, 0.0, test::catenary_3kv}; + // the diesel-electric keeps its full power at a stand (an electric one trips its overload relays there) + for (auto const *path : {"su45_v2/301d"}) { + CAPTURE(path); + consist train; + // four loaded coal wagons, braked in emergency once their brakes are charged + constexpr int wagons{4}; + for (int i = 0; i < wagons; ++i) { + add_mixed(train, 0, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, line); + for (int i = 0; i < wagons; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, line); + // the locomotive behind them, touching, driven forwards into them at full power + auto &locomotive{train.add(definition::fiz(path), 1, coupling::faux, 0.0, 0.0)}; + test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(locomotive.mover()); + for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { + locomotive->DirectionForward(); + } + test::drive(driver, line, 10.0); + auto pushed{0.0}; + auto seconds{0}; // pushing with 100 kN or more + auto const push = [&]() { + auto const force{std::max(0.0, -locomotive->Couplers[end::front].CForce)}; + pushed = std::max(pushed, force); + seconds += force >= 100.0e3; + }; + // the line contactors close at the first position, once their delay and the pressure switch let them + locomotive->IncMainCtrl(1); + for (int i = 0; i < 90 && false == locomotive->StLinFlag; ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { + locomotive->IncMainCtrl(1); + test::drive(driver, line, 1.0); + push(); + } + for (int i = 0; i < 60; ++i) { + test::drive(driver, line, 1.0); + push(); + } + MESSAGE(std::format("{}: pushing at up to {:.0f} kN, {} s at 100 kN or more, at {:.1f} km/h at the end", path, pushed / 1000.0, seconds, locomotive.speed())); + CHECK(pushed > 200.0e3); + CHECK(seconds >= 55); + for (std::size_t i = 0; i < train.size(); ++i) { + CAPTURE(i); + CHECK(crush_of(train[i].mover()) == 0.0); + CHECK_FALSE(derailed(train[i].mover())); + } + } +} + +TEST_CASE("collisions: vehicles put down with their buffers pressed in don't crush") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + for (auto const overlap : {0.1, 0.3, 0.6}) { + CAPTURE(overlap); + for (auto const &[front, back] : {std::pair{definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, std::pair{coach(32.0e3), coach(37.6e3)}, + std::pair{definition::fiz("3wl_v2/3wl"), definition::fiz("4e_v1/4e")}}) { + auto const result{contact(front, back, 0.0, -overlap, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + } +} + +TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { + flag_setting const crashdamage{Global.crash_damage, true}; + model_setting const monitor{global_settings::collision_model::monitor}; + // a hit the buffers take in: the monitor tells of nothing + for (auto const gap : {1.0, -0.4}) { + CAPTURE(gap); + consist train; + train.add(definition::fiz("sm42_v1/6d1")); + train.add(definition::fiz("su45_v2/301d"), 0, coupling::faux, 5.8, gap); + train.run(5.0); + CHECK(train[0]->crush_reports + train[1]->crush_reports == 0); + } + // one past them it does + consist train; + train.add(definition::fiz("4e_v1/4e")); + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + train.run(10.0); + CHECK(train[0]->crush_reports + train[1]->crush_reports == 1); +} From b5a0a8121d5f93078c415224cb7ff36ba21442ad Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 01:00:36 +0100 Subject: [PATCH 29/59] fix(physics): vehicles put down inside each other don't crush; automatic couplers have no side buffers The rerun of calkowo_v2_kontenera with the energy budget still crushed and overrode its two locomotives, at 9-13 km/h: the scenery puts the SM42 onto the SU45 with their middles 2.7 m apart. The springs at the stops of both ends and the neighbours found at either end shake such a pair up past the energy of the buffers. Pressed past the stop of their buffers and the crush of their ends by more than 0.5 m (more than a hit takes them in a step), the pair is inside each other: no crush, the legacy collision pushes them apart, and the log tells it once (Bad scenery: A and B are inside each other ...). An automatic coupler, or its adapter, has no buffers at the side: its draft gear takes in what its springs of the .fiz do, so the budget leaves no EN 15551 capacity to such a pair. The EN57-2000 hitting a standing one at 20 km/h (en57_2000_crush_new) crushes again. The PoC cases of the energy budget, for the record: 15 km/h straight crushes 3 ends (0.18 m) where it crushed 2 (0.16 m), the same empty pushed off; at 25-40 km/h fewer ends deep in the trains crush on the straight, a few more in the curve, the locomotive overrides in all of them. --- McZapkie/MOVER.h | 2 ++ McZapkie/Mover.cpp | 22 ++++++++++++++++++++-- McZapkie/collision.h | 5 +++++ tests/unit/test_collisions.cpp | 15 +++++++++++++++ 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index a2ae1368c..14eb26224 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1306,6 +1306,8 @@ struct TCoupling bool crush_monitored{false}; // the energy the contact of the pair brought to its buffers, for the budget of the crush collision::contact_energy contact; + // the log told of the vehicle at this end being inside this one already + bool inside_reported{false}; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 1efeb597c..f623b933a 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1597,6 +1597,22 @@ bool TMoverParameters::crush_hit(int const End, double const dt) return false; } auto const monitor{Global.collisions == global_settings::collision_model::monitor}; + // put down by the scenery inside each other: pressed past the stop of the buffers and the crush of the ends by more + // than a hit takes them in a step. the legacy collision pushes them apart; their springs, the stops at both ends + // and the neighbours found at either end there make up any closing velocity, not a hit + auto const stop{std::max(thiscoupler.DmaxB + othercoupler.DmaxB, thiscoupler.physics.buffers.travel + othercoupler.physics.buffers.travel) + thiscoupler.crush + othercoupler.crush}; + auto const overlap{-static_cast(Neighbours[End].distance)}; + if (overlap > stop + collision::inside_margin + closing * dt) + { +", Name.c_str(), othervehicle->Name.c_str(), overlap, stop, closing, Neighbours[End].distance, thiscoupler.crush, othercoupler.crush, (int)Derailed, (int)othervehicle->Derailed); + if (false == thiscoupler.inside_reported) + { + thiscoupler.inside_reported = true; + othercoupler.inside_reported = true; + WriteLog(std::format("Bad scenery: {} and {} are inside each other, their buffers pressed {:.2f} m past their stop, no crush", Name, othervehicle->Name, overlap - stop)); + } + return false; + } // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it auto const wall{TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; auto const otherwall{TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; @@ -1623,9 +1639,11 @@ bool TMoverParameters::crush_hit(int const End, double const dt) // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts input.dt = monitor ? 1.0 : dt; input.start_velocity = thiscoupler.closing; - // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in + // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in. an automatic + // coupler (or its adapter) has no buffers at the side: its draft gear takes in what its springs of the .fiz do auto const reduced{mass * othermass / (mass + othermass)}; - auto const capacity{collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; + auto const central{thiscoupler.type() == TCouplerType::Automatic || othercoupler.type() == TCouplerType::Automatic || thiscoupler.has_adapter() || othercoupler.has_adapter()}; + auto const capacity{central ? 0.0 : collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; auto const hitvelocity{std::max(closing, thiscoupler.closing)}; input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity); auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; diff --git a/McZapkie/collision.h b/McZapkie/collision.h index 4964759af..083208d24 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -112,6 +112,11 @@ buffer_category default_buffers(vehicle_kind Kind); // the energy the two buffers of an end take in over their stroke, of the category given or the default of the kind [J] double buffer_capacity(end_definition const &Definition, vehicle_kind Kind); +// vehicles pressed onto each other past the stop of their buffers and the crush of their ends by more than this, more +// than a hit could have taken them in a step, are inside each other: a scenery put them down overlapping. no hit the +// crush could tell anything of, the legacy collision handles them [m] +inline constexpr double inside_margin{0.5}; + // ---- the energy of a hit, for the crush // the energy budget of the crush in a contact of two ends. what a hit brings to the stop of the buffers is the kinetic diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 0aa7cb037..803aafa3b 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -925,6 +925,21 @@ TEST_CASE("collisions: two locomotives (117 t and 84 t) touching at walking spee } } +TEST_CASE("collisions: locomotives put down inside each other don't crush, whatever their springs make of them") { + // calkowo_v2_kontenera puts an SM42 on an SU45 with their middles 2.7 m apart: the springs at the stops of both + // ends and the neighbours found at either end shook them up to 9-13 km/h, past the energy of the buffers + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const speed : {0.0, 10.0, 15.0}) { + CAPTURE(speed); + auto const result{contact(definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d"), speed, -3.0, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + // a hit from a distance at the same speeds crushes past the energy of the buffers + CHECK(contact(definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d"), 20.0, 0.5).crush > 0.0); +} + TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor run into a wall (baltyk_sdm)") { model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; From 00957a7bb5888fb1c4b67a28939f48669a40d611 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 01:04:05 +0100 Subject: [PATCH 30/59] fix(physics): drop a stray line of a debug print left in crush_hit() It broke the build of b5a0a812. --- McZapkie/Mover.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index f623b933a..ab5a513d0 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1604,7 +1604,6 @@ bool TMoverParameters::crush_hit(int const End, double const dt) auto const overlap{-static_cast(Neighbours[End].distance)}; if (overlap > stop + collision::inside_margin + closing * dt) { -", Name.c_str(), othervehicle->Name.c_str(), overlap, stop, closing, Neighbours[End].distance, thiscoupler.crush, othercoupler.crush, (int)Derailed, (int)othervehicle->Derailed); if (false == thiscoupler.inside_reported) { thiscoupler.inside_reported = true; From c554fff1ae59869e61ba56f024851601ad415d68 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 01:17:08 +0100 Subject: [PATCH 31/59] test(physics): the coaches of the Baltyk case at their masses of the log, 36 t and 41.6 t --- tests/unit/test_collisions.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 803aafa3b..37d297f9f 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -943,11 +943,12 @@ TEST_CASE("collisions: locomotives put down inside each other don't crush, whate TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor run into a wall (baltyk_sdm)") { model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; - auto const light{coach(32.0e3)}; - auto const heavy{coach(37.6e3)}; + auto const light{coach(34.3e3)}; + auto const heavy{coach(39.9e3)}; { vehicle check{light}; - MESSAGE("the coaches: ", check->TotalMass / 1000.0, " t and ", vehicle{heavy}->TotalMass / 1000.0, " t"); + CHECK(check->TotalMass == doctest::Approx(36.0e3).epsilon(0.01)); + CHECK(vehicle{heavy}->TotalMass == doctest::Approx(41.6e3).epsilon(0.01)); } for (auto const speed : {5.0, 8.0}) { CAPTURE(speed); @@ -1042,7 +1043,7 @@ TEST_CASE("collisions: vehicles put down with their buffers pressed in don't cru flag_setting const everywhere{Global.coupler_physics_all, physics}; for (auto const overlap : {0.1, 0.3, 0.6}) { CAPTURE(overlap); - for (auto const &[front, back] : {std::pair{definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, std::pair{coach(32.0e3), coach(37.6e3)}, + for (auto const &[front, back] : {std::pair{definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, std::pair{coach(34.3e3), coach(39.9e3)}, std::pair{definition::fiz("3wl_v2/3wl"), definition::fiz("4e_v1/4e")}}) { auto const result{contact(front, back, 0.0, -overlap, 10.0)}; CHECK(result.crush == 0.0); From 5ba9876aec334c673ab33eeb5739a438c9c55670 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 01:41:12 +0100 Subject: [PATCH 32/59] fix(physics): count the steps of the search for the climbing speed in whole steps --- McZapkie/derailment.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index ed55754b9..01ead60b3 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -241,7 +241,9 @@ std::optional climbing_speed(vehicle_state const &Vehicle, track_state c } // in steps of 1 m/s up to the first speed it climbs at, which needn't hold above it, then halving the step constexpr double fastest{200.0}; - for (auto low{balancing}; low < fastest; low += 1.0) { + auto const steps{static_cast(std::ceil(fastest - balancing))}; + for (auto step = 0; step < steps; ++step) { + auto low{balancing + step}; auto high{std::min(low + 1.0, fastest)}; if (false == climbs(high)) { continue; From 386a1df9997b5868ba024a9e738d57217607e110 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:00:31 +0100 Subject: [PATCH 33/59] test(scenarios): with -j N a case clearing the physicslogs of the game dir runs alone, after the others --- tests/scenarios/README.md | 5 +++-- tests/scenarios/run.py | 29 ++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 736e8639a..4dbb7755f 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -143,8 +143,9 @@ Python 3.10+, no extra packages. Options: - `--slow` runs the cases marked `slow` too. Without it, and with no cases named, they are skipped (and listed): each is a whole mission on a big scenery and takes many minutes. A slow case named on the command line always runs. Run them one at a time (`-j 1`): each - simulator loads a whole scenery, and the ones with physicslog on collect every physicslog - written in the game dir meanwhile. + simulator loads a whole scenery. A case on a mission of the base scenery with physicslog on + (`vehicle` given) removes every physicslog written in the game dir meanwhile, so with `-j N` + it runs alone, after the others. - `--seed N` (a number or a word) runs the cases with another seed of the simulator's random numbers (`randomseed`) than the fixed one of the test mode, for a bug that shows up only sometimes: run the case with a few seeds. diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index cd05866ec..dbe13d869 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -666,6 +666,12 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool return "XFAIL" +def exclusive_case(case: dict) -> bool: + """A case on a mission of the base scenery with the physicslog on: it removes every physicslog written + while it ran, those of other cases running at the time too, so it has to run alone.""" + return "vehicle" in case and case.get("physicslog", True) + + def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, seed: str | None = None) -> bool: say(f"\n=== {name}: {case.get('description', '')}") @@ -719,11 +725,15 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float shutil.move(other, out / other.name) # on a mission of the base scenery every train with a driver logs under its own name, the road vehicles # too (250 files and 740 MB after 900 s of Wrzosy): the ones written in this run are removed, nothing - # checks them (so such a case can't share the game dir with another run at the time) + # checks them (so such a case can't share the game dir with another run at the time: main() runs it + # alone, see exclusive_case()). a file still held open by another simulator is left where it is if own_vehicle and with_physicslog: for other in physicslog.parent.glob("*.dat"): - if other.stat().st_mtime >= started: - other.unlink() + try: + if other.stat().st_mtime >= started: + other.unlink() + except OSError as error: + say(f" left {other.name} in the game dir: {error}") # the black box is named after the case scenery too if result.blackbox: result.blackbox = Path(shutil.move(result.blackbox, out / f"{vehicle}.blackbox")) @@ -834,6 +844,12 @@ def main() -> int: for n in names: results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) else: + # a case on a mission of the base scenery removes the physicslogs written while it ran, so it runs + # alone, after the others + alone = [n for n in names if exclusive_case(load_case(n))] + together = [n for n in names if n not in alone] + if alone: + print(f"run alone after the others, they clear the physicslogs of the game dir: {', '.join(alone)}") # each case prints its block when it is done, so parallel output does not interleave def job(n): lines = [] @@ -843,12 +859,15 @@ def main() -> int: status = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) return n, status, lines with ThreadPoolExecutor(max_workers=args.jobs) as pool: - for n in names: + for n in together: print(f"started {n}", flush=True) - for fut in as_completed([pool.submit(job, n) for n in names]): + for fut in as_completed([pool.submit(job, n) for n in together]): n, status, lines = fut.result() print("\n".join(lines), flush=True) results[n] = status + for n in alone: + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, + lambda line, progress=False: print(line, flush=True), args.seed) print(f"\n=== summary ({time.monotonic() - started:.0f}s)") for n in names: From cff1232cce30cd07bf4eb9b597e06a08a6be1c5b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:25:04 +0100 Subject: [PATCH 34/59] refactor: the dates of the scenery wizard and of the editor's backups through std::format, ranges all_of (Sonar S6229, S6197) --- launcher/scenery_wizard.cpp | 4 ++-- scene/scenelayerssave.cpp | 4 ++-- scene/scenenodegroups.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/launcher/scenery_wizard.cpp b/launcher/scenery_wizard.cpp index 7038415d6..e28c52248 100644 --- a/launcher/scenery_wizard.cpp +++ b/launcher/scenery_wizard.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include namespace @@ -400,9 +401,8 @@ bool ui::scenerywizard_panel::create_scenery() return false; } auto const now{std::time(nullptr)}; - char date[32]; std::tm const local{local_tm(now)}; - std::strftime(date, sizeof(date), "%Y-%m-%d", &local); + auto const date{std::format("{:04}-{:02}-{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday)}; char reference[96]; std::snprintf(reference, sizeof(reference), "//$g PUWG1992 %.3f %.3f", m_map.point().x / 1000.0, m_map.point().y / 1000.0); auto const area{range()}; diff --git a/scene/scenelayerssave.cpp b/scene/scenelayerssave.cpp index 8321c1844..7c0b84241 100644 --- a/scene/scenelayerssave.cpp +++ b/scene/scenelayerssave.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "editor/editorFormat.hpp" +#include #include #include #include @@ -1667,9 +1668,8 @@ save_result node_layers::save(std::vector const &Rootstatements, st // without the copy nothing is replaced { auto const now{std::time(nullptr)}; - char stamp[32]; std::tm const local{local_tm(now)}; - std::strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", &local); + auto const stamp{std::format("{:04}{:02}{:02}-{:02}{:02}{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec)}; for (auto const output : written) { auto const filepath{path(output)}; diff --git a/scene/scenenodegroups.cpp b/scene/scenenodegroups.cpp index dd10fc143..e3d1bc463 100644 --- a/scene/scenenodegroups.cpp +++ b/scene/scenenodegroups.cpp @@ -208,7 +208,7 @@ node_groups::update_map() last_switch->track[lastc - 'a'] = track; // all four tracks of the cross switch have to be known before it's assigned - if (!std::all_of(last_switch->track.begin(), last_switch->track.end(), [](TTrack const *Track) { return Track != nullptr; })) + if (!std::ranges::all_of(last_switch->track, [](TTrack const *Track) { return Track != nullptr; })) continue; if (!assign_cross_switch(*last_switch, sw_name, "ac", 0)) From 0e41d27032df27e06c56ba3f4de8fe6ec2787a2e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:44:31 +0100 Subject: [PATCH 35/59] fix(physics): a repaired vehicle is back on the rails, the state of the criteria of derailment cleared resetconsist (Stop and repair consist of the debug panel and of the vehicle window) cleared the damage flags, but kept Derailed, the stretches of the criteria, the distance gathered for them and the report of the monitor. A vehicle once derailed by the criteria and repaired then slid on with their friction after a derailment of the legacy kind, instead of stopping dead, and the friction of the ballast kept holding it whenever it stood. TMoverParameters::rerail() puts a vehicle back on the rails: dtrain_out off, Derailed none, the criteria from scratch, the monitor free to report the track again, a rail vehicle back on the axis of the track. repair_damage() does what resetconsist did to the damage (the flags, the engine damage, the wheel flats, the alarm chain) and rerails it; resetconsist and the road vehicles coming back from the pool of a road point use it. SetDamage taking dtrain_out off rerails the vehicle as well. A vehicle put on a track anew (consistteleport) starts the stretches of the criteria over, they were gathered on the track it left. --- McZapkie/MOVER.h | 5 ++ McZapkie/Mover.cpp | 31 ++++++++ simulation/simulation.cpp | 6 +- tests/unit/test_derailment_vehicle.cpp | 97 ++++++++++++++++++++++++++ vehicle/DynObj.cpp | 3 + world/RoadPoint.cpp | 3 +- 6 files changed, 139 insertions(+), 6 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 1d2280bcc..a6c36168b 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2448,6 +2448,11 @@ class TMoverParameters void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName = nullptr); // height of the centre of gravity above the rail with the load [m] double centre_of_gravity() const; + // the vehicle is back on the rails (resetconsist, SetDamage taking dtrain_out off): not derailed any more, and the + // criteria of derailment start from scratch, so a later derailment goes the way its model has it + void rerail(); + // what resetconsist does to a vehicle: no damage of any kind, the alarm chain released, back on the rails + void repair_damage(); // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other // derailment, which stops it as the legacy model does derailment::outcome Derailed{derailment::outcome::none}; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2dfb8d484..ab42af462 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1584,6 +1584,31 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{})); } +void TMoverParameters::rerail() +{ + ClearFlag(DamageFlag, dtrain_out); + Derailed = derailment::outcome::none; + derailment_monitor.reset(); + derailment_distance = 0.0; + derailment_reported.reset(); + // back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps + // its place on the road) + if (TestFlag(CategoryFlag, 1)) + { + OffsetTrackH = 0.0; + OffsetTrackV = 0.0; + } +} + +void TMoverParameters::repair_damage() +{ + DamageFlag = 0; + EngDmgFlag = 0; + WheelFlat = 0.0; + AlarmChainFlag = false; + rerail(); +} + void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) @@ -13488,7 +13513,13 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do if (CValue2 == 1) OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); if (CValue2 == -1) + { + auto const derailed{TestFlag(DamageFlag, dtrain_out)}; OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); + // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held + if (derailed && false == TestFlag(DamageFlag, dtrain_out)) + rerail(); + } } else if (Command == "Emergency_brake") { diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 87cce81b6..b47bc752b 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -398,12 +398,10 @@ void state_manager::process_commands() { } while (vehicle) { - vehicle->MoverParameters->DamageFlag = 0; - vehicle->MoverParameters->EngDmgFlag = 0; + // no damage, back on the rails with the state of the derailment cleared + vehicle->MoverParameters->repair_damage(); vehicle->MoverParameters->V = 0.000001; // HACK: force vehicle position re-calculation vehicle->MoverParameters->DistCounter = 0.0; - vehicle->MoverParameters->WheelFlat = 0.0; - vehicle->MoverParameters->AlarmChainFlag = false; vehicle->MoverParameters->OffsetTrackH = 0.0; vehicle->MoverParameters->OffsetTrackV = 0.0; diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 6e8e4661a..d6c94b9b0 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -165,6 +165,103 @@ TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { CHECK(still); } +TEST_CASE("derailment: a repaired vehicle is back on the rails") { + // resetconsist (the debug panel's "Stop and repair consist") clears the damage flags; the state of the criteria + // has to go with them, or a vehicle once derailed by the criteria slides on with their friction after a later + // derailment of any other kind, and the friction of the ballast keeps holding it once it stops + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + curve.gradient = 0.02; + vehicle repaired{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 2000; ++step) { + repaired.step(curve); + } + REQUIRE(repaired->Derailed == dr::outcome::overturned); + REQUIRE(repaired->V == 0.0); + repaired->repair_damage(); + CHECK(repaired->DamageFlag == 0); + CHECK(repaired->Derailed == dr::outcome::none); + CHECK(repaired->derailment_distance == 0.0); + CHECK(repaired->OffsetTrackH == 0.0); + CHECK(repaired->OffsetTrackV == 0.0); + + SUBCASE("a derailment of the legacy kind stops it dead, as one never derailed") { + test::track straight; + vehicle fresh{definition::fiz("4e_v1/4e"), 60.0}; + repaired->V = fresh->V; + repaired->AccS = 0.0; + repaired->Derail(TOO_HIGH_SPEED); + fresh->Derail(TOO_HIGH_SPEED); + REQUIRE(repaired->Derailed == dr::outcome::none); + auto const start{fresh->V}; + REQUIRE(start > 10.0); + for (int step = 0; step < 150; ++step) { + repaired.step(straight); + fresh.step(straight); + } + // the legacy model takes g off a derailed vehicle and holds it with a friction 1e20 times its own: 1.1 s from + // 39 km/h. with the friction of the overturned one (half of g on 80 of 96 t) it would still go at 23 km/h + CHECK(fresh->V == doctest::Approx(0.0).epsilon(0.01)); + CHECK(repaired->V == doctest::Approx(fresh->V).epsilon(0.01)); + } + SUBCASE("the friction of the ballast doesn't hold it any more") { + // unbraked on the gradient of 20 per mille it rolls away, at g / 50 less the running resistance + test::track straight; + straight.gradient = 0.02; + for (int step = 0; step < 300; ++step) { + repaired.step(straight); + } + CHECK(std::abs(repaired->V) > 0.4); + CHECK(std::abs(repaired->V) < 3.0 * 0.02 * dr::gravity); + } + SUBCASE("too fast in a curve again it derails again, by the criteria") { + repaired->V = 150.0 * kmh; + curve.gradient = 0.0; + for (int step = 0; step < 20; ++step) { + repaired.step(curve); + } + CHECK(repaired->Derailed == dr::outcome::overturned); + } +} + +TEST_CASE("derailment: SetDamage taking the derailment off puts the vehicle back on the rails") { + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + // another flag taken off leaves it derailed + eu07vehicle->RunCommand("SetDamage", dtrain_engine, 1); + eu07vehicle->RunCommand("SetDamage", dtrain_engine, -1); + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->RunCommand("SetDamage", dtrain_out, -1)); + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); +} + +TEST_CASE("derailment: monitor tells again on the same track after a repair") { + model_setting const monitor{global_settings::derailment_model::monitor}; + test::track curve; + curve.radius = 300.0; + curve.name = "curve_1"; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->derailment_reports == 1); + eu07vehicle->repair_damage(); + CHECK_FALSE(eu07vehicle->derailment_reported.has_value()); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->derailment_reports == 2); +} + TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what the criteria would do") { model_setting const monitor{global_settings::derailment_model::monitor}; test::track curve; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 39ab5c4b6..7f266d099 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -1986,6 +1986,9 @@ void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów break; } + // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) + MoverParameters->derailment_monitor.reset(); + MoverParameters->derailment_distance = 0.0; // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie // zrobiło tego diff --git a/world/RoadPoint.cpp b/world/RoadPoint.cpp index 96eb4814f..ecf39f2ba 100644 --- a/world/RoadPoint.cpp +++ b/world/RoadPoint.cpp @@ -994,8 +994,7 @@ void roadpoint_node::update_spawn(double const Deltatime) auto *vehicle{entry.vehicle}; // it comes back the way it was made: whole, at speed, with the driver told to drive on vehicle->bEnabled = true; - vehicle->MoverParameters->DamageFlag = 0; - vehicle->MoverParameters->EngDmgFlag = 0; + vehicle->MoverParameters->repair_damage(); vehicle->MoverParameters->V = entry.velocity; vehicle->place_on_track(m_lanes.front(), m_offset + 0.5 * vehicle->MoverParameters->Dim.L, false); if (vehicle->Mechanik != nullptr) From 3df78e137ae4bb5cb4bebd227563403620e7f36f Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:44:32 +0100 Subject: [PATCH 36/59] fix(physics): trackcheck tells a curve without a speed limit apart from the defects A track without a speed limit of its own was checked at a default 125 km/h and counted as overturning or a tight curve too fast at the default speed: in Tomaszewo 154 such lines, all of them curves with no limit, the tram tracks of the town (29 to 31 m) among them. A curve without a speed limit is no defect: the drivers go by the signals and the timetable there. It now gets a note of its own, "no speed limit set (not a defect): the curve takes at most X km/h, the overturning speed of EU07", only where that is under the top speed of the EU07, and the summary counts these curves apart from the suspicious tracks, with the slowest speed among them. The tight curve too fast needs a speed limit too. Tram tracks have no category of their own (a tram is a vehicle of the trains' category, on their tracks), so they are checked alike. --- tests/unit/test_track_check.cpp | 42 +++++++++-- world/TrackCheck.cpp | 130 +++++++++++++++++++++++--------- world/TrackCheck.h | 24 ++++-- 3 files changed, 144 insertions(+), 52 deletions(-) diff --git a/tests/unit/test_track_check.cpp b/tests/unit/test_track_check.cpp index ce0424d81..f9f015f96 100644 --- a/tests/unit/test_track_check.cpp +++ b/tests/unit/test_track_check.cpp @@ -52,20 +52,35 @@ TEST_CASE("trackcheck: the speed limit of a curve") { SUBCASE("over the overturning speed of the EU07") { auto const found{tc::check(curve(300.0, critical + 5.0))}; CHECK(has(found, tc::kind::overturning)); - CHECK_FALSE(has(found, tc::kind::overturning_default)); + CHECK_FALSE(has(found, tc::kind::unlimited_curve)); + CHECK(found.defective()); CHECK(found.text.find("over the overturning speed of EU07") != std::string::npos); CHECK(found.text.find("speed limit 113 km/h") != std::string::npos); } SUBCASE("the cant raises it") { CHECK(tc::check(curve(300.0, critical + 5.0, 100.0)).empty()); } - SUBCASE("without a speed limit of its own the default one goes, counted apart") { + SUBCASE("without a speed limit of its own it's no defect, the speed it takes is told") { auto const found{tc::check(curve(300.0, -1.0))}; - CHECK(has(found, tc::kind::overturning_default)); + CHECK(has(found, tc::kind::unlimited_curve)); CHECK_FALSE(has(found, tc::kind::overturning)); - CHECK(found.text.find("default speed 125 km/h") != std::string::npos); + CHECK_FALSE(found.defective()); + CHECK_FALSE(tc::is_defect(tc::kind::unlimited_curve)); + CHECK(found.unlimited_speed == doctest::Approx(critical)); + CHECK(found.text.starts_with("no speed limit set (not a defect): the curve takes at most ")); + CHECK(found.text.find(" km/h, the overturning speed of EU07") != std::string::npos); CHECK(found.text.find("speed limit none") != std::string::npos); } + SUBCASE("nor anything when it takes them at the top speed of the EU07") { + CHECK(tc::check(curve(600.0, -1.0)).empty()); + } + SUBCASE("a tram loop of 30 m without a speed limit is no tight curve too fast") { + // the tram tracks of Tomaszewo (tramwaj106...): no category of their own, no speed limit + auto const found{tc::check(curve(30.0, -1.0))}; + CHECK(found.kinds == std::vector{tc::kind::unlimited_curve}); + CHECK(found.unlimited_speed == doctest::Approx(overturning(30.0))); + CHECK(found.unlimited_speed < 40.0); + } SUBCASE("a closed track (speed 0) is not checked") { CHECK(tc::check(curve(100.0, 0.0)).empty()); } @@ -135,23 +150,34 @@ TEST_CASE("trackcheck: the scan of a scenery") { tracks.push_back(curve(0.0, 100.0)); tracks.back().name = "fine"; tracks.back().damage = 2; + tracks.push_back(curve(30.0, -1.0)); + tracks.back().name = "tram_1"; + tracks.push_back(curve(150.0, -1.0)); + tracks.back().name = "siding_1"; std::vector log; auto const summary{tc::scan(tracks, [&](std::string const &Line) { log.push_back(Line); })}; - CHECK(summary.tracks == 4); + CHECK(summary.tracks == 6); + // the curves without a speed limit are told apart from the defects CHECK(summary.suspicious == 2); + CHECK(summary.unlimited == 2); + CHECK(summary.slowest == doctest::Approx(overturning(30.0))); CHECK(summary.count(tc::kind::overturning) == 1); CHECK(summary.count(tc::kind::cant_on_straight) == 1); CHECK(summary.count(tc::kind::tight_curve) == 0); + CHECK(summary.count(tc::kind::unlimited_curve) == 2); // the damage flags are counted, not told track by track CHECK(summary.damage.at(31) == 2); CHECK(summary.damage.at(2) == 1); - REQUIRE(log.size() == 4); + REQUIRE(log.size() == 7); CHECK(log[0].starts_with("trackcheck: fast: speed limit 140 km/h over the overturning speed of EU07")); CHECK(log[1].starts_with("trackcheck: leaning: cant 50 / 50 mm on a straight track")); CHECK(log[1].ends_with("damage 31)")); - CHECK(log[2].starts_with("trackcheck: 4 rail tracks checked, 2 suspicious: overturning 1; flange climbing 0;")); - CHECK(log[3] == "trackcheck: damage flags: 2 on 1; 31 on 2"); + CHECK(log[2].starts_with("trackcheck: tram_1: no speed limit set (not a defect): the curve takes at most ")); + CHECK(log[3].starts_with("trackcheck: siding_1: no speed limit set (not a defect)")); + CHECK(log[4] == "trackcheck: 6 rail tracks checked, 2 suspicious: overturning 1; flange climbing 0; cant on a straight 1; cant too high 0; tight curve too fast 0; uneven out of range 0"); + CHECK(log[5].starts_with("trackcheck: curves without a speed limit: 2 taking the reference vehicles under 125 km/h (not a defect), the slowest at ")); + CHECK(log[6] == "trackcheck: damage flags: 2 on 1; 31 on 2"); for (auto const &line : log) { CHECK(line.starts_with("trackcheck: ")); } diff --git a/world/TrackCheck.cpp b/world/TrackCheck.cpp index 22bc61861..c0661bf2f 100644 --- a/world/TrackCheck.cpp +++ b/world/TrackCheck.cpp @@ -65,6 +65,64 @@ std::string uneven_excess(track_uneven::attribute const &Uneven, settings const return result; } +// what the check of a track found so far +struct collector { + findings &result; + void add(kind const Kind, std::string const &Text) const { + if (std::ranges::find(result.kinds, Kind) == result.kinds.end()) { + result.kinds.push_back(Kind); + } + append(result.text, Text); + } +}; + +derailment::track_state curve_of(track const &Track) { + // with the cant both ends have at the least + auto const cant{std::min(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; + derailment::track_state result; + result.radius = Track.radius; + result.cant = cant_angle(cant, Track.gauge); + result.gauge = Track.gauge; + return result; +} + +// a speed limit over the speed a reference vehicle overturns or climbs the rail at in the curve +void check_limit(track const &Track, std::vector const &References, collector const &Found) { + auto const curve{curve_of(Track)}; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(curve.radius, curve.cant, reference.vehicle.centre_of_gravity, curve.gauge) * kmh}; + if (overturning > 0.0 && Track.velocity > overturning) { + Found.add(kind::overturning, std::format("speed limit {:.0f} km/h over the overturning speed of {} {:.0f} km/h", Track.velocity, reference.name, overturning)); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, curve)}; climbing.has_value() && Track.velocity > *climbing * kmh) { + Found.add(kind::climbing, std::format("speed limit {:.0f} km/h over the flange climbing speed of {} {:.0f} km/h", Track.velocity, reference.name, *climbing * kmh)); + } + } +} + +// a curve without a speed limit: how fast it takes the reference vehicles, when that's under the unlimited velocity +void check_unlimited(track const &Track, std::vector const &References, settings const &Settings, collector const &Found) { + auto const curve{curve_of(Track)}; + auto slowest{Settings.unlimited_velocity}; + std::string what; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(curve.radius, curve.cant, reference.vehicle.centre_of_gravity, curve.gauge) * kmh}; + if (overturning > 0.0 && overturning < slowest) { + slowest = overturning; + what = std::format("the overturning speed of {}", reference.name); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, curve)}; climbing.has_value() && *climbing * kmh < slowest) { + slowest = *climbing * kmh; + what = std::format("the flange climbing speed of {}", reference.name); + } + } + if (what.empty()) { + return; + } + Found.result.unlimited_speed = slowest; + Found.add(kind::unlimited_curve, std::format("no speed limit set (not a defect): the curve takes at most {:.0f} km/h, {}", slowest, what)); +} + } // namespace std::vector const &default_references() { @@ -81,10 +139,6 @@ std::string_view name_of(kind const Kind) { return "overturning"; case kind::climbing: return "flange climbing"; - case kind::overturning_default: - return "overturning at the default speed"; - case kind::climbing_default: - return "flange climbing at the default speed"; case kind::cant_on_straight: return "cant on a straight"; case kind::cant_excess: @@ -93,56 +147,48 @@ std::string_view name_of(kind const Kind) { return "tight curve too fast"; case kind::uneven: return "uneven out of range"; + case kind::unlimited_curve: + return "curve without a speed limit"; default: return "?"; } } +bool is_defect(kind const Kind) { + return Kind != kind::unlimited_curve; +} + +bool findings::defective() const { + return std::ranges::any_of(kinds, [](kind const Kind) { return is_defect(Kind); }); +} + findings check(track const &Track, std::vector const &References, settings const &Settings) { findings result; - auto const found = [&](kind const Kind, std::string const &Text) { - if (std::find(result.kinds.begin(), result.kinds.end(), Kind) == result.kinds.end()) { - result.kinds.push_back(Kind); - } - append(result.text, Text); - }; + collector const found{result}; auto const curved{Track.radius > 0.0}; auto const given{Track.velocity >= 0.0}; - auto const velocity{given ? Track.velocity : Settings.default_velocity}; if (Track.plain) { - // the speed in the curve, with the cant both ends have at the least - if (curved && velocity > 0.0) { - auto const cant{std::min(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; - derailment::track_state track; - track.radius = Track.radius; - track.cant = cant_angle(cant, Track.gauge); - track.gauge = Track.gauge; - for (auto const &reference : References) { - auto const overturning{derailment::overturning_speed(track.radius, track.cant, reference.vehicle.centre_of_gravity, track.gauge) * kmh}; - if (overturning > 0.0 && velocity > overturning) { - found(given ? kind::overturning : kind::overturning_default, - std::format("{} {:.0f} km/h over the overturning speed of {} {:.0f} km/h", given ? "speed limit" : "default speed", velocity, reference.name, overturning)); - } - if (auto const climbing{derailment::climbing_speed(reference.vehicle, track)}; climbing.has_value() && velocity > *climbing * kmh) { - found(given ? kind::climbing : kind::climbing_default, - std::format("{} {:.0f} km/h over the flange climbing speed of {} {:.0f} km/h", given ? "speed limit" : "default speed", velocity, reference.name, *climbing * kmh)); - } - } + // a closed track (speed 0) isn't run on + if (curved && given && Track.velocity > 0.0) { + check_limit(Track, References, found); + } + if (curved && false == given) { + check_unlimited(Track, References, Settings, found); } // cant held over the whole of a straight track: a transition has it at one end only if (false == curved && std::abs(Track.cant[0]) > Settings.straight_cant && std::abs(Track.cant[1]) > Settings.straight_cant && Track.cant[0] * Track.cant[1] > 0.0) { - found(kind::cant_on_straight, std::format("cant {:.0f} / {:.0f} mm on a straight track", Track.cant[0], Track.cant[1])); + found.add(kind::cant_on_straight, std::format("cant {:.0f} / {:.0f} mm on a straight track", Track.cant[0], Track.cant[1])); } - if (curved && velocity > Settings.tight_velocity && Track.radius < Settings.tight_radius) { - found(kind::tight_curve, std::format("radius {:.0f} m with a {} of {:.0f} km/h", Track.radius, given ? "speed limit" : "default speed", velocity)); + if (curved && given && Track.velocity > Settings.tight_velocity && Track.radius < Settings.tight_radius) { + found.add(kind::tight_curve, std::format("radius {:.0f} m with a speed limit of {:.0f} km/h", Track.radius, Track.velocity)); } } if (auto const most{std::max(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; most > Settings.most_cant) { - found(kind::cant_excess, std::format("cant {:.0f} mm over {:.0f} mm", most, Settings.most_cant)); + found.add(kind::cant_excess, std::format("cant {:.0f} mm over {:.0f} mm", most, Settings.most_cant)); } if (auto const excess{uneven_excess(Track.uneven, Settings)}; false == excess.empty()) { - found(kind::uneven, std::format("uneven {} mm out of range", excess)); + found.add(kind::uneven, std::format("uneven {} mm out of range", excess)); } if (false == result.empty()) { result.text += std::format(" (radius {:.0f} m, cant {:.0f} / {:.0f} mm, speed limit {}, damage {})", Track.radius, Track.cant[0], Track.cant[1], @@ -162,17 +208,27 @@ summary scan(std::vector const &Tracks, sink const &Log, std::vector 0.0) { + ++result.unlimited; + result.slowest = result.slowest > 0.0 ? std::min(result.slowest, found.unlimited_speed) : found.unlimited_speed; + } for (auto const kind : found.kinds) { ++result.counts[static_cast(kind)]; } Log(std::format("trackcheck: {}: {}", track.name.empty() ? std::string{"(none)"} : track.name, found.text)); } std::string counts; - for (std::size_t kind = 0; kind < result.counts.size(); ++kind) { - append(counts, std::format("{} {}", name_of(static_cast(kind)), result.counts[kind])); + for (std::size_t index = 0; index < result.counts.size(); ++index) { + if (auto const kind{static_cast(index)}; is_defect(kind)) { + append(counts, std::format("{} {}", name_of(kind), result.counts[index])); + } } Log(std::format("trackcheck: {} rail tracks checked, {} suspicious: {}", result.tracks, result.suspicious, counts)); + Log(std::format("trackcheck: curves without a speed limit: {} taking the reference vehicles under {:.0f} km/h (not a defect){}", result.unlimited, Settings.unlimited_velocity, + result.unlimited > 0 ? std::format(", the slowest at {:.0f} km/h", result.slowest) : std::string{})); std::string damage; for (auto const &[flags, count] : result.damage) { append(damage, std::format("{} on {}", flags, count)); diff --git a/world/TrackCheck.h b/world/TrackCheck.h index d07b3cb49..e6e99fb2b 100644 --- a/world/TrackCheck.h +++ b/world/TrackCheck.h @@ -23,7 +23,10 @@ http://mozilla.org/MPL/2.0/. // derailment (McZapkie/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery // loaded, so a run can tell a faulty scenery from a faulty simulation. one line for a track with all it found // ("trackcheck: : ..."), and a summary with the count of each kind. the damage flags are only counted: sceneries -// set them for the jolts of a worn track (damage 31 on every track of line 107) +// set them for the jolts of a worn track (damage 31 on every track of line 107). a curve without a speed limit of its +// own is no defect (the drivers go by the signals and the timetable there, the tram loops of a town have none), it is +// only told how fast it takes the reference vehicles, apart from the defects. the rail tracks of trams have no category +// of their own (a tram is a vehicle of the category of the trains, on a track of theirs), so they are checked alike namespace track_check { // a rail track as the check sees it @@ -49,9 +52,9 @@ struct reference { std::vector const &default_references(); struct settings { - // the speed limit of a track which gives none [km/h]: the top speed of the EU07, the trains the default vehicles - // make up run no faster - double default_velocity{125.0}; + // a curve without a speed limit is told of when it takes the reference vehicles slower than this [km/h]: the top + // speed of the EU07, the trains the default vehicles make up run no faster + double unlimited_velocity{125.0}; double most_cant{160.0}; // [mm], 150 the most of the Polish rules (Id-1), and a margin double straight_cant{5.0}; // the cant both ends of a straight track have, past which it's cant without a curve [mm] double tight_radius{40.0}; // a curve tighter than this [m] @@ -63,27 +66,34 @@ struct settings { enum class kind { overturning, // the speed limit is over the speed a reference vehicle overturns at climbing, // or over the one its flange climbs the rail at - overturning_default, // the same with the default speed limit, of a track which gives none - climbing_default, cant_on_straight, // both ends of a straight track have the same cant cant_excess, // over the most cant tight_curve, // a curve tighter than the tight radius with a speed limit over the tight velocity uneven, // the unevenness out of the plausible range + unlimited_curve, // no defect: a curve without a speed limit, which takes the reference vehicles slower than the + // unlimited velocity count_ }; std::string_view name_of(kind Kind); +// whether the kind is a defect of the scenery, rather than a note +bool is_defect(kind Kind); // what the check found on a track struct findings { std::vector kinds; std::string text; // what the log line tells after the name of the track, empty when nothing + double unlimited_speed{0.0}; // the speed a curve without a speed limit takes the reference vehicles at [km/h], 0 when + // not told of bool empty() const { return kinds.empty(); } + bool defective() const; // has a kind which is a defect }; findings check(track const &Track, std::vector const &References = default_references(), settings const &Settings = {}); struct summary { int tracks{0}; // checked - int suspicious{0}; // with a line of their own + int suspicious{0}; // with a defect + int unlimited{0}; // curves without a speed limit told of, defects or not + double slowest{0.0}; // the lowest speed one of them takes the reference vehicles at [km/h], 0 without any std::array(kind::count_)> counts{}; std::map damage; // the tracks of each value of the damage flags, none for 0 int count(kind const Kind) const { return counts[static_cast(Kind)]; } From c774a1ff1c3cff1e2a98de18f848559f6e4fe5a3 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:56:12 +0100 Subject: [PATCH 37/59] fix(physics): a pushed wheel climbs the rail over the distance it rolls, not over a time at a stand check_pushed_off() counted the time Y/Q of the leading wheel stayed over the climbing limit, at any speed: a locomotive at its starting effort pressing a braked rake pushed the empty wagon in front of it off the rails in five steps of 0.01 s without it moving, and an 80 t locomotive running onto a free empty 3WL at 9 km/h pushed it off with the half-sine of its buffer springs (565 kN for some 0.06 s, over the climbing limit past about 400 kN in a curve of 150 m). Nadal's limit is that of a wheel rolling under its angle of attack: the creep of the flange contact turns the friction upwards, helping the flange up. A wheel that doesn't roll has the friction against the lift, and with a flange of 70 degrees and a friction over 1 / tan 70 = 0.36 no lateral force gets it up. So the flange now climbs over the distance the wheels roll with Y/Q over the limit without a break, the 2 m window of the criteria of derailment (the window of EN 14363; the climb distance criteria replaced the 50 ms of AAR Chapter XI for the same reason). A hit counts the distance rolled over the time its peak lasted. A push which takes the whole load off the leading wheels lifts them off the rail, rolling or not: that, held for 0.05 s, still derails the vehicle by the time. collision::pushed_forces() gives Y and Q of the wheel (pushed_ratio() their ratio), pushed_monitor counts the climb over the distance and the lift over the time. Tests: both cases of the review stay on the rails (the ST44 pressing at 386 kN, Y/Q 1.29 in a yard curve of 120 m, the 3WL moving 0.11 m; the EU07 at 9 km/h, 565 kN, Y/Q 1.68 for 8 steps), a heavy train propelling an empty 3WL into a braked rake in a curve of 150 m still pushes it off as it slides on. --- McZapkie/MOVER.h | 5 +- McZapkie/Mover.cpp | 34 ++++-- McZapkie/collision.cpp | 37 +++++-- McZapkie/collision.h | 47 +++++--- tests/unit/test_collisions.cpp | 190 +++++++++++++++++++++++++++++++-- 5 files changed, 273 insertions(+), 40 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 8d8ee6e89..3c1b01ec7 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2491,8 +2491,9 @@ class TMoverParameters // velocities took the hit; the legacy collision takes the rest. physics.collisions monitor: the log tells what the // crush of the whole hit would be, once for a hit, nothing changes, and it returns false bool crush_hit(int End, double dt); - // the force pressing the ends pushes the vehicle off the track (physics.collisions new) - void check_pushed_off(double dt); + // the force pressing the ends pushes the vehicle off the track (physics.collisions new), the step travelled the + // Distance [m]: the flange climbs while the wheels roll on + void check_pushed_off(double dt, double Distance); // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of // derailment.h have it void derail_in_collision(DerailReason Reason, std::string const &Why); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2e5425393..1f6d09875 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1780,7 +1780,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) return true; } -void TMoverParameters::check_pushed_off(double const dt) +void TMoverParameters::check_pushed_off(double const dt, double const Distance) { if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) @@ -1795,7 +1795,9 @@ void TMoverParameters::check_pushed_off(double const dt) vehicle.pivots = BDist; vehicle.axle_base = ADist > 0.0 ? ADist : BDist; - auto holds{false}; + auto climbs{false}; + auto distance{0.0}; + auto lifted{false}; auto duration{0.0}; auto worst{0.0}; auto worstforce{0.0}; @@ -1811,17 +1813,24 @@ void TMoverParameters::check_pushed_off(double const dt) collision::pushed_end pushed; pushed.other_length = other->MoverParameters->Dim.L; pushed.crush = coupler.crush; - // the steady push of the springs over the step, or the peak of a hit for as long as it lasted + // the steady push of the springs over the step, or the peak of a hit for as long as it lasted: the flange climbs + // over the distance the wheels rolled meanwhile, a wheel lifted off the rail goes in a short time, rolling or not for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}}) { pushed.force = force; - auto const ratio{collision::pushed_ratio(vehicle, pushed, RunningShape.R)}; + auto const wheel{collision::pushed_forces(vehicle, pushed, RunningShape.R)}; + auto const ratio{wheel.ratio()}; if (ratio < derailment::climbing_limit) { continue; } - holds = true; - duration = std::max(duration, time); + climbs = true; + distance = std::max(distance, Distance * std::clamp(time / std::max(dt, 1e-9), 0.0, 1.0)); + if (wheel.lifted()) + { + lifted = true; + duration = std::max(duration, time); + } if (ratio > worst) { worst = ratio; @@ -1830,11 +1839,14 @@ void TMoverParameters::check_pushed_off(double const dt) } } } - if (pushed_off_monitor.update(holds, duration)) + if (pushed_off_monitor.update(climbs, distance, lifted, duration)) { - derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in for {:.3f} s, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, {}, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " "springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)", - worstforce / 1000.0, end_name(worstend), pushed_off_monitor.time(), Vel, std::abs(RunningShape.R), std::min(worst, 99.0), + worstforce / 1000.0, end_name(worstend), + lifted ? std::format("its wheels lifted off the rail for {:.3f} s", pushed_off_monitor.time()) + : std::format("the flange climbing over {:.2f} m", pushed_off_monitor.distance()), + Vel, std::abs(RunningShape.R), std::min(worst, 99.0), vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0, compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, Couplers[end::front].crush, Couplers[end::rear].crush)); @@ -2135,7 +2147,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! - check_pushed_off(dt); + check_pushed_off(dt, std::abs(dL)); } // liczone dL, predkosc i przyspieszenie @@ -2212,7 +2224,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! - check_pushed_off(dt); + check_pushed_off(dt, std::abs(dL)); } // liczone dL, predkosc i przyspieszenie auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp index 0abdfdd3b..ef3874b93 100644 --- a/McZapkie/collision.cpp +++ b/McZapkie/collision.cpp @@ -341,9 +341,21 @@ override_result override_of(override_input const &Input) { return result; } +double pushed_wheel::ratio() const { + if (q > 0.0) { + return y / q; + } + return y > 0.0 ? 1e9 : 0.0; +} + double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + return pushed_forces(Vehicle, End, Radius).ratio(); +} + +pushed_wheel pushed_forces(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + pushed_wheel result; if (Vehicle.mass <= 0.0 || End.force <= 0.0) { - return 0.0; + return result; } auto const axles{static_cast(std::max(Vehicle.axles, 1))}; // the axles of the half of the vehicle at the end: its bogie, or its axle @@ -360,17 +372,24 @@ double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double auto const lateral{End.force * angle / half + guiding}; // the force off the height it's carried at pitches the vehicle: the bogie at the end pressed in takes the load off auto const pivots{Vehicle.pivots > 0.0 ? Vehicle.pivots : halflength}; - auto const vertical{wheelload - End.force * eccentricity / (2.0 * half * pivots)}; - return vertical > 0.0 ? lateral / vertical : 1e9; + result.y = lateral; + result.q = wheelload - End.force * eccentricity / (2.0 * half * pivots); + return result; } -bool pushed_monitor::update(bool const Holds, double const Duration) { - if (false == Holds) { - m_time = 0.0; - return false; +bool pushed_monitor::update(bool const Climbs, double const Distance, bool const Lifted, double const Duration) { + auto const climbed{m_climbing.update(Climbs, Distance, climb_distance)}; + if (false == Lifted) { + m_lifted = 0.0; + return climbed; } - m_time += std::max(Duration, 0.0); - return m_time >= pushed_time - 1e-9; + m_lifted += std::max(Duration, 0.0); + return climbed || m_lifted >= lift_time - 1e-9; +} + +void pushed_monitor::reset() { + m_climbing.reset(); + m_lifted = 0.0; } } // namespace collision diff --git a/McZapkie/collision.h b/McZapkie/collision.h index 083208d24..fb719315d 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include "couplerphysics.h" +#include "derailment.h" // what a collision of two vehicles does to them past their buffers (physics.collisions new in eu07.ini, see // TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: @@ -29,9 +30,14 @@ http://mozilla.org/MPL/2.0/. // zone of an end is used up // pushed off the track: the force pressing a vehicle's end acts at an angle to it, the more in a curve and the // deeper the end is crushed, which gives a lateral force on its wheels; acting off the height of the centre of the -// vehicle it lifts its leading wheels. Y / Q over Nadal's limit for long enough and the flange climbs the rail -// (the light wagon between heavy ones goes first, in a curve sooner than on a straight track: EN 15566 takes -// 250 kN of the pair of buffers in a curve of 150 m as the safe push) +// vehicle it lifts its leading wheels. Y / Q over Nadal's limit while the wheels roll on over the window of +// EN 14363 and the flange climbs the rail (the light wagon between heavy ones goes first, in a curve sooner than +// on a straight track: EN 15566 takes 250 kN of the pair of buffers in a curve of 150 m as the safe push). a wheel +// which doesn't roll doesn't climb: Nadal's limit is that of a wheel rolling under its angle of attack, the creep of +// the flange contact turning the friction upwards; standing, the friction holds the flange down, and with a flange +// of 70 degrees and a friction over 1 / tan 70 = 0.36 no lateral force gets it up. so a train pushing at a stand, +// or the short peak of the springs of a hit, never pushes a wheel off. a push that takes the whole load off the +// leading wheels lifts them off the rail, rolling or not: that holding for a short time is enough namespace collision { inline constexpr double gravity{9.81}; // [m/s2] @@ -235,8 +241,12 @@ inline constexpr double straight_angle{0.006}; inline constexpr double crush_angle{0.1}; // the height the force acts at off the height it's carried at, the buffers of the pair not at the same height [m] inline constexpr double eccentricity{0.10}; -// the time Y / Q has to stay over the limit for the flange to climb the rail [s] -inline constexpr double pushed_time{0.05}; +// the distance the wheels have to roll with Y / Q over the limit for the flange to climb the rail: the window of the +// criteria of derailment [m] +inline constexpr double climb_distance{derailment::window}; +// the time the push has to hold the leading wheels off the rail, without any load on them, to lift them over the +// rail [s] +inline constexpr double lift_time{0.05}; struct pushed_vehicle { double mass{0.0}; // with the load, without the rotating masses [kg] @@ -250,19 +260,32 @@ struct pushed_end { double other_length{0.0}; // of the vehicle at that end [m] double crush{0.0}; // of the end [m] }; -// Y / Q of the leading wheel at the end pressed in by the force, in a curve of the radius [m] (0 straight) +// the forces of the leading wheel at the end pressed in by the force, in a curve of the radius [m] (0 straight): its +// lateral force, and its vertical one, none or less when the push lifts it off the rail +struct pushed_wheel { + double y{0.0}; // [N] + double q{0.0}; // [N] + double ratio() const; + bool lifted() const { return q <= 0.0 && y > 0.0; } +}; +pushed_wheel pushed_forces(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); +// Y / Q of that wheel double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); -// the time the condition held, without a break +// the push off the track step by step: how far the wheels rolled with Y / Q over the limit without a break, and how +// long the push held the leading wheels lifted off the rail class pushed_monitor { public: - // true once the condition held for the time it takes the flange to climb, given how long it held in the step [s] - bool update(bool Holds, double Duration); - void reset() { m_time = 0.0; } - double time() const { return m_time; } + // true once the flange climbed the rail, given whether Y / Q held over the limit in the step and the distance the + // wheels rolled while it held [m], and whether the push lifted the wheels and for how long in the step [s] + bool update(bool Climbs, double Distance, bool Lifted, double Duration); + void reset(); + double distance() const { return m_climbing.distance(); } + double time() const { return m_lifted; } private: - double m_time{0.0}; + derailment::stretch m_climbing; + double m_lifted{0.0}; }; } // namespace collision diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 37d297f9f..53bcd4859 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -250,6 +250,29 @@ definition coach(double const Mass) { return definition::load("wagon").set("Param", "M", Mass); } +// Y / Q of the leading wheel of the vehicle at the end pressed in by its coupling, as check_pushed_off() takes it +double pushed_ratio_of(TMoverParameters const &Vehicle, int const End, double const OtherLength, double const Radius) { + cl::pushed_vehicle pushed; + pushed.mass = Vehicle.TotalMass - Vehicle.Mred; + pushed.axles = Vehicle.NAxles > 0 ? Vehicle.NAxles : 4; + pushed.length = Vehicle.Dim.L; + pushed.pivots = Vehicle.BDist; + pushed.axle_base = Vehicle.ADist > 0.0 ? Vehicle.ADist : Vehicle.BDist; + cl::pushed_end end; + end.force = std::max(0.0, (End == end::front ? -1.0 : 1.0) * Vehicle.Couplers[End].CForce); + end.other_length = OtherLength; + end.crush = Vehicle.Couplers[End].crush; + return cl::pushed_ratio(pushed, end, Radius); +} + +// a loaded 430W coal wagon +vehicle &add_loaded(consist &Train, int const Coupling, double const Velocity, double const Gap) { + auto &wagon{Train.add(definition::fiz("430w_v2/430w"), 0, Coupling, Velocity, Gap)}; + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + return wagon; +} + } // namespace // ---- the crush curve @@ -487,12 +510,167 @@ TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of end.force = 600.0e3; CHECK(cl::pushed_ratio(heavy, end, 150.0) < 0.5); - // it has to hold for 0.05 s, however long the steps - cl::pushed_monitor monitor; - CHECK_FALSE(monitor.update(true, 0.03)); - CHECK_FALSE(monitor.update(false, 0.01)); - CHECK_FALSE(monitor.update(true, 0.03)); - CHECK(monitor.update(true, 0.03)); + // past 3 MN on a straight track the push takes the whole load off its leading wheels: they lift off the rail + CHECK_FALSE(cl::pushed_forces(wagon, end, 0.0).lifted()); + end.force = 3.5e6; + CHECK(cl::pushed_forces(wagon, end, 0.0).lifted()); + CHECK(cl::pushed_ratio(wagon, end, 0.0) > 1e8); +} + +TEST_CASE("collisions: the flange climbs while the wheels roll on, a lifted wheel goes in a short time") { + SUBCASE("Y / Q over the limit over 2 m rolled, however long the steps") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.7, false, 0.03)); + CHECK_FALSE(monitor.update(true, 0.7, false, 0.03)); + CHECK(monitor.distance() == doctest::Approx(1.4)); + CHECK(monitor.update(true, 0.7, false, 0.03)); + } + SUBCASE("a break starts it over") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 1.5, false, 0.03)); + CHECK_FALSE(monitor.update(false, 0.1, false, 0.03)); + CHECK_FALSE(monitor.update(true, 1.5, false, 0.03)); + CHECK(monitor.update(true, 0.5, false, 0.03)); + } + SUBCASE("standing, it never climbs, however long the push holds") { + cl::pushed_monitor monitor; + auto climbed{false}; + for (int step = 0; step < 100000; ++step) { + climbed = climbed || monitor.update(true, 0.0, false, 0.01); + } + CHECK_FALSE(climbed); + CHECK(monitor.distance() == 0.0); + } + SUBCASE("the wheels lifted off the rail for 0.05 s, standing or not") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.0, true, 0.03)); + CHECK_FALSE(monitor.update(false, 0.0, false, 0.01)); + CHECK_FALSE(monitor.update(true, 0.0, true, 0.03)); + CHECK(monitor.update(true, 0.0, true, 0.03)); + } + SUBCASE("a reset clears both") { + cl::pushed_monitor monitor; + monitor.update(true, 1.9, true, 0.04); + monitor.reset(); + CHECK(monitor.distance() == 0.0); + CHECK(monitor.time() == 0.0); + CHECK_FALSE(monitor.update(true, 0.05, true, 0.005)); + } +} + +TEST_CASE("collisions: a locomotive at its starting effort against a braked train doesn't push the empty wagon off at a stand") { + // the reviewer's case: an ST44 pressing a rake with an empty two-axle wagon right in front of it, in a yard curve. + // the push is over the climbing limit of the empty wagon, but nothing rolls: a wheel which doesn't roll doesn't + // climb. the time criterion pushed it off in five steps of 0.01 s. the ST44 gives some 390 kN, at the climbing + // limit of the empty wagon in a curve of 150 m: the yard curve is one of 120 m, to be past it + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track line; + line.radius = 120.0; + consist train; + constexpr int wagons{4}; + for (int i = 0; i < wagons; ++i) { + add_loaded(train, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; + empty.hold_brake_pipe(5.0); + train.run(90.0, line); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, line); + auto &locomotive{train.add(definition::fiz("st44_v2/m62-1151"), 1, coupling::faux, 0.0, 0.0)}; + test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(locomotive.mover()); + for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { + locomotive->DirectionForward(); + } + test::drive(driver, line, 10.0); + auto const start{empty->DistCounter}; + auto pushed{0.0}; + auto worst{0.0}; + auto const watch = [&]() { + pushed = std::max(pushed, -locomotive->Couplers[end::front].CForce); + worst = std::max(worst, pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, line.radius)); + }; + // the line contactors close at the first position, once their delay and the pressure switch let them + locomotive->IncMainCtrl(1); + for (int i = 0; i < 90 && false == locomotive->StLinFlag; ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { + locomotive->IncMainCtrl(1); + test::drive(driver, line, 1.0); + watch(); + } + for (int i = 0; i < 60; ++i) { + test::drive(driver, line, 1.0); + watch(); + } + auto const rolled{(empty->DistCounter - start) * 1000.0}; + MESSAGE(std::format("ST44 pushing at up to {:.0f} kN, the empty 3WL at Y/Q {:.2f}, rolled {:.3f} m", pushed / 1000.0, worst, rolled)); + REQUIRE(worst >= derailment::climbing_limit); + CHECK(rolled < 0.5); + CHECK_FALSE(derailed(empty.mover())); + CHECK(empty->CollisionDerail == NONE); +} + +TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn't push it off with the peak of the springs") { + // the reviewer's case: an 80 t locomotive onto a free empty 3WL in a curve of 150 m. the springs of the buffers + // press past the climbing limit for some 0.06 s, the wagon rolls a few centimetres meanwhile + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track curve; + curve.radius = 150.0; + consist train; + auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 9.0, 0.5)}; + auto pushed{0.0}; + auto worst{0.0}; + auto over{0}; // steps past the climbing limit + for (int step = 0; step < 500; ++step) { + train.step(curve); + pushed = std::max(pushed, empty->Couplers[end::rear].CForce); + auto const ratio{pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, curve.radius)}; + worst = std::max(worst, ratio); + over += ratio >= derailment::climbing_limit; + } + MESSAGE(std::format("EU07 at 9 km/h onto the empty 3WL: up to {:.0f} kN, Y/Q {:.2f}, {} steps of 0.01 s past the limit, the wagon at {:.1f} km/h", pushed / 1000.0, worst, over, + empty.speed())); + REQUIRE(worst >= derailment::climbing_limit); + REQUIRE(over >= 5); + CHECK_FALSE(derailed(empty.mover())); + CHECK_FALSE(derailed(locomotive.mover())); +} + +TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a curve pushes it off as it rolls on") { + // the genuine push off: the empty 3WL leading a heavy train at 15 km/h, the train pressing it on into a braked + // rake through the curve while it all slides along + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track curve; + curve.radius = 150.0; + consist train; + constexpr int standing{4}; + for (int i = 0; i < standing; ++i) { + add_loaded(train, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, curve); + for (int i = 0; i < standing; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, curve); + auto &empty{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux, 15.0, 1.0)}; + train.add(definition::fiz("4e_v1/4e"), 0, consist::full_coupling, 15.0, 0.0); + for (int i = 0; i < 6; ++i) { + add_loaded(train, consist::full_coupling, 15.0, 0.0); + } + auto const start{empty->DistCounter}; + train.run(10.0, curve); + MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.mover()), empty->CollisionDerail == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", + (empty->DistCounter - start) * 1000.0)); + CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); } // ---- the model of eu07.ini From d9c72e3d7cef083631ff9f7d2c0e804e9eab7171 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:56:12 +0100 Subject: [PATCH 38/59] fix(physics): a repaired vehicle has its crushed ends rebuilt and its collision derailment cleared Neither resetconsist nor the repair of a coupler cleared what a collision left: the crush of the ends (which keeps shifting the stop of the buffers in CouplerForce() and in the pair input of the coupler physics, so the next hit of the repaired consist started past it and sooner over the override threshold), the energy of the contact, the hit of the step and the reports of the log; nor the reason of a derailment in a collision and the state of the push off. repair_damage() rebuilds both ends of the vehicle, rerail() clears CollisionDerail and the push off monitor along with the state of the criteria of derailment (so SetDamage taking dtrain_out off does as well), and the repair of a coupler rebuilds its end, the crush past the draw gear having torn it off. --- McZapkie/Mover.cpp | 25 +++++++++++++-- tests/unit/test_collisions.cpp | 58 ++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 1f6d09875..14c7fadef 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1856,13 +1856,26 @@ void TMoverParameters::check_pushed_off(double const dt, double const Distance) namespace { -// the coupler as good as new, the vehicle without the coupler damage (and the emergency braking of the torn brake -// hose) once neither of its couplers is broken +// the end as it was built (physics.collisions new): not crushed, and nothing of a contact or a hit kept +void restore_end(TCoupling &Coupler) +{ + Coupler.crush = 0.0; + Coupler.contact.reset(); + Coupler.hit_handled = false; + Coupler.hit_force = 0.0; + Coupler.hit_duration = 0.0; + Coupler.crush_monitored = false; + Coupler.inside_reported = false; +} + +// the coupler as good as new, its end with it (the crush that tore the draw gear off), the vehicle without the coupler +// damage (and the emergency braking of the torn brake hose) once neither of its couplers is broken void repair(TMoverParameters &Vehicle, TCoupling &Coupler) { Coupler.broken = false; Coupler.stretch_duration = 0.f; Coupler.physics_state.couple(); + restore_end(Coupler); if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) { return; @@ -1979,6 +1992,9 @@ void TMoverParameters::rerail() derailment_monitor.reset(); derailment_distance = 0.0; derailment_reported.reset(); + // nor derailed in a collision + CollisionDerail = NONE; + pushed_off_monitor.reset(); // back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps // its place on the road) if (TestFlag(CategoryFlag, 1)) @@ -1994,6 +2010,11 @@ void TMoverParameters::repair_damage() EngDmgFlag = 0; WheelFlat = 0.0; AlarmChainFlag = false; + // the crushed ends rebuilt + for (auto &coupler : Couplers) + { + restore_end(coupler); + } rerail(); } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 53bcd4859..3dead8771 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -673,6 +673,64 @@ TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); } +// ---- recovery + +TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on the rails") { + // resetconsist: the crush of the ends shifted the stop of the buffers, the next hit of the repaired consist would + // have started from it; and a vehicle derailed in a collision kept its reason and the state of the push + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + consist train; + auto &wagon{add_loaded(train, coupling::faux, 0.0, 0.0)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 30.0, 0.5)}; + train.run(3.0); + REQUIRE(wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush > cl::override_crush); + REQUIRE((derailed(wagon.mover()) || derailed(locomotive.mover()))); + for (auto *vehicle : {&wagon, &locomotive}) { + auto &mover{vehicle->mover()}; + mover.repair_damage(); + CHECK(mover.DamageFlag == 0); + CHECK(mover.Derailed == derailment::outcome::none); + CHECK(mover.CollisionDerail == NONE); + CHECK(mover.pushed_off_monitor.distance() == 0.0); + CHECK(mover.pushed_off_monitor.time() == 0.0); + for (auto const &coupler : mover.Couplers) { + CHECK(coupler.crush == 0.0); + CHECK(coupler.contact.absorbed() == 0.0); + CHECK(coupler.contact.crush_work() == 0.0); + CHECK_FALSE(coupler.hit_handled); + CHECK(coupler.hit_force == 0.0); + CHECK_FALSE(coupler.crush_monitored); + CHECK_FALSE(coupler.inside_reported); + } + } +} + +TEST_CASE("collisions: the repair of a coupler torn off by the crush rebuilds its end") { + vehicle wagon{definition::fiz("430w_v2/430w")}; + auto &coupler{wagon->Couplers[end::rear]}; + coupler.crush = 0.3; + coupler.broken = true; + coupler.hit_force = 2.0e6; + SetFlag(wagon->DamageFlag, dtrain_coupling); + REQUIRE(wagon->repair_coupler(end::rear)); + CHECK(coupler.crush == 0.0); + CHECK(coupler.hit_force == 0.0); + CHECK_FALSE(coupler.broken); + CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_coupling)); +} + +TEST_CASE("collisions: SetDamage taking the derailment off clears the collision's") { + vehicle wagon{definition::fiz("3wl_v2/3wl")}; + wagon->derail_in_collision(COLLISION_PUSHED_OFF, "test"); + REQUIRE(wagon->CollisionDerail == COLLISION_PUSHED_OFF); + REQUIRE(wagon->Derailed == derailment::outcome::off_rails); + wagon->RunCommand("SetDamage", dtrain_out, -1); + CHECK(wagon->CollisionDerail == NONE); + CHECK(wagon->Derailed == derailment::outcome::none); + CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_out)); +} + // ---- the model of eu07.ini TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush with new") { From 3ae8d4e72ed13d9d723ffc4546cfab393eda23d0 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 08:54:00 +0100 Subject: [PATCH 39/59] fix(scripting): typed scenery handles, sandbox keys from eu07.ini only, GCC 13 build - the scenery API (eu07.events) hands out a full userdata of its own locked metatable for each kind of object (event, track, isolated, vehicle, memcell), checked with luaL_checkudata: a handle of another kind, a light userdata or any other value is a Lua error, not an object taken for another. nil stays "no object". one object has one handle while the script holds it, so handles compare and key tables as before. event handlers get their handles built inside lua_cpcall, and nil for no activator - memcell_values keeps its text as a std::string: the text of a number was read from a stack slot popped before use - newproxy is gone from the sandboxed libraries - a config block of a scenery no longer changes what only eu07.ini sets (lua.fulllibraries, execonexit, extcam.cmd/rec, screenshotsdir, network.server/client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport, python/luascreens/wasm.enabled): kept before its keys are read, put back before FinalizeConfig(), each attempt logged - open_file_library() iterates luaL_Reg instead of a std::pair GCC 13 deduces as a pair of an array and a function --- CMakeLists.txt | 1 + script_screens_doc.md | 13 ++- scripting/lua.cpp | 73 +++++++++----- scripting/lua.h | 4 +- scripting/luasandbox.cpp | 87 ++++++++++++++++- scripting/luasandbox.h | 33 +++++++ simulation/simulationstateserializer.cpp | 5 +- tests/unit/test_ini_only_settings.cpp | 116 +++++++++++++++++++++++ tests/unit/test_lua_sandbox.cpp | 110 ++++++++++++++++++++- utilities/Globals.cpp | 17 +++- utilities/Globals.h | 10 +- utilities/inionlysettings.cpp | 82 ++++++++++++++++ utilities/inionlysettings.h | 55 +++++++++++ 13 files changed, 571 insertions(+), 35 deletions(-) create mode 100644 tests/unit/test_ini_only_settings.cpp create mode 100644 utilities/inionlysettings.cpp create mode 100644 utilities/inionlysettings.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b73b0805..eb3e12aff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -541,6 +541,7 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/inionlysettings.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" diff --git a/script_screens_doc.md b/script_screens_doc.md index 435706fe4..7ebf14caf 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -221,7 +221,13 @@ and works with memcells, tracks and vehicles through the table `eu07.events` (`e `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; - a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on - loading. An event handler that fails is logged with the name of the event, and the simulation goes on. + loading. An event handler that fails is logged with the name of the event, and the simulation goes on; +- the events, tracks, isolated circuits, memcells and vehicles the functions give (`event_find`, `track_find`, + `memcell_find`, the event and the vehicle an event handler gets...) are handles of their kind: equal for the same + object, usable as keys of a table, and taken only where that kind goes. Another kind, or any other value, is an + error (`bad argument #1 to 'memcell_update' (eu07.memcell expected, got userdata)`); `nil`, which the find + functions give for a missing object, is taken as no object, as before. An event run without a vehicle gives its + handler `nil` for the vehicle. Instead of `io`, a scenery script reads and writes files through `eu07`, as the Lua screens read theirs: @@ -257,3 +263,8 @@ again: | key | default | meaning | |---------------------|---------|------------------------------------------------------------------------------------------| | `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | + +Only `eu07.ini` sets it: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set +the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, +`extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, +`feedbackmode`, `feedbackport`, `python.enabled`, `luascreens.enabled` and `wasm.enabled`. diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 7079bb2c3..2011413b5 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -18,6 +18,9 @@ lua::lua() // lua.fulllibraries in eu07.ini opens the rest when the scenery loads its first script (interpret()) lua_sandbox::open_safe_libraries(state); lua_sandbox::open_clock_library(state); + // the events, tracks, isolated circuits, vehicles and memcells a script holds: a userdata of a metatable of each + // kind, which the functions check + lua_sandbox::open_handles(state); static constexpr luaL_Reg api[] = { @@ -100,14 +103,33 @@ void lua::unref(lua_State *L, const int ref) luaL_unref(L, LUA_REGISTRYINDEX, ref); } +namespace { + +struct event_call { + int handler; + basic_event *event; + TDynamicObject *activator; +}; + +// calls the handler of the event (event_call) with the handles of the event and its activator (nil when there is none) +int call_handler(lua_State *L) +{ + auto const &call = *static_cast(lua_touserdata(L, 1)); + lua_rawgeti(L, LUA_REGISTRYINDEX, call.handler); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, call.event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::vehicle, call.activator); + lua_call(L, 2, 0); + return 0; +} + +} // namespace + /// Executes the callback function of an event created with `scriptapi_event_create`. void lua::dispatch_event(lua_State *L, const int handler, basic_event *event, const TDynamicObject *activator) { - lua_rawgeti(L, LUA_REGISTRYINDEX, handler); - lua_pushlightuserdata(L, event); - lua_pushlightuserdata(L, const_cast(activator)); - // in protected mode: a handler that fails is logged, and the simulation goes on - if (lua_pcall(L, 2, 0, 0) != 0) { + event_call call{handler, event, const_cast(activator)}; + // in protected mode, the handles made as well: a handler that fails is logged, and the simulation goes on + if (lua_cpcall(L, call_handler, &call) != 0) { auto const *error = lua_tostring(L, -1); ErrorLog("lua: event " + (event ? event->m_name : std::string("?")) + ": " + (error ? error : "unknown error"), logtype::lua); lua_pop(L, 1); @@ -133,12 +155,17 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) // For negative indices, we need to account for the extra item that is the key name/value extracted from the table. if (idx < 0) idx--; - // no text in the table is an empty one: the memcell and the vehicle take the text as a string + luaL_checktype(L, idx, LUA_TTABLE); + // no text in the table is an empty one: the memcell and the vehicle take the text as a string. copied: the text of + // a number is made on the stack, and gone with it memcell_values mc{"", 0.0, 0.0}; lua_pushstring(L, "str"); lua_gettable(L, idx); - if (lua_isstring(L, -1)) - mc.str = lua_tostring(L, -1); + if (lua_isstring(L, -1)) { + std::size_t length = 0; + auto const *text = lua_tolstring(L, -1, &length); + mc.str.assign(text, length); + } lua_pop(L, 1); lua_pushstring(L, "num1"); lua_gettable(L, idx); @@ -167,7 +194,7 @@ int lua::scriptapi_event_create(lua_State *L) event->m_delayrandom = randomdelay; if (simulation::Events.insert(event)) { - lua_pushlightuserdata(L, event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, event); return 1; } return 0; @@ -179,7 +206,7 @@ int lua::scriptapi_event_find(lua_State *L) basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) { - lua_pushlightuserdata(L, foundevent); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, foundevent); return 1; } ErrorLog("lua: missing event: " + name); @@ -196,7 +223,7 @@ int lua::scriptapi_event_exists(lua_State *L) int lua::scriptapi_event_getname(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); if (event) { lua_pushstring(L, event->m_name.c_str()); @@ -207,8 +234,8 @@ int lua::scriptapi_event_getname(lua_State *L) int lua::scriptapi_event_dispatch(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); - auto *activator = static_cast(lua_touserdata(L, 2)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); if (event) simulation::Events.AddToQuery(event, activator, delay); @@ -218,7 +245,7 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { std::string name = luaL_checkstring(L, 1); - auto *activator = static_cast(lua_touserdata(L, 2)); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) @@ -234,7 +261,7 @@ int lua::scriptapi_track_find(lua_State *L) TTrack *track = simulation::Paths.find(name); if (track) { - lua_pushlightuserdata(L, track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, track); return 1; } ErrorLog("lua: missing track: " + name); @@ -243,7 +270,7 @@ int lua::scriptapi_track_find(lua_State *L) int lua::scriptapi_track_isoccupied(lua_State *L) { - auto *track = static_cast(lua_touserdata(L, 1)); + auto *track = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track); if (track) { lua_pushboolean(L, !track->IsEmpty()); @@ -271,7 +298,7 @@ int lua::scriptapi_isolated_find(lua_State *L) TIsolated *isolated = TIsolated::Find(name); if (isolated) { - lua_pushlightuserdata(L, isolated); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::isolated, isolated); return 1; } ErrorLog("lua: missing isolated: " + name); @@ -280,7 +307,7 @@ int lua::scriptapi_isolated_find(lua_State *L) int lua::scriptapi_isolated_isoccupied(lua_State *L) { - auto *isolated = static_cast(lua_touserdata(L, 1)); + auto *isolated = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::isolated); if (isolated) { lua_pushboolean(L, isolated->Busy()); @@ -304,7 +331,7 @@ int lua::scriptapi_isolated_isoccupied_n(lua_State *L) int lua::scriptapi_train_getname(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); if (dyn && dyn->Mechanik) { lua_pushstring(L, dyn->Mechanik->TrainName().c_str()); @@ -315,7 +342,7 @@ int lua::scriptapi_train_getname(lua_State *L) int lua::scriptapi_dynobj_putvalues(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); auto [str, num1, num2] = get_memcell_values(L, 2); if (!dyn) return 0; @@ -333,7 +360,7 @@ int lua::scriptapi_memcell_find(lua_State *L) TMemCell *mc = simulation::Memory.find(str); if (mc) { - lua_pushlightuserdata(L, mc); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, mc); return 1; } ErrorLog("lua: missing memcell: " + str); @@ -342,7 +369,7 @@ int lua::scriptapi_memcell_find(lua_State *L) int lua::scriptapi_memcell_read(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); push_memcell_values(L, mc); return 1; } @@ -359,7 +386,7 @@ int lua::scriptapi_memcell_read_n(lua_State *L) int lua::scriptapi_memcell_update(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); auto [str, num1, num2] = get_memcell_values(L, 2); if (mc) mc->UpdateValues(str, num1, num2, diff --git a/scripting/lua.h b/scripting/lua.h index a0a2b9333..dc28a01e4 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -3,10 +3,12 @@ #include #include "scripting/luasandbox.h" +#include + class basic_event; class TMemCell; class TDynamicObject; -struct memcell_values { const char *str; double num1; double num2; }; +struct memcell_values { std::string str; double num1; double num2; }; class lua { diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index bf6ab3961..16e7f70ba 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreenrules.h" #include +#include #include #include #include @@ -76,8 +77,9 @@ void open_safe_libraries(lua_State *L) open_library(L, luaopen_string, LUA_STRLIBNAME); open_library(L, luaopen_math, LUA_MATHLIBNAME); open_library(L, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) + // what reaches files or loads code, and newproxy: a userdata of a metatable of the script's own, whose __gc LuaJIT + // runs without the hooks (the instruction limit of the Lua screens), at any allocation and in lua_close + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require", "newproxy"}) { lua_pushnil(L); lua_setglobal(L, name); @@ -430,8 +432,9 @@ void open_file_library(lua_State *L, file_folders const *Folders) lua_pushvalue(L, -1); lua_setglobal(L, "eu07"); } - for (auto const &[name, function] : {std::pair{"read_file", api_read_file}, std::pair{"write_file", api_write_file}, - std::pair{"read_data_file", api_read_data_file}}) + // luaL_Reg, not std::pair: GCC deduces std::pair{"read_file", api_read_file} as a pair of an array and a function + static constexpr luaL_Reg functions[]{{"read_file", api_read_file}, {"write_file", api_write_file}, {"read_data_file", api_read_data_file}}; + for (auto const &[name, function] : functions) { lua_pushlightuserdata(L, const_cast(Folders)); lua_pushcclosure(L, function, 1); @@ -440,4 +443,80 @@ void open_file_library(lua_State *L, file_folders const *Folders) lua_pop(L, 1); } +namespace +{ + +constexpr std::array handle_names{"eu07.event", "eu07.track", "eu07.isolated", "eu07.vehicle", "eu07.memcell"}; +// the addresses are the keys of the handles of each kind in the registry: the objects, to their userdata +constexpr std::array handle_cache_keys{}; + +void *cache_key(handle_kind const Kind) +{ + return const_cast(&handle_cache_keys[static_cast(Kind)]); // NOSONAR: the address is only a key +} + +} // namespace + +char const *handle_name(handle_kind const Kind) +{ + return handle_names[static_cast(Kind)]; +} + +void open_handles(lua_State *L) +{ + for (std::size_t idx = 0; idx < handle_names.size(); ++idx) + { + auto const kind{static_cast(idx)}; + luaL_newmetatable(L, handle_name(kind)); + // getmetatable() of a handle gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); + lua_pop(L, 1); + // the handles made, weak: a handle the script dropped is collected, and made again when asked for + lua_pushlightuserdata(L, cache_key(kind)); + lua_newtable(L); + lua_createtable(L, 0, 1); + lua_pushliteral(L, "v"); + lua_setfield(L, -2, "__mode"); + lua_setmetatable(L, -2); + lua_rawset(L, LUA_REGISTRYINDEX); + } +} + +void push_handle(lua_State *L, handle_kind const Kind, void *Object) +{ + if (Object == nullptr) + { + lua_pushnil(L); + return; + } + lua_pushlightuserdata(L, cache_key(Kind)); + lua_rawget(L, LUA_REGISTRYINDEX); + lua_pushlightuserdata(L, Object); + lua_rawget(L, -2); + if (false == lua_isnil(L, -1)) + { + // the cache, the handle + lua_remove(L, -2); + return; + } + lua_pop(L, 1); + *static_cast(lua_newuserdata(L, sizeof(void *))) = Object; + luaL_getmetatable(L, handle_name(Kind)); + lua_setmetatable(L, -2); + lua_pushlightuserdata(L, Object); + lua_pushvalue(L, -2); + lua_rawset(L, -4); + lua_remove(L, -2); +} + +void *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + if (lua_isnoneornil(L, Index)) + { + return nullptr; + } + return *static_cast(luaL_checkudata(L, Index, handle_name(Kind))); +} + } // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h index 5f57c62af..dfb1cd024 100644 --- a/scripting/luasandbox.h +++ b/scripting/luasandbox.h @@ -98,4 +98,37 @@ struct file_folders // Folders, read on every call: Folders is to outlive the state void open_file_library(lua_State *L, file_folders const *Folders); +// the objects of the simulation a scenery script holds (eu07.events): each kind is a userdata of a metatable of its +// own, so a function given the handle of another kind, a light userdata or anything else raises a Lua error, and never +// takes one object for another. the objects outlive the state (the scenery's events, tracks, memcells and isolated +// track circuits, and its vehicles, which the game takes off the tracks but doesn't delete) +enum class handle_kind +{ + event, + track, + isolated, + vehicle, + memcell +}; + +// the name of the metatable of the kind, as the errors give it ("eu07.memcell expected, got userdata") +char const *handle_name(handle_kind Kind); + +// makes the metatables of the handles; once, before the first handle. a script can't reach them (getmetatable gives +// false) +void open_handles(lua_State *L); + +// pushes the handle of Object, of the kind, or nil for nullptr. one object has one handle while the script holds it: +// the handles of an object found twice are equal, and the same key of a table +void push_handle(lua_State *L, handle_kind Kind, void *Object); + +// the object of the handle at Index: nullptr for nil or nothing (what the find functions give for a missing object), +// a Lua error (bad argument) for anything else than a handle of the kind +void *check_handle(lua_State *L, int Index, handle_kind Kind); + +template Type_ *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + return static_cast(check_handle(L, Index, Kind)); +} + } // namespace lua_sandbox diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index c39870600..b93c69f2d 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -362,8 +362,9 @@ state_serializer::deserialize_camera( cParser &Input, scene::scratch_data &Scrat void state_serializer::deserialize_config( cParser &Input, scene::scratch_data &Scratchpad ) { - // config parameters (re)definition - Global.ConfigParse( Input ); + // config parameters (re)definition, but for what only eu07.ini sets: programs to run, connections, the sandbox of + // the scripts (utilities/inionlysettings.h) + Global.ConfigParse( Input, config_source::scenery ); if( Global.test.enabled ) { // a scenery doesn't get to turn on what a test keeps off simulation::apply_test_mode_settings(); diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp new file mode 100644 index 000000000..8ae73fe43 --- /dev/null +++ b/tests/unit/test_ini_only_settings.cpp @@ -0,0 +1,116 @@ +#include "stdafx.h" +#include "doctest.h" + +// the settings only eu07.ini sets (utilities/inionlysettings.h): a config block of a scenery is read by the parser of +// eu07.ini (global_settings::ConfigParse with config_source::scenery), which keeps these as eu07.ini set them, and puts +// them back before FinalizeConfig() acts on any. here the keeping, as ConfigParse does it around the keys of a scenery + +#include "utilities/Globals.h" +#include "utilities/inionlysettings.h" + +#include +#include +#include +#include + +namespace { + +bool listed(std::vector const &Keys, std::string_view const Key) { + return std::ranges::find(Keys, Key) != Keys.end(); +} + +} // namespace + +TEST_CASE("ini only settings: a scenery's config block doesn't give its scripts all libraries") { + auto const settings{std::make_unique()}; + settings->lua_fulllibraries = false; + ini_only_settings const ini{*settings}; + // "config lua.fulllibraries yes endconfig" in the .scn + settings->lua_fulllibraries = true; + auto const changed{ini.restore(*settings)}; + CHECK_FALSE(settings->lua_fulllibraries); + CHECK(changed == std::vector{"lua.fulllibraries"}); +} + +TEST_CASE("ini only settings: what eu07.ini turned on stays on") { + auto const settings{std::make_unique()}; + settings->lua_fulllibraries = true; + settings->python_enabled = false; + ini_only_settings const ini{*settings}; + settings->lua_fulllibraries = false; + settings->python_enabled = true; + auto const changed{ini.restore(*settings)}; + CHECK(settings->lua_fulllibraries); + CHECK_FALSE(settings->python_enabled); + CHECK(changed.size() == 2); +} + +TEST_CASE("ini only settings: a scenery runs no program, opens no connection and switches no runtime back on") { + auto const settings{std::make_unique()}; + settings->luascreens_enabled = false; + settings->wasm_enabled = false; + settings->python_enabled = false; + ini_only_settings const ini{*settings}; + + settings->exec_on_exit = "cmd /c del something"; + settings->extcam_cmd = "evil.exe"; + settings->extcam_rec = "evil.exe"; + settings->screenshot_dir = "C:/Users/Public"; + settings->network_servers.emplace_back("tcp", "0.0.0.0:7424"); + settings->network_client.emplace("tcp", "example.com:7424"); + settings->motiontelemetry_conf.enable = true; + settings->motiontelemetry_conf.address = "example.com"; + settings->iFeedbackMode = 4; + settings->iFeedbackPort = 0x378; + settings->luascreens_enabled = true; + settings->wasm_enabled = true; + settings->python_enabled = true; +#ifdef WITH_UART + settings->uart_conf.enable = true; + settings->uart_conf.port = "COM1"; +#endif +#ifdef WITH_ZMQ + settings->zmq_address = "tcp://*:5555"; +#endif + // and a key a scenery may set + settings->fFriction = 0.5; + + auto const changed{ini.restore(*settings)}; + CHECK(settings->exec_on_exit.empty()); + CHECK(settings->extcam_cmd.empty()); + CHECK(settings->extcam_rec.empty()); + CHECK(settings->screenshot_dir.empty()); + CHECK(settings->network_servers.empty()); + CHECK_FALSE(settings->network_client.has_value()); + CHECK_FALSE(settings->motiontelemetry_conf.enable); + CHECK(settings->motiontelemetry_conf.address.empty()); + CHECK(settings->iFeedbackMode == 1); + CHECK(settings->iFeedbackPort == 0); + CHECK_FALSE(settings->luascreens_enabled); + CHECK_FALSE(settings->wasm_enabled); + CHECK_FALSE(settings->python_enabled); + for (auto const *key : {"execonexit", "extcam.cmd", "extcam.rec", "screenshotsdir", "network.server", "network.client", "motiontelemetry", + "feedbackmode", "feedbackport", "luascreens.enabled", "wasm.enabled", "python.enabled"}) { + CAPTURE(key); + CHECK(listed(changed, key)); + } +#ifdef WITH_UART + CHECK_FALSE(settings->uart_conf.enable); + CHECK(settings->uart_conf.port.empty()); + CHECK(listed(changed, "uart")); +#endif +#ifdef WITH_ZMQ + CHECK(settings->zmq_address.empty()); + CHECK(listed(changed, "zmq.address")); +#endif + // the rest is the scenery's to set + CHECK(settings->fFriction == doctest::Approx(0.5)); +} + +TEST_CASE("ini only settings: nothing changed, nothing to tell") { + auto const settings{std::make_unique()}; + settings->exec_on_exit = "notify.exe"; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(settings->exec_on_exit == "notify.exe"); +} diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp index 344f51c63..bc0753162 100644 --- a/tests/unit/test_lua_sandbox.cpp +++ b/tests/unit/test_lua_sandbox.cpp @@ -65,7 +65,7 @@ bool contains(std::string_view const Text, std::string_view const Part) { TEST_CASE("lua sandbox: no library that reaches files, programs, ffi or the debugger, and nothing that loads code") { sandboxed_state const lua; for (auto const *name : {"io", "ffi", "debug", "package", "jit", "require", "module", "dofile", "loadfile", "load", "loadstring", - "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", + "newproxy", "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", "os.setlocale"}) { CAPTURE(name); CHECK(lua.run(std::format("return {}", name)) == "nil"); @@ -424,4 +424,112 @@ TEST_CASE("lua sandbox: the file functions make eu07 when there is none") { CHECK(lua.run("return eu07.read_file('x.txt')") == "nil"); } +TEST_CASE("lua sandbox: no userdata of the script's own, whose __gc would run without the hooks") { + sandboxed_state const lua; + CHECK(lua.run("return newproxy") == "nil"); + // a table's __gc isn't called (Lua 5.1, LuaJIT): no other way to a finalizer of the script's own + CHECK(lua.run("collected = false setmetatable({}, { __gc = function() collected = true end }) collectgarbage() collectgarbage() return collected") == + "false"); +} + +namespace { + +// two objects of the simulation, of which a script holds handles +int memcell_object{1}; +int track_object{2}; + +// eu07.test_memcell(handle): the number of the memcell object, nil for none; eu07.test_track(handle) likewise +int test_memcell(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +int test_track(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +// a state with the handles, the functions above, and the globals memcell, track (handles), memcell2 (the memcell's +// handle pushed again) and light (a light userdata, which a script can't make, as the game gave them before) +class handle_state : public sandboxed_state { + public: + handle_state() { + auto *L{get()}; + lua_sandbox::open_handles(L); + lua_register(L, "test_memcell", test_memcell); + lua_register(L, "test_track", test_track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell2"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &track_object); + lua_setglobal(L, "track"); + // the address of the memcell as a handle of another kind: told apart all the same + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &memcell_object); + lua_setglobal(L, "memcell_as_track"); + lua_pushlightuserdata(L, &memcell_object); + lua_setglobal(L, "light"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, nullptr); + lua_setglobal(L, "none"); + } +}; + +} // namespace + +TEST_CASE("lua sandbox: a handle of the scenery api reaches the object of its kind") { + handle_state const lua; + CHECK(lua.run("return test_memcell(memcell)") == "1"); + CHECK(lua.run("return test_track(track)") == "2"); + CHECK(lua.run("return type(memcell)") == "userdata"); + // what the find functions give for a missing object, and what the functions take as no object + CHECK(lua.run("return none") == "nil"); + CHECK(lua.run("return test_memcell(nil)") == "nil"); + CHECK(lua.run("return test_memcell()") == "nil"); + // one object, one handle: equal, and the same key of a table + CHECK(lua.run("return rawequal(memcell, memcell2)") == "true"); + CHECK(lua.run("local t = { [memcell] = 'cell' } return t[memcell2]") == "cell"); + CHECK(lua.run("return rawequal(memcell, memcell_as_track)") == "false"); + // the handle of a dropped handle is made again + REQUIRE_FALSE(luaL_dostring(lua.get(), "memcell = nil memcell2 = nil collectgarbage() collectgarbage()")); + lua_sandbox::push_handle(lua.get(), lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(lua.get(), "memcell"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a handle of another kind, or anything else, is a Lua error and not an object") { + handle_state const lua; + // a track where a memcell goes (memcell_update(track_find(...)) once wrote into a track as a memcell). not a tail + // call, which LuaJIT gives no function name in the message + CHECK(contains(lua.run("local r = test_memcell(track) return r"), "bad argument #1 to 'test_memcell' (eu07.memcell expected, got userdata)")); + CHECK(contains(lua.run("local r = test_track(memcell) return r"), "bad argument #1 to 'test_track' (eu07.track expected, got userdata)")); + CHECK(contains(lua.run("return test_memcell(memcell_as_track)"), "eu07.memcell expected")); + CHECK(contains(lua.run("return test_memcell(light)"), "eu07.memcell expected, got userdata")); + for (auto const *value : {"1", "'memcell'", "{}", "true", "false", "print", "coroutine.create(function() end)"}) { + CAPTURE(value); + CHECK(contains(lua.run(std::format("return test_memcell({})", value)), "eu07.memcell expected")); + } + // the error is the script's: caught by pcall, and the state goes on + CHECK(lua.run("return (pcall(test_memcell, track))") == "false"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a script can't reach the metatable of a handle") { + handle_state const lua; + CHECK(lua.run("return getmetatable(memcell)") == "false"); + CHECK(contains(lua.run("local r = setmetatable(memcell, {}) return r"), "bad argument #1 to 'setmetatable' (table expected, got userdata)")); + // no field to read or write + CHECK(contains(lua.run("return memcell.x"), "attempt to index")); + CHECK(contains(lua.run("memcell.x = 1"), "attempt to index")); +} + #endif diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 2b5684dab..9ac0f3bff 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "vehicle/Driver.h" #include "utilities/Logs.h" +#include "utilities/inionlysettings.h" #include "utilities/utilities.h" #include "Console.h" #include "scripting/PyInt.h" @@ -957,7 +958,8 @@ bool global_settings::ConfigParseScriptScreens(cParser& Parser, std::string_view } // the scenery scripts (lua in the .scn) with all of LuaJIT's libraries, for a scenery that needs io, ffi or - // require: they then reach files and programs as the player does + // require: they then reach files and programs as the player does. from eu07.ini only: a config block of the + // scenery doesn't change it (utilities/inionlysettings.h) if (token == "lua.fulllibraries") { ParseOne(Parser, lua_fulllibraries, 1); @@ -1451,8 +1453,10 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return false; } -void global_settings::ConfigParse(cParser& Parser) +void global_settings::ConfigParse(cParser& Parser, config_source const Source) { + // what a scenery doesn't change, kept before its keys are read + std::optional const inionly{Source == config_source::scenery ? std::make_optional(*this) : std::nullopt}; std::string token; do @@ -1507,6 +1511,15 @@ void global_settings::ConfigParse(cParser& Parser) } while (true); + if (inionly.has_value()) + { + // put back before FinalizeConfig() acts on them (feedbackmode) + for (auto const key : inionly->restore(*this)) + { + ErrorLog("scenery config: \"" + std::string(key) + "\" is read from eu07.ini only, ignored"); + } + } + FinalizeConfig(); } diff --git a/utilities/Globals.h b/utilities/Globals.h index 25c7872c8..f77bd65de 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -25,6 +25,12 @@ http://mozilla.org/MPL/2.0/. #include "input/zmq_input.h" #endif +// where the keys global_settings::ConfigParse reads come from +enum class config_source { + ini, // eu07.ini, and the file given with -ini + scenery // a config block of a scenery (.scn, .inc), read as it loads +}; + struct global_settings { // members // data items @@ -403,7 +409,9 @@ struct global_settings { // methods void LoadIniFile( std::string asFileName ); void FinalizeConfig(); - void ConfigParse(cParser &parser); + // the keys of eu07.ini. Source: where they come from, eu07.ini or a config block of a scenery, which doesn't change + // the settings only eu07.ini sets (utilities/inionlysettings.h) + void ConfigParse(cParser &parser, config_source Source = config_source::ini); bool ConfigParseGeneral(cParser& Parser, const std::string& token); bool ConfigParseAudio(cParser& Parser, const std::string& token); bool ConfigParseGraphics(cParser& Parser, const std::string& token); diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp new file mode 100644 index 000000000..836954bf1 --- /dev/null +++ b/utilities/inionlysettings.cpp @@ -0,0 +1,82 @@ +/* +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 "utilities/inionlysettings.h" + +namespace +{ + +// puts Kept back into Current, and adds Key to Changed when they differed +template void keep(Type_ &Current, Type_ const &Kept, std::string_view const Key, std::vector &Changed) +{ + if (false == (Current == Kept)) + { + Current = Kept; + Changed.push_back(Key); + } +} + +} // namespace + +ini_only_settings::ini_only_settings(global_settings const &Settings) + : m_exec_on_exit{Settings.exec_on_exit}, m_screenshot_dir{Settings.screenshot_dir}, m_extcam_cmd{Settings.extcam_cmd}, + m_extcam_rec{Settings.extcam_rec}, m_network_servers{Settings.network_servers}, m_network_client{Settings.network_client}, +#ifdef WITH_ZMQ + m_zmq_address{Settings.zmq_address}, +#endif + m_motiontelemetry{Settings.motiontelemetry_conf}, +#ifdef WITH_UART + m_uart{Settings.uart_conf}, +#endif + m_feedback_mode{Settings.iFeedbackMode}, m_feedback_port{Settings.iFeedbackPort}, m_python_enabled{Settings.python_enabled}, + m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled} +{ +} + +std::vector ini_only_settings::restore(global_settings &Settings) const +{ + std::vector changed; + keep(Settings.exec_on_exit, m_exec_on_exit, "execonexit", changed); + keep(Settings.screenshot_dir, m_screenshot_dir, "screenshotsdir", changed); + keep(Settings.extcam_cmd, m_extcam_cmd, "extcam.cmd", changed); + keep(Settings.extcam_rec, m_extcam_rec, "extcam.rec", changed); + keep(Settings.network_servers, m_network_servers, "network.server", changed); + keep(Settings.network_client, m_network_client, "network.client", changed); +#ifdef WITH_ZMQ + keep(Settings.zmq_address, m_zmq_address, "zmq.address", changed); +#endif + // the structures as a whole, told apart by what turns them on and where they lead + { + auto ¤t{Settings.motiontelemetry_conf}; + if (current.enable != m_motiontelemetry.enable || current.proto != m_motiontelemetry.proto || current.address != m_motiontelemetry.address || + current.port != m_motiontelemetry.port) + { + changed.emplace_back("motiontelemetry"); + } + current = m_motiontelemetry; + } +#ifdef WITH_UART + { + auto ¤t{Settings.uart_conf}; + if (current.enable != m_uart.enable || current.port != m_uart.port) + { + changed.emplace_back("uart"); + } + current = m_uart; + } +#endif + keep(Settings.iFeedbackMode, m_feedback_mode, "feedbackmode", changed); + keep(Settings.iFeedbackPort, m_feedback_port, "feedbackport", changed); + keep(Settings.python_enabled, m_python_enabled, "python.enabled", changed); + keep(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); + keep(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); + keep(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + return changed; +} diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h new file mode 100644 index 000000000..eff5c067f --- /dev/null +++ b/utilities/inionlysettings.h @@ -0,0 +1,55 @@ +/* +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 "utilities/Globals.h" + +#include +#include +#include +#include +#include + +// the settings only eu07.ini sets. a scenery's config block is read by the parser of eu07.ini +// (state_serializer::deserialize_config, global_settings::ConfigParse), and with these keys it would run a program +// (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports +// (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a +// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled) or take its own scripts +// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set +class ini_only_settings +{ + public: + // what Settings holds now, as eu07.ini set it + explicit ini_only_settings(global_settings const &Settings); + + // puts back into Settings what changed since, and gives the keys of eu07.ini whose settings changed + std::vector restore(global_settings &Settings) const; + + private: + std::string m_exec_on_exit; + std::string m_screenshot_dir; + std::string m_extcam_cmd; + std::string m_extcam_rec; + std::vector> m_network_servers; + std::optional> m_network_client; +#ifdef WITH_ZMQ + std::string m_zmq_address; +#endif + motiontelemetry::conf_t m_motiontelemetry; +#ifdef WITH_UART + uart_input::conf_t m_uart; +#endif + int m_feedback_mode; + int m_feedback_port; + bool m_python_enabled; + bool m_luascreens_enabled; + bool m_lua_fulllibraries; + bool m_wasm_enabled; +}; From 6ee2cc8eb8207c2303e3781da41f9bdefb0d804e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 11:53:44 +0100 Subject: [PATCH 40/59] fix: exchange the brake pipe air between vehicles after all of them stepped, in sub-steps The air the brake hoses carry between the vehicles was taken explicitly inside each vehicle's step, at the physics step of 0.01 s. Through the hose between two 14 m freight wagons (Spg 0.792, 11.5 l of pipe) one step moved 11.8 l per bar, 2.06 times the 5.7 l that evens out the two pipes: the pipes overshot each other in turns and settled into a pattern in which every distributor saw the pipe up to 0.28 bar off the pressure left in it after the step. ESt3 valves charged at 5.0 bar saw 4.79 and lapped at the first stage, and the AI of a standing freight train never got its brakes released (the report of eu07/maszyna#368). The exchange now comes after every vehicle has stepped (vehicle_table::update_brake_pipes(), once per physics iteration), for the vehicles which stepped their pipe, in as many sub-steps as keep the air a hose carries in one below what evens out the pipes on its ends (3 for 14 m freight wagons, 2 for passenger cars), each going through the vehicles in the order they step. The distributors see the pressure the pipe holds, and an application reaches the end of the train as with a step of 0.001 s. --- McZapkie/MOVER.h | 4 ++ McZapkie/Mover.cpp | 68 ++++++++++++++++++- McZapkie/hamulce.h | 2 + tests/unit/consist.cpp | 11 ++++ tests/unit/consist.h | 1 + tests/unit/test_brake_pipe.cpp | 117 +++++++++++++++++++++++++++++++++ tests/unit/vehicle.cpp | 2 + vehicle/DynObj.cpp | 15 +++++ vehicle/DynObj.h | 4 ++ 9 files changed, 223 insertions(+), 1 deletion(-) create mode 100644 tests/unit/test_brake_pipe.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index b619ba7de..0166ba30c 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2078,6 +2078,7 @@ class TMoverParameters double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ double PipePress = 0.0; /*!o cisnienie w przewodzie glownym*/ + bool PipeCouplersPending{false}; // the brake pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double EqvtPipePress = 0.0; /*!o cisnienie w przewodzie glownym skladu*/ double Volume = 0.0; /*objetosc spr. powietrza w zbiorniku hamulca*/ double CompressedVolume = 0.0; /*objetosc spr. powietrza w ukl. zasilania*/ @@ -2557,6 +2558,9 @@ class TMoverParameters void UpdateScndPipePressure(double dt); void UpdateSpringBrake(double dt); double GetDVc(double dt); + int PipeCouplersSubsteps(double dt) const; + // the air exchange through the brake hoses, after the vehicles stepped + static void UpdatePipeCouplers(std::vector const &Vehicles, double dt); /*funkcje obliczajace sily*/ void ComputeConstans(void); // ABu: wczesniejsze wyznaczenie stalych dla liczenia sil diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..4e0040deb 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -4958,7 +4958,9 @@ void TMoverParameters::UpdatePipePressure(double dt) temp = 0.0; // odetnij else temp = 1.0; // połącz - Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel) + GetDVc(dt)); + Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); + // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + PipeCouplersPending = true; if (ASBType == 128) Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); @@ -5125,6 +5127,70 @@ double TMoverParameters::GetDVc(double dt) return dv2 + dv1; } +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs: in one, the air +// a hose carries stays below what evens out the pipes on its ends. taken in a single step of 0.01 s, the hose +// between two 14 m freight wagons carries twice that, their pipes overshoot each other in turns and the +// distributors see the pressure up to 0.28 bar off what's in the pipe (eu07/maszyna#368) +// ************************************************************************************************* +int TMoverParameters::PipeCouplersSubsteps(double const dt) const +{ + auto substeps{1}; + auto const area{Spg / (1.0 + 0.015 / Spg * Dim.L)}; // as in GetDVc() + for (auto const &coupler : Couplers) + { + if (coupler.Connected == nullptr || false == TestFlag(coupler.CouplingFlag, ctrain_pneumatic)) + { + continue; + } + auto const &other{*coupler.Connected}; + // the flow per bar of the difference, at small differences, where it's the largest + auto const pressure{std::max(PipePress, other.PipePress)}; + auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; + auto const equalising{Pipe->GetCap() * other.Pipe->GetCap() / (Pipe->GetCap() + other.Pipe->GetCap())}; + substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); + } + return std::min(substeps, 10); +} + +// ************************************************************************************************* +// the air exchange through the brake hoses of the vehicles which stepped their brake pipe (UpdatePipePressure()) +// since the last call, in the order they stepped: in as many sub-steps of dt as the vehicle needing the most of +// them takes, each going through the vehicles one after another, as the step of the vehicles does +// ************************************************************************************************* +void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +{ + auto substeps{1}; + for (auto const *vehicle : Vehicles) + { + if (vehicle->PipeCouplersPending) + { + substeps = std::max(substeps, vehicle->PipeCouplersSubsteps(dt)); + } + } + auto const substep{dt / substeps}; + for (auto i = 0; i < substeps; ++i) + { + for (auto *vehicle : Vehicles) + { + if (false == vehicle->PipeCouplersPending) + { + continue; + } + auto &pipe{*vehicle->Pipe}; + pipe.Act(); // what the neighbours have sent in the meantime + vehicle->PipePress = pipe.P(); + pipe.Flow(vehicle->GetDVc(substep)); + pipe.Act(); + vehicle->PipePress = pipe.P(); + } + } + for (auto *vehicle : Vehicles) + { + vehicle->PipeCouplersPending = false; + } +} + // ************************************************************************************************* // Q: 20160713 // Obliczenie stałych potrzebnych do dalszych obliczeń diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 2fb433a85..7de34ea23 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -249,6 +249,8 @@ class TReservoir /// /// Pressure in bar (atm). void CreatePress(double Press); + /// Returns reservoir capacity in liters. + double GetCap() const { return Cap; } /// /// Returns absolute (atmospheric) pressure inside the reservoir. /// diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index a5f10d936..1226c8192 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -74,6 +74,7 @@ void consist::step(track const &Track, double Dt) { for (std::size_t i = 0; i < m_vehicles.size(); ++i) { m_positions[i] += m_vehicles[i]->fast_move(Track, Dt, TLocation{m_positions[i], 0.0, 0.0}); } + update_brake_pipes(Dt); } for (auto const &vehicle : m_vehicles) { vehicle->forces(Dt); @@ -90,6 +91,16 @@ void consist::step(track const &Track, double Dt) { for (std::size_t i = 0; i < m_vehicles.size(); ++i) { m_positions[i] += m_vehicles[i]->move(Track, Dt, TLocation{m_positions[i], 0.0, 0.0}, pipe); } + update_brake_pipes(Dt); +} + +void consist::update_brake_pipes(double Dt) { + // vehicle_table::update_brake_pipes() + std::vector movers; + for (auto const &vehicle : m_vehicles) { + movers.push_back(&vehicle->mover()); + } + TMoverParameters::UpdatePipeCouplers(movers, Dt); } void consist::run(double Seconds, track const &Track, double Dt) { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 02001e042..282c8d07b 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -45,6 +45,7 @@ public: private: void update_neighbours(); + void update_brake_pipes(double Dt); std::vector> m_vehicles; std::vector m_positions; // of the vehicles' middles along the track diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp new file mode 100644 index 000000000..18aa531e8 --- /dev/null +++ b/tests/unit/test_brake_pipe.cpp @@ -0,0 +1,117 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" +#include "consist.h" +#include "vehicle.h" + +// the air exchange through the brake hoses between the vehicles of a train (TMoverParameters::UpdatePipeCouplers()). +// taken in one explicit step of 0.01 s, the hose between two short freight wagons carried twice the air which evens +// out their pipes: the pipes overshot each other in turns, and an ESt3 distributor saw the pipe pressure up to +// 0.28 bar off what was in it, lapped at the first stage of braking and kept the AI's train from leaving +// (eu07/maszyna#368) + +namespace { + +using test::definition; + +// a freight train standing charged: a locomotive and Wagons empty two-axle freight wagons with ESt3, set to G +void freight_train(test::consist &Train, int const Wagons) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < Wagons; ++i) { + auto &wagon{Train.add(definition::fiz("3wl_v2/3wl"))}; + wagon->BrakeDelaySwitch(bdelay_G); + REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3); + REQUIRE(wagon->Spg == doctest::Approx(0.792)); // the pipe of a freight wagon + } + Train[0].hold_brake_pipe(5.0); // the locomotive's driver's valve in the running position +} + +// a passenger train standing charged: a locomotive and Cars passenger cars with ESt4, set to R +void passenger_train(test::consist &Train, int const Cars) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < Cars; ++i) { + auto &car{Train.add(definition::fiz("11xa_v2/93a"))}; + REQUIRE(car->Spg == doctest::Approx(0.507)); // the pipe of a passenger car + } + Train[0].hold_brake_pipe(5.0); +} + +// the time [s] until the brake pipe of the train's last vehicle is 0.5 bar down, once the locomotive holds its pipe +// at Pressure [bar], the physics stepping by Dt +double application_time(test::consist &Train, double const Pressure, double const Dt) { + auto &last{Train[Train.size() - 1]}; + auto const start{last->PipePress}; + Train[0].hold_brake_pipe(Pressure); + auto time{0.0}; + while (last->PipePress > start - 0.5 && time < 60.0) { + Train.step({}, Dt); + time += Dt; + } + return time; +} + +// the same train standing a minute, then braked from the locomotive, all of it in steps of Dt +double application_time(void (*Train)(test::consist &, int), int const Vehicles, double const Pressure, double const Dt) { + test::consist train; + Train(train, Vehicles); + train.run(60.0, {}, Dt); + return application_time(train, Pressure, Dt); +} + +} // namespace + +TEST_CASE("brake pipe: the distributors of a standing freight train see the pressure in the pipe, and none of them brakes") { + test::consist train; + freight_train(train, 37); + // standing a while, the locomotive keeping the pipe charged + train.run(300.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &wagon{train[i].mover()}; + // the distributor's valve chamber follows the pressure the distributor works with: the pipe's own + CHECK(std::abs(wagon.Hamulec->GetVRP() - wagon.PipePress) < 0.005); + CHECK(wagon.PipePress > 4.9); + // released, as the AI wants every vehicle before it starts (TController::CheckVehicles()) + CHECK((wagon.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(wagon.BrakePress < 0.1); + } + // the exchange between the 14 m wagons takes 3 sub-steps of a step of 0.01 s + CHECK(train[1]->PipeCouplersSubsteps(0.01) == 3); +} + +TEST_CASE("brake pipe: an application from the locomotive reaches the end of a freight train as with a short step") { + // a light application, the locomotive's pipe 1 bar down: the last wagon's pipe 0.5 bar down as soon as in the + // step of 0.001 s, at which the exchange through the hoses converges + auto const converged{application_time(freight_train, 37, 4.0, 0.001)}; + auto const usual{application_time(freight_train, 37, 4.0, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(converged < 60.0); + CHECK(usual == doctest::Approx(converged).epsilon(0.1)); + // a full service application + auto const convergedfull{application_time(freight_train, 37, 3.5, 0.001)}; + auto const usualfull{application_time(freight_train, 37, 3.5, 0.01)}; + CAPTURE(convergedfull); + CAPTURE(usualfull); + CHECK(usualfull == doctest::Approx(convergedfull).epsilon(0.1)); +} + +TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, brakes as with a short step") { + test::consist train; + passenger_train(train, 10); + train.run(300.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &car{train[i].mover()}; + CHECK(std::abs(car.Hamulec->GetVRP() - car.PipePress) < 0.005); + CHECK((car.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(car.BrakePress < 0.1); + } + auto const converged{application_time(passenger_train, 10, 3.5, 0.001)}; + auto const usual{application_time(passenger_train, 10, 3.5, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(usual == doctest::Approx(converged).epsilon(0.05)); +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index e38999f7d..743f3f266 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -332,6 +332,8 @@ void pair::step(track const &Track, double Dt) { auto const &mover{placed.owner->mover()}; placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, mover.PipePress); } + // vehicle_table::update_brake_pipes() + TMoverParameters::UpdatePipeCouplers({&m_vehicles[0].owner->mover(), &m_vehicles[1].owner->mover()}, Dt); } void pair::run(double Seconds, track const &Track, double Dt) { diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..67f0d516c 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -9023,6 +9023,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { for( auto *vehicle : m_items ) { vehicle->FastUpdate( Deltatime ); } + update_brake_pipes( Deltatime ); } } for( auto *vehicle : m_items ) { @@ -9035,6 +9036,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { // Ra 2015-01: tylko tu przelicza sieć trakcyjną vehicle->Update( Deltatime, totaltime ); } + update_brake_pipes( Deltatime ); // jeśli jest coś do usunięcia z listy, to trzeba na końcu erase_disabled(); @@ -9046,6 +9048,19 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } +// the air exchange through the brake hoses of the vehicles which stepped their physics, after all of them did +void +vehicle_table::update_brake_pipes( double const Deltatime ) { + + m_brakepipes.clear(); + for( auto *vehicle : m_items ) { + if( true == vehicle->MoverParameters->PipeCouplersPending ) { + m_brakepipes.push_back( vehicle->MoverParameters ); + } + } + TMoverParameters::UpdatePipeCouplers( m_brakepipes, Deltatime ); +} + // records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) void vehicle_table::save_odometers() { diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 49b23c959..8771146c5 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -948,8 +948,12 @@ private: // the trains it closes in on void update_coupler_physics() const; + // the air exchange through the brake hoses of the vehicles which stepped their physics, after all of them did + void + update_brake_pipes( double const Deltatime ); double m_odometersavetimer { 0.0 }; // simulation time since the odometers were last saved + std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory }; From c0bcdc23c7b7360d7692611a12069e03739052e1 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 17:35:42 +0100 Subject: [PATCH 41/59] fix: Sonar on the brake pipe sub-steps: no shadowed enumerator, const test helper, template callback --- McZapkie/Mover.cpp | 6 +++--- tests/unit/consist.cpp | 2 +- tests/unit/consist.h | 2 +- tests/unit/test_brake_pipe.cpp | 3 ++- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 4e0040deb..949a11dc4 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -5137,13 +5137,13 @@ int TMoverParameters::PipeCouplersSubsteps(double const dt) const { auto substeps{1}; auto const area{Spg / (1.0 + 0.015 / Spg * Dim.L)}; // as in GetDVc() - for (auto const &coupler : Couplers) + for (auto const &hose : Couplers) { - if (coupler.Connected == nullptr || false == TestFlag(coupler.CouplingFlag, ctrain_pneumatic)) + if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, ctrain_pneumatic)) { continue; } - auto const &other{*coupler.Connected}; + auto const &other{*hose.Connected}; // the flow per bar of the difference, at small differences, where it's the largest auto const pressure{std::max(PipePress, other.PipePress)}; auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 1226c8192..1f22632e6 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -94,7 +94,7 @@ void consist::step(track const &Track, double Dt) { update_brake_pipes(Dt); } -void consist::update_brake_pipes(double Dt) { +void consist::update_brake_pipes(double Dt) const { // vehicle_table::update_brake_pipes() std::vector movers; for (auto const &vehicle : m_vehicles) { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 282c8d07b..2c982e446 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -45,7 +45,7 @@ public: private: void update_neighbours(); - void update_brake_pipes(double Dt); + void update_brake_pipes(double Dt) const; std::vector> m_vehicles; std::vector m_positions; // of the vehicles' middles along the track diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index 18aa531e8..664f7262d 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -53,7 +53,8 @@ double application_time(test::consist &Train, double const Pressure, double cons } // the same train standing a minute, then braked from the locomotive, all of it in steps of Dt -double application_time(void (*Train)(test::consist &, int), int const Vehicles, double const Pressure, double const Dt) { +template +double application_time(Builder Train, int const Vehicles, double const Pressure, double const Dt) { test::consist train; Train(train, Vehicles); train.run(60.0, {}, Dt); From 8a185ee9807a31ee17a9d92482005b15301116d1 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 18:03:03 +0100 Subject: [PATCH 42/59] fix: exchange the main reservoir pipe air between vehicles after all of them stepped, in sub-steps The main reservoir hoses (ctrain_scndpneumatic) exchanged the air explicitly inside each vehicle's step at the physics step of 0.01 s, as the brake hoses did before eu07/maszyna#387. One step through the hose (0.38 of area, whatever the vehicles) moves about 1.5 times the air which evens out the pipes on its ends (EN57 cars 8.3 l per bar against 5.5 l, SM40 8.6 against 5.7, passenger cars 9.3 against 6.3), and the vehicles with a main reservoir of their own feed the pipe from it in the same step. Where a vehicle has both, and hoses on both ends, the pipe can't settle: with all the main reservoirs held at 7.0 bar, the middle cars of a three unit EN57 kept jumping 0.8 bar to and fro between the steps for good (6.6/7.4), three SM40s in multiple traction the same, a two unit Impuls 1.7 bar. Freely evening out, the reservoirs of a three unit EN57 took 13.9 s at 0.01 s against 7.6 s at 0.001 s. A locomotive with passenger cars, whose pipe only it feeds, was stable already. The main reservoir pipe now goes through the brake pipe's mechanism: UpdateScndPipePressure() leaves the hose exchange to UpdatePipeCouplers() (GetScndDVc(), ScndPipeCouplersSubsteps(), 2 sub-steps for these vehicles), which vehicle_table::update_brake_pipes() calls after every vehicle stepped. The two pipes share the code and take their sub-steps apart, so the brake pipe's exchange is as it was. With it the EN57 pipes stand at 7.000, and its reservoirs even out in 7.0 s against 7.5 s at 0.001 s. --- McZapkie/MOVER.h | 5 +- McZapkie/Mover.cpp | 182 +++++++++++++++++++++++----------- tests/unit/test_feed_pipe.cpp | 173 ++++++++++++++++++++++++++++++++ vehicle/DynObj.cpp | 5 +- vehicle/DynObj.h | 2 +- 5 files changed, 305 insertions(+), 62 deletions(-) create mode 100644 tests/unit/test_feed_pipe.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 0166ba30c..030c3f2ed 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2074,6 +2074,7 @@ class TMoverParameters double EmergencyValveFlow = 0.0; // air flow through alerter valve during last simulation step /*! przyrosty cisnienia w kroku czasowym*/ double ScndPipePress = 0.0; /*cisnienie w przewodzie zasilajacym*/ + bool ScndPipeCouplersPending{false}; // the main reservoir pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double BrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych*/ double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ @@ -2559,7 +2560,9 @@ class TMoverParameters void UpdateSpringBrake(double dt); double GetDVc(double dt); int PipeCouplersSubsteps(double dt) const; - // the air exchange through the brake hoses, after the vehicles stepped + double GetScndDVc(double dt); + int ScndPipeCouplersSubsteps(double dt) const; + // the air exchange through the brake and main reservoir hoses, after the vehicles stepped static void UpdatePipeCouplers(std::vector const &Vehicles, double dt); /*funkcje obliczajace sily*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 949a11dc4..5e8c57ff9 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -4997,50 +4997,19 @@ void TMoverParameters::UpdateScndPipePressure(double dt) } const double Spz = 0.5067; - TMoverParameters *c; - double dv1; - double dv2; - double dV; UpdateSpringBrake(dt); - dv1 = 0; - dv2 = 0; - - // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - if (dv1 * dv1 > 0.00000000000001) - c->switch_physics(true); - c->Pipe2->Flow(-dv1); - } - // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - if (dv2 * dv2 > 0.00000000000001) - c->switch_physics(true); - c->Pipe2->Flow(-dv2); - } - if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); - Couplers[0].Connected->Pipe2->Flow(+dV); - Couplers[1].Connected->Pipe2->Flow(-dV); - } - Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == dt_EZT ) || ( TrainType == dt_DMU ) */) { - dV = PF(Compressor, ScndPipePress, Spz) * dt; + double const dV = PF(Compressor, ScndPipePress, Spz) * dt; CompressedVolume += dV / 1000.0; Pipe2->Flow(-dV); } - Pipe2->Flow(dv1 + dv2); + // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + ScndPipeCouplersPending = true; Pipe2->Act(); ScndPipePress = Pipe2->P(); @@ -5128,44 +5097,107 @@ double TMoverParameters::GetDVc(double dt) } // ************************************************************************************************* -// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs: in one, the air -// a hose carries stays below what evens out the pipes on its ends. taken in a single step of 0.01 s, the hose -// between two 14 m freight wagons carries twice that, their pipes overshoot each other in turns and the -// distributors see the pressure up to 0.28 bar off what's in the pipe (eu07/maszyna#368) +// the air the main reservoir hoses carry between the vehicle's pipe and the neighbours' in dt: the neighbours' +// share is sent to them, the vehicle's own returned // ************************************************************************************************* -int TMoverParameters::PipeCouplersSubsteps(double const dt) const +double TMoverParameters::GetScndDVc(double dt) +{ + const double Spz = 0.5067; + TMoverParameters *c; + double dv1 = 0; + double dv2 = 0; + + // sprzeg 1 + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[0].Connected; // skrot + dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + if (dv1 * dv1 > 0.00000000000001) + c->switch_physics(true); + c->Pipe2->Flow(-dv1); + } + // sprzeg 2 + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + if (dv2 * dv2 > 0.00000000000001) + c->switch_physics(true); + c->Pipe2->Flow(-dv2); + } + if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + double const dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); + Couplers[0].Connected->Pipe2->Flow(+dV); + Couplers[1].Connected->Pipe2->Flow(-dV); + } + return dv1 + dv2; +} + +namespace +{ + +// a pipe along the train, whose air the hoses between the vehicles carry (TMoverParameters::UpdatePipeCouplers()) +struct train_pipe +{ + std::shared_ptr TMoverParameters::*reservoir; + double TMoverParameters::*pressure; + bool TMoverParameters::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come + int hose; // the coupling flag of the pipe's hose + double (TMoverParameters::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them + double (*area)(TMoverParameters const &); // the cross-section of the hose, as the exchange takes it +}; + +// the brake pipe, GetDVc() +train_pipe const brake_pipe{&TMoverParameters::Pipe, + &TMoverParameters::PipePress, + &TMoverParameters::PipeCouplersPending, + ctrain_pneumatic, + &TMoverParameters::GetDVc, + [](TMoverParameters const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; +// the main reservoir pipe, GetScndDVc() +train_pipe const main_reservoir_pipe{&TMoverParameters::Pipe2, + &TMoverParameters::ScndPipePress, + &TMoverParameters::ScndPipeCouplersPending, + ctrain_scndpneumatic, + &TMoverParameters::GetScndDVc, + [](TMoverParameters const &) { return 0.5067 * 0.75; }}; + +// the number of sub-steps of dt the air exchange through the hoses of the vehicle's pipe needs: in one, the air a +// hose carries stays below what evens out the pipes on its ends +int hose_substeps(TMoverParameters const &Vehicle, train_pipe const &Pipe, double const dt) { auto substeps{1}; - auto const area{Spg / (1.0 + 0.015 / Spg * Dim.L)}; // as in GetDVc() - for (auto const &hose : Couplers) + auto const area{Pipe.area(Vehicle)}; + auto const capacity{(Vehicle.*Pipe.reservoir)->GetCap()}; + for (auto const &hose : Vehicle.Couplers) { - if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, ctrain_pneumatic)) + if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) { continue; } auto const &other{*hose.Connected}; + auto const othercapacity{(other.*Pipe.reservoir)->GetCap()}; // the flow per bar of the difference, at small differences, where it's the largest - auto const pressure{std::max(PipePress, other.PipePress)}; + auto const pressure{std::max(Vehicle.*Pipe.pressure, other.*Pipe.pressure)}; auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; - auto const equalising{Pipe->GetCap() * other.Pipe->GetCap() / (Pipe->GetCap() + other.Pipe->GetCap())}; + auto const equalising{capacity * othercapacity / (capacity + othercapacity)}; substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); } return std::min(substeps, 10); } -// ************************************************************************************************* -// the air exchange through the brake hoses of the vehicles which stepped their brake pipe (UpdatePipePressure()) -// since the last call, in the order they stepped: in as many sub-steps of dt as the vehicle needing the most of -// them takes, each going through the vehicles one after another, as the step of the vehicles does -// ************************************************************************************************* -void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +// the air exchange through the hoses of the pipe, for the vehicles which stepped it since the last call, in the order +// they stepped: in as many sub-steps of dt as the vehicle needing the most of them takes, each going through the +// vehicles one after another, as the step of the vehicles does +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &Pipe, double const dt) { auto substeps{1}; for (auto const *vehicle : Vehicles) { - if (vehicle->PipeCouplersPending) + if (vehicle->*Pipe.pending) { - substeps = std::max(substeps, vehicle->PipeCouplersSubsteps(dt)); + substeps = std::max(substeps, hose_substeps(*vehicle, Pipe, dt)); } } auto const substep{dt / substeps}; @@ -5173,24 +5205,58 @@ void TMoverParameters::UpdatePipeCouplers(std::vector const { for (auto *vehicle : Vehicles) { - if (false == vehicle->PipeCouplersPending) + if (false == vehicle->*Pipe.pending) { continue; } - auto &pipe{*vehicle->Pipe}; + auto &pipe{*(vehicle->*Pipe.reservoir)}; pipe.Act(); // what the neighbours have sent in the meantime - vehicle->PipePress = pipe.P(); - pipe.Flow(vehicle->GetDVc(substep)); + vehicle->*Pipe.pressure = pipe.P(); + pipe.Flow((vehicle->*Pipe.exchange)(substep)); pipe.Act(); - vehicle->PipePress = pipe.P(); + vehicle->*Pipe.pressure = pipe.P(); } } for (auto *vehicle : Vehicles) { - vehicle->PipeCouplersPending = false; + vehicle->*Pipe.pending = false; } } +} // namespace + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs. taken in a single +// step of 0.01 s, the hose between two 14 m freight wagons carries twice the air which evens out their pipes, the +// pipes overshoot each other in turns and the distributors see the pressure up to 0.28 bar off what's in the pipe +// (eu07/maszyna#368) +// ************************************************************************************************* +int TMoverParameters::PipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, brake_pipe, dt); +} + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the main reservoir hoses of the vehicle needs. taken in a +// single step of 0.01 s, the hose carries about 1.5 times the air which evens out the pipes on its ends; along with +// the vehicles' own main reservoirs feeding the pipe in the same step, the pipes of the middle vehicles of a +// multiple unit or of locomotives in multiple traction kept jumping 0.8 bar to and fro between the steps +// ************************************************************************************************* +int TMoverParameters::ScndPipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, main_reservoir_pipe, dt); +} + +// ************************************************************************************************* +// the air exchange through the brake and the main reservoir hoses of the vehicles which stepped their pipes +// (UpdatePipePressure(), UpdateScndPipePressure()) since the last call, each pipe in its own sub-steps +// ************************************************************************************************* +void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +{ + exchange_through_hoses(Vehicles, brake_pipe, dt); + exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); +} + // ************************************************************************************************* // Q: 20160713 // Obliczenie stałych potrzebnych do dalszych obliczeń diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp new file mode 100644 index 000000000..00e7596c4 --- /dev/null +++ b/tests/unit/test_feed_pipe.cpp @@ -0,0 +1,173 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" +#include "consist.h" +#include "vehicle.h" + +// the air exchange through the main reservoir hoses between the vehicles of a train (TMoverParameters::UpdatePipeCouplers()). +// taken in one explicit step of 0.01 s, a hose carried about 1.5 times the air which evens out the pipes on its ends, +// and the vehicles' own main reservoirs fed the pipe in the same step: the pipes of the middle vehicles of a multiple +// unit, or of locomotives in multiple traction, kept jumping 0.8 bar to and fro between the steps, with the main +// reservoirs all at the same pressure + +namespace { + +using test::definition; + +// an EN57 of Units units, driven from the front cab +void en57(test::consist &Train, int const Units) { + for (int i = 0; i < Units; ++i) { + Train.add(definition::fiz("en57_v1/5bgb"), i == 0 ? 1 : 0); + Train.add(definition::fiz("en57_v1/6ba_840")); + Train.add(definition::fiz("en57_v1/5bgb")); + } +} + +// Count SM40 shunters in multiple traction, driven from the first +void sm40(test::consist &Train, int const Count) { + for (int i = 0; i < Count; ++i) { + Train.add(definition::fiz("sm40_v1/sm40"), i == 0 ? 1 : 0); + } +} + +// a locomotive and Cars passenger cars, whose main reservoir pipe only the locomotive feeds +void passenger_train(test::consist &Train, int const Cars) { + Train.add(definition::fiz("ep09_v2/104e")); + for (int i = 0; i < Cars; ++i) { + Train.add(definition::fiz("11xa_v2/93a")); + } + Train[0].hold_brake_pipe(5.0); +} + +// the largest difference [bar] of a main reservoir pipe of the train from Pressure, over Seconds of steps of Dt +double off_pressure(test::consist &Train, double const Pressure, double const Seconds, double const Dt = 0.01) { + auto off{0.0}; + for (auto time = 0.0; time < Seconds; time += Dt) { + Train.step({}, Dt); + for (std::size_t i = 0; i < Train.size(); ++i) { + off = std::max(off, std::abs(Train[i]->ScndPipePress - Pressure)); + } + } + return off; +} + +struct evening_out { + double time{60.0}; // [s] until the main reservoirs of the train's ends are within 0.05 bar + double zigzag{0.0}; // [bar] the largest step of a main reservoir pipe back and forth, between steps the other way +}; + +// the train standing, the main reservoir of its first vehicle Pressure [bar], those of the rest 1 bar below, stepping +// by Dt until they even out through the main reservoir pipe +template +evening_out even_out(Builder Train, int const Count, double const Pressure, double const Dt) { + test::consist train; + Train(train, Count); + for (std::size_t i = 0; i < train.size(); ++i) { + auto &mover{train[i].mover()}; + REQUIRE(mover.VeselVolume > 0.0); + auto const pressure{i == 0 ? Pressure : Pressure - 1.0}; + mover.CompressedVolume = pressure * mover.VeselVolume; + mover.Compressor = pressure; + mover.Pipe2->CreatePress(pressure); + mover.Pipe2->Act(); + mover.ScndPipePress = pressure; + } + evening_out result; + auto &first{train[0].mover()}; + auto &last{train[train.size() - 1].mover()}; + std::vector previous(train.size()), change(train.size()); + for (std::size_t i = 0; i < train.size(); ++i) { + previous[i] = train[i]->ScndPipePress; + } + auto time{0.0}; + while (time < 60.0) { + train.step({}, Dt); + time += Dt; + for (std::size_t i = 0; i < train.size(); ++i) { + auto const step{train[i]->ScndPipePress - previous[i]}; + if (step * change[i] < 0.0) { + // turned back + result.zigzag = std::max(result.zigzag, std::min(std::abs(step), std::abs(change[i]))); + } + change[i] = step; + previous[i] = train[i]->ScndPipePress; + } + if (std::abs(first.Compressor - last.Compressor) < 0.05) { + result.time = time; + break; + } + } + return result; +} + +// the time [s] until the main reservoir pipe of the train's last vehicle, emptied with all the others which have no +// main reservoir of their own, is within 0.2 bar of the first vehicle's, which holds its main reservoir at Pressure [bar] +template +double charging_time(Builder Train, int const Count, double const Pressure, double const Dt) { + test::consist train; + Train(train, Count); + train[0].hold_main_reservoir(Pressure); + for (std::size_t i = 1; i < train.size(); ++i) { + auto &mover{train[i].mover()}; + REQUIRE(mover.VeselVolume == 0.0); + mover.Pipe2->CreatePress(0.0); + mover.Pipe2->Act(); + mover.ScndPipePress = 0.0; + } + auto &first{train[0].mover()}; + auto &last{train[train.size() - 1].mover()}; + auto time{0.0}; + while ((last.ScndPipePress < 1.0 || std::abs(last.ScndPipePress - first.ScndPipePress) > 0.2) && time < 60.0) { + train.step({}, Dt); + time += Dt; + } + return time; +} + +} // namespace + +TEST_CASE("main reservoir pipe: the pipes of a three unit EN57 stand at the pressure of its main reservoirs") { + test::consist train; + en57(train, 3); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_main_reservoir(7.0); + } + // the pipes filling up from the reservoirs + train.run(60.0); + CHECK(off_pressure(train, 7.0, 1.0) < 0.01); + // the exchange through the hoses of the 21 m cars takes 2 sub-steps of a step of 0.01 s + CHECK(train[1]->ScndPipeCouplersSubsteps(0.01) == 2); +} + +TEST_CASE("main reservoir pipe: the pipes of locomotives in multiple traction stand at the pressure of their main reservoirs") { + test::consist train; + sm40(train, 3); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_main_reservoir(7.5); + } + train.run(60.0); + CHECK(off_pressure(train, 7.5, 1.0) < 0.01); +} + +TEST_CASE("main reservoir pipe: the main reservoirs of a multiple unit even out as with a short step") { + auto const converged{even_out(en57, 3, 7.0, 0.001)}; + auto const usual{even_out(en57, 3, 7.0, 0.01)}; + CAPTURE(converged.time); + CAPTURE(usual.time); + CAPTURE(usual.zigzag); + CHECK(converged.time < 60.0); + CHECK(usual.time == doctest::Approx(converged.time).epsilon(0.1)); + // the pipes go along with the reservoirs, without jumping to and fro between the steps + CHECK(usual.zigzag < 0.05); +} + +TEST_CASE("main reservoir pipe: a passenger train, whose exchange was stable in one step, fills its pipe as with a short step") { + auto const converged{charging_time(passenger_train, 10, 9.0, 0.001)}; + auto const usual{charging_time(passenger_train, 10, 9.0, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(converged < 60.0); + CHECK(usual == doctest::Approx(converged).epsilon(0.05)); +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 67f0d516c..64354d774 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -9048,13 +9048,14 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } -// the air exchange through the brake hoses of the vehicles which stepped their physics, after all of them did +// the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did void vehicle_table::update_brake_pipes( double const Deltatime ) { m_brakepipes.clear(); for( auto *vehicle : m_items ) { - if( true == vehicle->MoverParameters->PipeCouplersPending ) { + if( ( true == vehicle->MoverParameters->PipeCouplersPending ) + || ( true == vehicle->MoverParameters->ScndPipeCouplersPending ) ) { m_brakepipes.push_back( vehicle->MoverParameters ); } } diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 8771146c5..7e2fb6e37 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -948,7 +948,7 @@ private: // the trains it closes in on void update_coupler_physics() const; - // the air exchange through the brake hoses of the vehicles which stepped their physics, after all of them did + // the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did void update_brake_pipes( double const Deltatime ); From c8f52c8b03b6d45ffaa060ed8070408a5101778a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 20:22:53 +0100 Subject: [PATCH 43/59] test: Sonar on the main reservoir pipe test: an integer step counter, const references, one declaration a line --- tests/unit/test_feed_pipe.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp index 00e7596c4..55816af43 100644 --- a/tests/unit/test_feed_pipe.cpp +++ b/tests/unit/test_feed_pipe.cpp @@ -44,7 +44,8 @@ void passenger_train(test::consist &Train, int const Cars) { // the largest difference [bar] of a main reservoir pipe of the train from Pressure, over Seconds of steps of Dt double off_pressure(test::consist &Train, double const Pressure, double const Seconds, double const Dt = 0.01) { auto off{0.0}; - for (auto time = 0.0; time < Seconds; time += Dt) { + auto const steps{static_cast(std::lround(Seconds / Dt))}; + for (int step = 0; step < steps; ++step) { Train.step({}, Dt); for (std::size_t i = 0; i < Train.size(); ++i) { off = std::max(off, std::abs(Train[i]->ScndPipePress - Pressure)); @@ -75,9 +76,10 @@ evening_out even_out(Builder Train, int const Count, double const Pressure, doub mover.ScndPipePress = pressure; } evening_out result; - auto &first{train[0].mover()}; - auto &last{train[train.size() - 1].mover()}; - std::vector previous(train.size()), change(train.size()); + auto const &first{train[0].mover()}; + auto const &last{train[train.size() - 1].mover()}; + std::vector previous(train.size()); + std::vector change(train.size()); for (std::size_t i = 0; i < train.size(); ++i) { previous[i] = train[i]->ScndPipePress; } @@ -116,8 +118,8 @@ double charging_time(Builder Train, int const Count, double const Pressure, doub mover.Pipe2->Act(); mover.ScndPipePress = 0.0; } - auto &first{train[0].mover()}; - auto &last{train[train.size() - 1].mover()}; + auto const &first{train[0].mover()}; + auto const &last{train[train.size() - 1].mover()}; auto time{0.0}; while ((last.ScndPipePress < 1.0 || std::abs(last.ScndPipePress - first.ScndPipePress) > 0.2) && time < 60.0) { train.step({}, Dt); From dda38b6c0d03fe39b6da38e1c26f9b115f93d9ce Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 21:37:58 +0100 Subject: [PATCH 44/59] feat: the cruise control apart from the field shunting (eu07/maszyna#69) The secondary controller (ScndCtrl) is the switch of the cruise control (SpeedCtrl) on the vehicles which have one: its first position switches it on (IncScndCtrl), zero off (DecScndCtrl), and the speed buttons and steps work only off its zero position. On the 6Dg, the ST45 and the BR285, diesel-electrics with SpeedCtrl=Yes, the same controller shunts the field of the traction motors by itself (AutoRelay), refuses the driver's moves, and nothing could switch the cruise control on. Now the cruise control has a switch of its own wherever the secondary controller shunts the field (ElectricSeriesMotor, DieselElectric) or there's none: - IsSpeedCtrlSeparate(): which vehicles; IsSpeedCtrlEngaged(): on or off, SpeedCtrlUnit.IsActive for those, ScndCtrlPos > 0 for the rest; - SpeedCtrlSwitch(): the driver's switch, on at the speed of the moment or off; on the others IncScndCtrl(1) / DecScndCtrl(2), as before; - the buttons, the steps and the power limit go by IsSpeedCtrlEngaged(), the automatic turning off (SpeedCtrlATOF) by SpeedCtrlSwitch(false); - the cab's tempomat_sw / tempomatoff_sw toggle it, and follow its state rather than the secondary controller's; the AI's SpeedCntrl() uses it. The .fiz and .mmd formats are unchanged, with no new keys: the SpeedControl section and the cab's scndctrl and tempomat_sw entries stay as they are and now work side by side. Nothing changes for the vehicles with only one of the two: the whole unit test suite matches golden traces recorded before the change bit for bit. Tests (test_speed_control.cpp): the field shunting of the EU07, SM42 and SU45 and the cruise control of the Impuls and EU47 as before, the 6Dg's and ST45's shunting as before, the 6Dg's and ST45's cruise control on its own switch holding and changing the speed with the shunting going on by itself, the 214M railbus switched by the secondary controller through SpeedCtrlSwitch(). The 6Dg's definition joins tests/unit/data/fiz as on test/6dg-power-steps-real-data. --- McZapkie/MOVER.h | 9 + McZapkie/Mover.cpp | 54 +++- tests/unit/data/fiz/6dg_v1/6dg.json | 55 ++++ tests/unit/data/fiz/README.md | 3 +- tests/unit/test_speed_control.cpp | 395 ++++++++++++++++++++++++++++ vehicle/Driver.cpp | 13 +- vehicle/Train.cpp | 24 +- 7 files changed, 530 insertions(+), 23 deletions(-) create mode 100644 tests/unit/data/fiz/6dg_v1/6dg.json create mode 100644 tests/unit/test_speed_control.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index b619ba7de..7cdf004f4 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2498,6 +2498,7 @@ class TMoverParameters // ScndCtrlResistiveLock: the shunt controller drops to 0 once the master controller is at zero or on a resistive position, so it // can't stay engaged there, locked in place (eu07/maszyna#402) void ScndCtrlResistiveLockCheck(); + // NOTE: with the cruise control, either end of the secondary controller, as before the split of the two (eu07/maszyna#69) bool IsScndCtrlNoPowerPos() const; bool IsScndCtrlMaxPowerPos() const; @@ -2743,6 +2744,14 @@ class TMoverParameters void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania void CheckSpeedCtrl(double dt); + // whether the cruise control has a switch of its own: the secondary controller doubles as its switch unless it + // shunts the field of the traction motors already, or there's none (the 6Dg, the ST45; eu07/maszyna#69) + bool IsSpeedCtrlSeparate() const; + // whether the cruise control is switched on: by its own switch, or by the secondary controller off its zero position + bool IsSpeedCtrlEngaged() const; + // the driver's switch of the cruise control: on, to hold the speed of the moment, or off. its own switch, or the + // secondary controller doubling as one (first position on, back to zero off); returns whether it did anything + bool SpeedCtrlSwitch(bool State); void SpeedCtrlButton(int button); void SpeedCtrlInc(); void SpeedCtrlDec(); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..dacb9dd34 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -2577,7 +2577,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) OK = true; if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) { - DecScndCtrl(2); + SpeedCtrlSwitch(false); SpeedCtrlUnit.IsActive = false; } break; @@ -2755,7 +2755,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) OK = true; if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) { - DecScndCtrl(2); + SpeedCtrlSwitch(false); SpeedCtrlUnit.IsActive = false; } } @@ -8043,7 +8043,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) } if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && Hamulec->GetEDBCP() > 0.25) { - DecScndCtrl(2); + SpeedCtrlSwitch(false); SpeedCtrlUnit.IsActive = false; } } @@ -8056,9 +8056,47 @@ void TMoverParameters::CheckSpeedCtrl(double dt) } } +bool TMoverParameters::IsSpeedCtrlSeparate() const +{ + // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) + return SpeedCtrl && (ScndCtrlPosNo == 0 || EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric); +} + +bool TMoverParameters::IsSpeedCtrlEngaged() const +{ + return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : ScndCtrlPos > 0; +} + +bool TMoverParameters::SpeedCtrlSwitch(bool const State) +{ + if (false == IsSpeedCtrlSeparate()) + { + return State ? IncScndCtrl(1) : DecScndCtrl(2); + } + // its own switch, the secondary controller left to the field shunting + if (State) + { + if (CabActive == 0 || SpeedCtrlUnit.IsActive) + { + return false; + } + SpeedCtrlValue = static_cast(Round(Vel)); + SpeedCtrlUnit.IsActive = true; + return true; + } + auto const wasactive{SpeedCtrlUnit.IsActive}; + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (wasactive && SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + return wasactive; +} + void TMoverParameters::SpeedCtrlButton(int button) { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { SpeedCtrlValue = SpeedCtrlButtons[button]; } @@ -8066,7 +8104,7 @@ void TMoverParameters::SpeedCtrlButton(int button) void TMoverParameters::SpeedCtrlInc() { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); @@ -8075,7 +8113,7 @@ void TMoverParameters::SpeedCtrlInc() void TMoverParameters::SpeedCtrlDec() { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); @@ -8084,7 +8122,7 @@ void TMoverParameters::SpeedCtrlDec() bool TMoverParameters::SpeedCtrlPowerInc() { - if (!(SpeedCtrl && ScndCtrlPos > 0)) + if (!(SpeedCtrl && IsSpeedCtrlEngaged())) return false; if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MaxPower) @@ -8096,7 +8134,7 @@ bool TMoverParameters::SpeedCtrlPowerInc() bool TMoverParameters::SpeedCtrlPowerDec() { - if (!(SpeedCtrl && ScndCtrlPos > 0)) + if (!(SpeedCtrl && IsSpeedCtrlEngaged())) return false; if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MinPower) diff --git a/tests/unit/data/fiz/6dg_v1/6dg.json b/tests/unit/data/fiz/6dg_v1/6dg.json new file mode 100644 index 000000000..9ad99dec4 --- /dev/null +++ b/tests/unit/data/fiz/6dg_v1/6dg.json @@ -0,0 +1,55 @@ +{ + "_source": "pkp/6dg_v1/6dg.fiz", + "_comment": "converted by test_fiz.cpp from the game's definition with the files it includes, keeping what the game's loader reads", + "Param": {"Category": "train", "M": "70000", "Mred": "10000", "Vmax": "90", "PWR": "708", "SandCap": "300"}, + "Dimensions": {"L": "14.24", "H": "4.285", "W": "3.170", "Cx": "0.2"}, + "Wheels": {"D": "1.100", "AIM": "4000", "Tw": "1.435", "Axle": "Bo'Bo'", "Ad": "2.6", "Bd": "7.524", "Rmin": "80"}, + "Brake": {"BrakeValve": "LSt", "NBpA": "4", "MBF": "85.0", "MaxBP": "6.2", "MaxASBP": "2.0", "BCN": "4", "BCR": "0.1143", "BCD": "0.05", "BCM": "6.68", "HiPP": "5.0", "LoPP": "3.5", "Vv": "0.8", "MinCP": "7.5", "MaxCP": "8.5", "CompressorSpeed": "0.05", "CompressorPower": "Converter", "BVV": "200", "BRE": "0.9", "UBB1": "1", "UBB2": "12", "UBB3": "16", "HandlePipeUnlockPos": "-0.5", "LPOn": "2.75", "LPOff": "4.5"}, + "BuffCoupl": {"ControlType": "6Dg", "CType": "Screw", "kB": "9200", "DmaxB": "0.15", "FmaxB": "740", "kC": "4800", "DmaxC": "0.15", "FmaxC": "780", "beta": "0.58", "AllowedFlag": "39"}, + "Cntrl": {"BrakeSystem": "Pneumatic", "BCPN": "10", "BDelay1": "15", "BDelay2": "3", "BDelay3": "35", "BDelay4": "36", "ASB": "Manual", "LocalBrake": "PneumaticBrake", "MCPN": "6", "SCPN": "1", "AutoRelay": "Yes", "IniCDelay": "0.5", "SCDelay": "0.1", "BrakeDelays": "GP", "BrakeHandle": "MHZ_K8P", "LocBrakeHandle": "FD1", "ConverterStart": "Automatic", "ConverterStartDelay": "10", "FuelStart": "Automatic", "OilStart": "Automatic", "BrakeOpModes": "PN", "EIMCtrlType": "3", "DirChangeMaxPos": "3", "HAO": "No", "HMO": "Yes", "HGDP1": "2", "rows": [ + ["-1","0.7","-1","15","Pneumatic"], + ["0","0.5","-1","9","Pneumatic"], + ["1","0.46","-1","9","Pneumatic"], + ["2","0.42","-1","9","Pneumatic"], + ["3","0.38","-1","9","Pneumatic"], + ["4","0.34","-1","9","Pneumatic"], + ["5","0.29","-1","9","Pneumatic"], + ["6","0","-1","15","Pneumatic"] + ]}, + "Security": {"AwareSystem": "Active,CabSignal", "AwareDelay": "60", "SoundSignalDelay": "5", "MaxHoldTime": "1.0", "EmergencyBrakeDelay": "6", "RadioStop": "Yes"}, + "Light": {"Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": "110", "LMaxCurrent": "91"}, + "Engine": {"AIM": "0.55", "EngineType": "DumbDE", "Trans": "17:75", "Ftmax": "219000", "Vhyp": "7", "Vadd": "5.5", "Cr": "1", "ShuntMode": "0", "WaterCoolingTemperature": "81", "WaterCoolingFanSpeed": "-1200", "WaterMaxTemperature": "85", "OilMinPressure": "0.15", "OilMinTemperature": "25", "OilMaxTemperature": "90", "HeaterMinTemperature": "55", "HeaterMaxTemperature": "60", "HeatKFS": "35", "HeatKFO": "30", "HeatKFE": "7", "HeatKW": "0.01", "HeatKV": "0.3", "HeatKFO2": "100"}, + "MotorParamTable": {"rows": [ + ["0","17.567","64","1500","15","800","1320"], + ["1","15","183.3","2000","49","800","1320"] + ]}, + "SpringBrake": {"Volume": "8", "MBF": "5", "MaxSP": "6", "ResetP": "4.0", "MinFP": "3.5", "PressOff": "4.5", "PressOn": "3.5", "ValveOnArea": "0.0002", "ValveOffArea": "0.0002", "ValvePNBArea": "0.002", "MTC": "4"}, + "WWList": {"Size": "6", "rows": [ + ["596","0","0","0"], + ["840","120","324","1150"], + ["1080","240","468","1350"], + ["1320","360","612","1550"], + ["1560","480","756","1750"], + ["1800","600","900","2000"], + ["1800","600","900","2000"] + ]}, + "SpeedControl": {"SpeedCtrl": "Yes", "OverrideManual": "Yes", "InitPwr": "0.3", "MaxPwrVel": "5", "StartVel": "2", "MinPwr": "0.3", "MaxPwr": "1.0", "MinVel": "0", "MaxVel": "120", "Offset": "-0.5", "kPpos": "0.1", "kPneg": "0.4", "kIpos": "0.06", "kIneg": "0.06", "BrakeIntervention": "Yes"}, + "LightsList": {"Size": "7", "Wrap": "no", "Default": "1", "rows": [ + ["0","0"], + ["34","34"], + ["38","34"], + ["22","34"], + ["16","1"], + ["1","16"], + ["21","34"] + ]}, + "UCList": {"Size": "6", "IntegratedBrakePN": "no", "IntegratedLocBrake": "yes", "IntegratedBrake": "no", "CtrlValStep": "0.05", "rows": [ + ["0","0","-1","0","-1","0.15","0.15","0","1","1"], + ["1","0","-1","0","0","0.00","0.00","1","3","1"], + ["2","0","-1","0","0","0.15","0.00","1","3","1"], + ["3","0","0","0","0","0.00","0.00","1","5","3"], + ["4","0","0","1","0","0.00","0.15","3","5","5"], + ["5","0","0","1","0","0.00","0.00","3","6","5"], + ["6","0","0","1","1","0.15","0.15","5","6","5"] + ]} +} diff --git a/tests/unit/data/fiz/README.md b/tests/unit/data/fiz/README.md index 514fb6287..e29a85dbb 100644 --- a/tests/unit/data/fiz/README.md +++ b/tests/unit/data/fiz/README.md @@ -20,6 +20,7 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `3wl_v2/3wl.fiz` | 3WL | - | ESt3 | - | ManualBrake | Screw | | `430w_v2/430w.fiz` | 430W | - | ESt3AL2HBG300 | - | ManualBrake | Screw | | `4e_v1/4e.fiz` | 4E | ElectricSeriesMotor | LSt | FV4a | PneumaticBrake | Screw | +| `6dg_v1/6dg.fiz` | 6Dg | DumbDE | LSt | MHZ_K8P | PneumaticBrake | Screw | | `bdhpumn_v3/bdhpumn.fiz` | BDHPUMN | - | KE | - | ManualBrake | Screw | | `bhp_v1/bhp-b.fiz` | BHP | - | ESt3AL2 | - | ManualBrake | Articulated | | `br285_v1/br285.fiz` | BR285 | DieselElectric | KE | MHZ_6P | PneumaticBrake | Screw | @@ -63,4 +64,4 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `wmb10_v1/wmb10.fiz` | WMB10 | DieselEngine | LSt | FV4a | PneumaticBrake | Screw | | `z1_v2/152a.fiz` | Z1 | - | KE | - | ManualBrake | Screw | -The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. +The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft. The 6Dg is there for its universal controller (UCList) setting the power in steps (CtrlValStep), converted alone from the game data of 2026-11 (SVN r9630, which added the key), the others staying as they were. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp new file mode 100644 index 000000000..a141f41a6 --- /dev/null +++ b/tests/unit/test_speed_control.cpp @@ -0,0 +1,395 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "drive.h" + +#include + +// the cruise control (tempomat, SpeedCtrl) and the secondary controller (ScndCtrl) of the vehicles which have one +// of them or both (eu07/maszyna#69). on the vehicles with the cruise control alone the secondary controller is +// its switch, as it always was; on those whose secondary controller shunts the field of the traction motors +// (the 6Dg, the ST45 and the BR285 among them) the cruise control has a switch of its own, apart from it + +using test::scenario; +using namespace test::channels; + +namespace { + +std::vector cruise() { + return { + {"SpeedCtrlActive", [](auto const &M) { return M.SpeedCtrlUnit.IsActive ? 1.0 : 0.0; }}, + {"SpeedCtrlStandby", [](auto const &M) { return M.SpeedCtrlUnit.Standby ? 1.0 : 0.0; }}, + {"SpeedCtrlValue", [](auto const &M) { return M.SpeedCtrlValue; }}, + {"eimic", [](auto const &M) { return M.eimic; }}, + {"eimicSpeedCtrl", [](auto const &M) { return M.eimicSpeedCtrl; }}, + {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + }; +} + +// the universal controller (EIMCtrlType 3) of the 6Dg: 3 no power, 4 lowers the demand, 5 holds it, 6 raises it +constexpr int dg_no_power{3}; +constexpr int dg_lower{4}; +constexpr int dg_hold{5}; +constexpr int dg_raise{6}; + +void move_to(TMoverParameters &Vehicle, int const Position) { + while (Vehicle.MainCtrlPos < Position && Vehicle.IncMainCtrl(1)) { + ; + } + while (Vehicle.MainCtrlPos > Position && Vehicle.DecMainCtrl(1)) { + ; + } + REQUIRE(Vehicle.MainCtrlPos == Position); +} + +// the 6Dg started up, its brakes released, its controller through the no power and lowering positions to holding, +// for the line contactors to close +void get_6dg_going(scenario &Scenario) { + auto &loco{Scenario.cab()}; + REQUIRE(Scenario.start_up()); + Scenario.get_going(); + move_to(loco, dg_no_power); + for (int second = 0; second < 180 && loco.BrakePress > 0.1; ++second) { + Scenario.wait(1.0); + } + REQUIRE(loco.BrakePress <= 0.1); + move_to(loco, dg_lower); + Scenario.wait(1.0); + move_to(loco, dg_hold); + Scenario.wait(5.0); + REQUIRE(loco.StLinFlag); +} + +} // namespace + +// the vehicles with the field shunting alone, and those with the cruise control alone: as before the split + +TEST_CASE("speed control: the field shunting of the vehicles without a cruise control, as before") { + // the EU07's and the SM42's shunting by hand, the SU45's by itself (RelayType 45, from position 11 of its + // controller on); none has a cruise control, and the secondary controller shunts the field + SUBCASE("EU07 and SM42, by hand") { + for (auto const *path : {"4e_v1/4e", "sm42_v1/6d1"}) { + CAPTURE(path); + scenario scenario{std::string{"speed control/shunting/"} + path, motion() + traction() + cruise()}; + scenario.add(path, 1); + auto &loco{scenario.cab()}; + REQUIRE_FALSE(loco.SpeedCtrl); + REQUIRE_FALSE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(60.0); + auto const speed{loco.Vel}; + scenario.act("shunt"); + CHECK(loco.IncScndCtrl(1)); + CHECK(loco.ScndCtrlPos == 1); + scenario.wait(10.0); + CHECK(loco.Vel > speed); + CHECK(loco.ScndCtrlPos == 1); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.act("shunt off"); + CHECK(loco.DecScndCtrl(2)); + CHECK(loco.ScndCtrlPos == 0); + scenario.wait(5.0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.check(); + } + } + SUBCASE("SU45, by itself") { + scenario scenario{"speed control/shunting/su45_v2/301d", motion() + traction() + cruise()}; + scenario.add("su45_v2/301d", 1); + auto &loco{scenario.cab()}; + REQUIRE_FALSE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(5.0); + auto most{0}; + for (int i = 0; i < 18; ++i) { + scenario.wait(10.0); + most = std::max(most, loco.ScndCtrlPos); + } + CHECK(most == loco.ScndCtrlPosNo); + // the driver can't move it + CHECK_FALSE(loco.DecScndCtrl(2)); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.act("notch back"); + scenario.notch_back(0); + scenario.wait(5.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.check(); + } +} + +TEST_CASE("speed control: the vehicles whose secondary controller is the cruise control's switch, as before") { + SUBCASE("Impuls: on at the speed of the moment, off by the controller") { + scenario scenario{"speed control/cruise/impuls_v1/31we-a_pr", motion() + traction() + cruise()}; + scenario.add("impuls_v1/31we-a_pr", 1).add("impuls_v1/31we-b_pr").add("impuls_v1/31we-c_pr").add("impuls_v1/31we-d_pr"); + auto &unit{scenario.cab()}; + REQUIRE(unit.SpeedCtrl); + REQUIRE(unit.ScndCtrlPosNo == 1); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(40.0); + scenario.act("cruise control on"); + CHECK(unit.IncScndCtrl(1)); + CHECK(unit.ScndCtrlPos == 1); + CHECK(unit.SpeedCtrlUnit.IsActive); + CHECK(unit.SpeedCtrlValue == doctest::Approx(unit.Vel)); + auto const held{unit.SpeedCtrlValue}; + scenario.wait(60.0); + CHECK(unit.Vel == doctest::Approx(held).epsilon(0.05)); + scenario.act("cruise control off"); + CHECK(unit.DecScndCtrl(2)); + CHECK(unit.ScndCtrlPos == 0); + CHECK_FALSE(unit.SpeedCtrlUnit.IsActive); + CHECK(unit.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + scenario.check(); + } + SUBCASE("EU47: the speed raised by tens while the controller is held up, set when it's let go") { + scenario scenario{"speed control/cruise/e186_v2/eu47", motion() + traction() + cruise()}; + scenario.add("e186_v2/eu47", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.SpeedCtrlTypeTime); + REQUIRE(loco.ScndCtrlPosNo == 4); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.act("raise"); + while (loco.ScndCtrlPos < 3 && loco.IncScndCtrl(1)) { + ; + } + REQUIRE(loco.ScndCtrlPos == 3); + scenario.wait(10.0); + CHECK(loco.NewSpeed > 0.0); + scenario.act("set"); + CHECK(loco.DecScndCtrl(1)); + scenario.wait(1.0); + CHECK(loco.SpeedCtrlValue == doctest::Approx(loco.NewSpeed)); + CHECK(loco.SpeedCtrlUnit.IsActive); + scenario.full_power(60.0); + CHECK(loco.Vel == doctest::Approx(loco.SpeedCtrlValue).epsilon(0.1)); + scenario.act("off"); + CHECK(loco.DecScndCtrl(2)); + scenario.wait(1.0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.check(); + } +} + +// the vehicles with both: the field shunting as before, the cruise control on a switch of its own + +TEST_CASE("speed control: the field shunting of the vehicles with a cruise control besides, as before") { + SUBCASE("6Dg") { + scenario scenario{"speed control/both/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; + scenario.add("6dg_v1/6dg", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(loco.ScndCtrlPosNo == 1); + get_6dg_going(scenario); + scenario.act("raise"); + move_to(loco, dg_raise); + // the shunt engages by itself at about 40 km/h (RelayType 0, by the current of the motors) + scenario.wait(10.0); + CHECK(loco.Vel < 35.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.wait(110.0); + CHECK(loco.Vel > 100.0); + CHECK(loco.ScndCtrlPos == 1); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + // the driver can't move the shunt + CHECK_FALSE(loco.IncScndCtrl(1)); + CHECK_FALSE(loco.DecScndCtrl(2)); + scenario.check(); + } + SUBCASE("ST45") { + scenario scenario{"speed control/both/st45_v2/301dd", motion() + traction() + cruise(), test::track{}}; + scenario.add("st45_v2/301dd", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(5.0); + // its relays (RelayType 45) engage the shunt from position 11 of the controller on, which the universal + // controller of the ST45, of 4 positions, never gets to: the shunt stays off + auto most{0}; + for (int i = 0; i < 9; ++i) { + scenario.wait(10.0); + most = std::max(most, loco.ScndCtrlPos); + } + CHECK(loco.Vel > 130.0); + CHECK(most == 0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + // the speed buttons do nothing with the cruise control off + loco.SpeedCtrlButton(4); + loco.SpeedCtrlInc(); + CHECK(loco.SpeedCtrlValue == 0.0); + CHECK_FALSE(loco.IncScndCtrl(1)); + scenario.check(); + } +} + +TEST_CASE("speed control apart: which vehicles' cruise control has a switch of its own") { + struct kind { + char const *path; + bool separate; + }; + for (auto const &[path, separate] : { + // the secondary controller shunts the field: a switch of its own + kind{"6dg_v1/6dg", true}, kind{"st45_v2/301dd", true}, kind{"br285_v1/br285", true}, + // the secondary controller is the switch, the speed setter or the gears' selector of the automatic gearbox + kind{"21xm_v1/214ma", false}, kind{"21xm_v1/218ma_a_kd", false}, kind{"sa134_v1/218mc_a", false}, kind{"impuls_v1/31we-a_pr", false}, + kind{"elf_v1/21we-a", false}, kind{"e186_v2/eu47", false}, kind{"e6act_v2/e6acta", false}, kind{"en57akl_v1/akl_ra", false}, + // no cruise control + kind{"4e_v1/4e", false}, kind{"sm42_v1/6d1", false}, kind{"su45_v2/301d", false}, kind{"ep09_v2/104e", false}}) { + CAPTURE(path); + test::vehicle vehicle{test::definition::fiz(path)}; + CHECK(vehicle->IsSpeedCtrlSeparate() == separate); + CHECK_FALSE(vehicle->IsSpeedCtrlEngaged()); + } + // with a cruise control and no secondary controller, the switch is its own too + test::vehicle eu07{test::definition::fiz("4e_v1/4e").set("Cntrl", "SCPN", 0).set("SpeedControl", "SpeedCtrl", "Yes")}; + CHECK(eu07->IsSpeedCtrlSeparate()); +} + +TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the field shunting going on by itself") { + scenario scenario{"speed control apart/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; + scenario.add("6dg_v1/6dg", 1); + auto &loco{scenario.cab()}; + get_6dg_going(scenario); + scenario.act("raise"); + move_to(loco, dg_raise); + scenario.wait(30.0); + REQUIRE(loco.Vel > 50.0); + REQUIRE(loco.ScndCtrlPos == 1); // the shunt in + // the shunt is no cruise control: its buttons do nothing yet, the secondary controller can't switch it on + CHECK_FALSE(loco.IsSpeedCtrlEngaged()); + loco.SpeedCtrlButton(2); + CHECK(loco.SpeedCtrlValue == 0.0); + CHECK_FALSE(loco.IncScndCtrl(1)); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + + scenario.act("cruise control on"); + CHECK(loco.SpeedCtrlSwitch(true)); + CHECK_FALSE(loco.SpeedCtrlSwitch(true)); // on already + CHECK(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.IsSpeedCtrlEngaged()); + CHECK(loco.SpeedCtrlValue == doctest::Approx(std::round(loco.Vel)).epsilon(0.02)); + CHECK(loco.ScndCtrlPos == 1); // the shunt as it was + auto const held{loco.SpeedCtrlValue}; + // the shunt goes by itself all the while, by the current of the motors, which the cruise control's demand sets + auto shunted{0}; + auto unshunted{0}; + auto const run{[&](int const Seconds) { + for (int second = 0; second < Seconds; ++second) { + scenario.wait(1.0); + ++(loco.ScndCtrlPos > 0 ? shunted : unshunted); + } + }}; + run(60); + CHECK(loco.Vel == doctest::Approx(held).epsilon(0.03)); + CHECK_FALSE(loco.SpeedCtrlUnit.Standby); + CHECK(loco.eimic_real < loco.eimic); // the cruise control holding the power back + + scenario.act("two steps up"); + loco.SpeedCtrlInc(); + loco.SpeedCtrlInc(); + auto const higher{loco.SpeedCtrlValue}; + CHECK(higher == doctest::Approx(held + 10.0).epsilon(0.1)); + run(60); + CHECK(loco.Vel == doctest::Approx(higher).epsilon(0.03)); + CHECK(loco.StLinFlag); + CHECK(shunted > 0); + CHECK(unshunted > 0); + CHECK_FALSE(loco.IncScndCtrl(1)); // still not the driver's + + scenario.act("button 30"); + loco.SpeedCtrlButton(0); + CHECK(loco.SpeedCtrlValue == doctest::Approx(30.0)); + scenario.wait(60.0); + // it brakes down with the air (BrakeIntervention), which opens the line contactors (the pressure switch), and + // they close again only through the first power position of the controller, as without the cruise control + CHECK(loco.Vel < 35.0); + CHECK_FALSE(loco.StLinFlag); + scenario.act("controller to the first power position and back up"); + move_to(loco, dg_lower); + scenario.wait(2.0); + move_to(loco, dg_raise); + scenario.wait(60.0); + CHECK(loco.StLinFlag); + CHECK(loco.Vel == doctest::Approx(30.0).epsilon(0.05)); + CHECK(loco.ScndCtrlPos == 0); // out at this speed + + scenario.act("cruise control off"); + CHECK(loco.SpeedCtrlSwitch(false)); + CHECK_FALSE(loco.SpeedCtrlSwitch(false)); // off already + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); // the controller's demand again + scenario.check(); +} + +TEST_CASE("speed control apart: the ST45's cruise control on its own switch, with its buttons and the power limit") { + scenario scenario{"speed control apart/st45_v2/301dd", motion() + traction() + cruise(), test::track{}}; + scenario.add("st45_v2/301dd", 1); + auto &loco{scenario.cab()}; + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(0.0); + REQUIRE(loco.Vel < 50.0); + scenario.act("cruise control on, button 60"); + CHECK(loco.SpeedCtrlSwitch(true)); + CHECK(loco.SpeedCtrlUnit.IsActive); + loco.SpeedCtrlButton(4); + CHECK(loco.SpeedCtrlValue == doctest::Approx(60.0)); + scenario.wait(90.0); + CHECK(loco.Vel == doctest::Approx(60.0).epsilon(0.03)); + CHECK(loco.StLinFlag); + scenario.act("step up, power down"); + loco.SpeedCtrlInc(); + CHECK(loco.SpeedCtrlValue == doctest::Approx(65.0)); + CHECK(loco.SpeedCtrlPowerDec()); + CHECK(loco.SpeedCtrlUnit.DesiredPower == doctest::Approx(0.9)); + scenario.wait(60.0); + CHECK(loco.Vel == doctest::Approx(65.0).epsilon(0.03)); + CHECK(loco.eimic_real <= 0.9 + 1e-9); + scenario.act("cruise control off"); + CHECK(loco.SpeedCtrlSwitch(false)); + // off, its buttons do nothing + loco.SpeedCtrlButton(6); + loco.SpeedCtrlInc(); + CHECK_FALSE(loco.SpeedCtrlPowerInc()); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.check(); +} + +TEST_CASE("speed control apart: the switch of a cruise control without one of its own is the secondary controller, as before") { + // the 214M railbus: on, its first position; off, back to zero + scenario scenario{"speed control apart/21xm_v1/214ma", motion() + traction() + cruise(), test::track{}}; + scenario.add("21xm_v1/214ma", 1); + auto &railbus{scenario.cab()}; + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(20.0); + scenario.act("cruise control on"); + CHECK(railbus.SpeedCtrlSwitch(true)); + CHECK(railbus.ScndCtrlPos == 1); + CHECK(railbus.SpeedCtrlUnit.IsActive); + CHECK(railbus.IsSpeedCtrlEngaged()); + scenario.wait(10.0); + scenario.act("cruise control off"); + CHECK(railbus.SpeedCtrlSwitch(false)); + CHECK(railbus.ScndCtrlPos == 0); + CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive); + CHECK_FALSE(railbus.IsSpeedCtrlEngaged()); + scenario.wait(5.0); + scenario.check(); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb74344bf..594f660ce 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -4474,7 +4474,16 @@ void TController::SpeedCntrl(double DesiredSpeed) { if( false == mvControlling->SpeedCtrl ) { return; } - if (mvControlling->EngineType == TEngineType::DieselEngine) + if (mvControlling->IsSpeedCtrlSeparate()) + { + // a switch of its own, the secondary controller left to the field shunting (eu07/maszyna#69) + if (DesiredSpeed < 0.1) { + DesiredSpeed = 0; + } + mvControlling->SpeedCtrlSwitch(DesiredSpeed > 0); + mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive); + } + else if (mvControlling->EngineType == TEngineType::DieselEngine) { if (DesiredSpeed < 0.1) { mvControlling->DecScndCtrl(2); @@ -4498,7 +4507,7 @@ void TController::SpeedCntrl(double DesiredSpeed) while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop } - if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->ScndCtrlPos > 0 ) { + if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->IsSpeedCtrlEngaged() ) { while (mvControlling->SpeedCtrlUnit.DesiredPower < mvControlling->SpeedCtrlUnit.MaxPower) { mvControlling->SpeedCtrlPowerInc(); diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 50659934c..72aa6b480 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -1447,8 +1447,8 @@ void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data cons auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } - // potentially animate tempomat button - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1) + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) { Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); } @@ -1511,17 +1511,17 @@ void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command return; } // glfw_press - if (Train->mvControlled->ScndCtrlPos == 0) + if (false == Train->mvControlled->IsSpeedCtrlEngaged()) { // turn on if it's not active - Train->mvControlled->IncScndCtrl(1); + Train->mvControlled->SpeedCtrlSwitch(true); // visual feedback Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); } else { // otherwise turn off - Train->mvControlled->DecScndCtrl(2); + Train->mvControlled->SpeedCtrlSwitch(false); // visual feedback if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -1541,17 +1541,17 @@ void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command return; } - if (Train->mvControlled->ScndCtrlPos == 0) + if (false == Train->mvControlled->IsSpeedCtrlEngaged()) { // turn on - Train->mvControlled->IncScndCtrl(1); + Train->mvControlled->SpeedCtrlSwitch(true); // visual feedback Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); } else { // turn off - Train->mvControlled->DecScndCtrl(2); + Train->mvControlled->SpeedCtrlSwitch(false); // visual feedback Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -1653,8 +1653,8 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } - // potentially animate tempomat button - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1) + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) { if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -9725,7 +9725,7 @@ bool TTrain::Update(double const Deltatime) { if (ggScndCtrlButton.is_toggle()) { - ggScndCtrlButton.UpdateValue(mvControlled->ScndCtrlPos > 0 ? 1.f : 0.f, dsbSwitch); + ggScndCtrlButton.UpdateValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f, dsbSwitch); } ggScndCtrlButton.Update(lowvoltagepower); } @@ -11993,7 +11993,7 @@ void TTrain::set_cab_controls(int const Cab) // tempomat if (false == ggScndCtrlButton.is_push()) { - ggScndCtrlButton.PutValue(mvControlled->ScndCtrlPos > 0 ? 1.f : 0.f); + ggScndCtrlButton.PutValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f); } // sandbox if (ggAutoSandButton.type() != TGaugeType::push) From 611dc365ebae82a3ad588b2763c81756e0394b9f Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 22:37:04 +0100 Subject: [PATCH 45/59] test: Sonar on the cruise control test: no empty statements, the lambda's captures named --- tests/unit/test_speed_control.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index a141f41a6..7b0f7fc52 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -34,10 +34,10 @@ constexpr int dg_raise{6}; void move_to(TMoverParameters &Vehicle, int const Position) { while (Vehicle.MainCtrlPos < Position && Vehicle.IncMainCtrl(1)) { - ; + // all the work is done in the condition } while (Vehicle.MainCtrlPos > Position && Vehicle.DecMainCtrl(1)) { - ; + // all the work is done in the condition } REQUIRE(Vehicle.MainCtrlPos == Position); } @@ -158,7 +158,7 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise scenario.get_going(); scenario.act("raise"); while (loco.ScndCtrlPos < 3 && loco.IncScndCtrl(1)) { - ; + // all the work is done in the condition } REQUIRE(loco.ScndCtrlPos == 3); scenario.wait(10.0); @@ -285,7 +285,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the // the shunt goes by itself all the while, by the current of the motors, which the cruise control's demand sets auto shunted{0}; auto unshunted{0}; - auto const run{[&](int const Seconds) { + auto const run{[&scenario, &loco, &shunted, &unshunted](int const Seconds) { for (int second = 0; second < Seconds; ++second) { scenario.wait(1.0); ++(loco.ScndCtrlPos > 0 ? shunted : unshunted); From 88383c0903ef2452a5fa037e0145d5c8c2c9f86d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 22:45:06 +0100 Subject: [PATCH 46/59] feat: dynamic brake of the diesel-electric vehicles (#82) The drive of a diesel-electric vehicle is computed from the power of its generator, not from a circuit, so neither the EP09's resistor brake (Current()) nor the inverter model of the induction motors has anything to work on, and a negative setting of the integrated controller did nothing: the BR285's TRAXX controller has its braking range (EB+, EB, EB-) and brakes nothing. A vehicle opts in with keys of its Engine section, read only for the diesel-electric ones; without EDBrake nothing changes: - EDBrake=Controller: the negative range of the integrated controller (EIMCtrlType > 0) sets the effort, which goes to the vehicles in multiple with the EIMIC command; EDBrake=Lever: a lever of its own, the one of SplitEDPneumaticBrake (DBPN steps, the dynamicbrakecontroller commands), working with the master controller at zero. - EDBrakeFmax [kN], EDBrakePmax [kW]: the force at the wheels, limited by the power of the resistors at speed; EDBrakeV0, EDBrakeV1 [km/h]: no force below V0, the whole above V1. An inverter's brake fades only at the stop, a resistor brake of direct current motors grows with the speed from 0. - EDBrakeRate [1/s]: how fast the effort follows (0.5). - EDBrakeBlending=Yes: the locomotive's train brake lets off by the share of the force (Hamulec->SetED, LSt and EStED valves). The brake works while the engine runs, with the direction set, the overload relay closed, the wheels rolling and no power asked for. Its force takes the place of the drive's in TractionForce(), the ammeter shows the motors' current, DynamicBrakeFlag lights the dynamic brake lamp. The traces of all 615 test cases recorded before the change compare bit for bit after it (EU07_UNIT_TESTS_GOLDEN_EXACT=1). --- McZapkie/MOVER.h | 30 +++ McZapkie/Mover.cpp | 131 ++++++++++++- tests/unit/test_dynamic_brake_diesel.cpp | 234 +++++++++++++++++++++++ 3 files changed, 390 insertions(+), 5 deletions(-) create mode 100644 tests/unit/test_dynamic_brake_diesel.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index b619ba7de..1411ff4bd 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1842,6 +1842,29 @@ class TMoverParameters int DynamicBrakeAmpmeters = 2; /*liczba amperomierzy przy hamowaniu ED*/ bool SplitEDPneumaticBrake = false; /*czy hamulec ED i pneumatyczny pomocniczy są rozdzielone na osobne nastawniki*/ int DynamicBrakeCtrlPosNo = 10; /*ilosc pozycji nastawnika hamulca ED (DBPN, domyslnie 10)*/ + // the dynamic brake of a diesel-electric vehicle (Engine: EDBrake=...): the traction motors brake into resistors while + // the engine runs, with the force of the definition rather than from a circuit, as the drive of these vehicles is + // computed from the generator's power. no definition, no dynamic brake (MaSzyna-EU07/maszyna#82) + struct diesel_electric_dynamic_brake + { + enum class control + { + none, + controller, // the negative range of the integrated controller (EIMCtrlType > 0), as the TRAXX one of the BR285 + lever // a lever of its own (the SplitEDPneumaticBrake one, DBPN steps), with the master controller at zero + }; + control source{control::none}; + double max_force{0.0}; // [N] at the wheel rims of the whole vehicle, EDBrakeFmax [kN] + double max_power{0.0}; // [W] the resistors take, EDBrakePmax [kW]; 0: no limit + double fade_low{0.0}; // [km/h] EDBrakeV0: no force below + double fade_high{0.0}; // [km/h] EDBrakeV1: the whole force above, rising in between + double rate{0.5}; // [1/s] EDBrakeRate: how fast the effort follows the demand + bool blending{false}; // EDBrakeBlending: the locomotive's train brake lets off while the dynamic brake works (Hamulec->SetED) + // state + double level{0.0}; // the effort, 0..1 + double force{0.0}; // [N] the braking force, against the motion + }; + diesel_electric_dynamic_brake DEDynamicBrake; double DynamicBrakeRes = 5.8; /*rezystancja oporników przy hamowaniu ED*/ double DynamicBrakeRes1 = 5.8; /*rezystancja oporników przy hamowaniu ED - 1 tryb*/ double DynamicBrakeRes2 = 5.8; /*rezystancja oporników przy hamowaniu ED - 2 tryb*/ @@ -2564,6 +2587,12 @@ class TMoverParameters void ComputeTotalForce(double dt); double Adhesive(double staticfriction) const; double TractionForce(double dt); + // the dynamic brake of a diesel-electric vehicle: the effort following the demand, the force it gives at the speed + void update_dieselelectric_dynamic_brake(double dt); + double dieselelectric_dynamic_brake_demand() const; // 0..1, the effort the driver asks for + double dieselelectric_dynamic_brake_limit() const; // [N] the force at full effort at the speed + void apply_dieselelectric_dynamic_brake(); // the force in place of the drive's one + double dieselelectric_motor_current(double Moment) const; // the current of the motors giving the moment double FrictionForce() const; double BrakeForceR(double ratio, double velocity) const; double BrakeForceP(double press, double velocity) const; @@ -2815,6 +2844,7 @@ class TMoverParameters void LoadFIZ_AI(std::string const &Input); void LoadFIZ_RList(std::string const &Input); void LoadFIZ_UCList(std::string const &Input); + void LoadFIZ_DieselElectricDynamicBrake(std::string const &Input); void LoadFIZ_DList(std::string const &Input); void LoadFIZ_FFList(std::string const &Input); void LoadFIZ_FFEDList(std::string const &Input); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..9c0b6b881 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -6119,6 +6119,11 @@ double TMoverParameters::TractionForce(double dt) } } + if (EngineType == TEngineType::DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) + { + update_dieselelectric_dynamic_brake(dt); + } + if (DirActive != 0) switch (EngineType) { @@ -6361,11 +6366,7 @@ double TMoverParameters::TractionForce(double dt) Mw = Fw * WheelDiameter / 2.0; // moment na osi kola Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego - // with MotorParam[ScndCtrlPos] do - if (abs(Mm) > motor_param(ScndCtrlPos).fi) - Im = NPoweredAxles * abs(abs(Mm) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); - else - Im = NPoweredAxles * sqrt(abs(Mm * motor_param(ScndCtrlPos).Isat)); + Im = dieselelectric_motor_current(Mm); if (ShuntMode) { @@ -6611,6 +6612,11 @@ double TMoverParameters::TractionForce(double dt) } } } + if (DEDynamicBrake.level > 0.0) + { + // braking: no power asked for, so the drive above gave no force + apply_dieselelectric_dynamic_brake(); + } break; } // DieselElectric @@ -6940,6 +6946,91 @@ double TMoverParameters::TractionForce(double dt) return Ft; } +// the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor +double TMoverParameters::dieselelectric_motor_current(double const Moment) const +{ + // with MotorParam[ScndCtrlPos] do + if (abs(Moment) > motor_param(ScndCtrlPos).fi) + return NPoweredAxles * abs(abs(Moment) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); + else + return NPoweredAxles * sqrt(abs(Moment * motor_param(ScndCtrlPos).Isat)); +} + +// the effort of a diesel-electric vehicle's dynamic brake the driver asks for, 0..1 +double TMoverParameters::dieselelectric_dynamic_brake_demand() const +{ + switch (DEDynamicBrake.source) + { + case diesel_electric_dynamic_brake::control::controller: + return std::clamp(-eimic_real, 0.0, 1.0); + case diesel_electric_dynamic_brake::control::lever: + return DynamicBrakeRatio(); + default: + return 0.0; + } +} + +// the force [N] of a diesel-electric vehicle's dynamic brake at full effort at the speed: the most the motors take +// (the current), above the speed where the resistors' power takes over, the power; under EDBrakeV1 it fades, down to +// nothing at EDBrakeV0. a brake of direct current motors, whose force grows with the speed (the voltage they generate +// into the resistors), fades from 0 to the speed of its whole force; an inverter's only at the stop +double TMoverParameters::dieselelectric_dynamic_brake_limit() const +{ + auto const &brake{DEDynamicBrake}; + auto limit{brake.max_force}; + if (brake.max_power > 0.0 && std::abs(V) > 0.0) + { + limit = std::min(limit, brake.max_power / std::abs(V)); + } + if (brake.fade_high > brake.fade_low) + { + limit *= std::clamp((Vel - brake.fade_low) / (brake.fade_high - brake.fade_low), 0.0, 1.0); + } + else if (Vel < brake.fade_low) + { + limit = 0.0; + } + return limit; +} + +// the dynamic brake of a diesel-electric vehicle, before the drive's force: the effort follows the demand, the force +// is the share of the most at the speed. the motors brake while the engine runs (it excites them, or keeps the +// control of the inverters going), with the direction set, the overload relay closed, no power asked for and the +// wheels rolling; otherwise there's no brake at once +void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) +{ + auto &brake{DEDynamicBrake}; + auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimic_real <= 0.0 : IsMainCtrlNoPowerPos()}; + if (Mains && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) + { + brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); + } + else + { + brake.level = 0.0; + } + brake.force = brake.level * dieselelectric_dynamic_brake_limit(); + DynamicBrakeFlag = brake.force > 0.0; + if (brake.blending) + { + // the train brake of the locomotive lets off by the share of the dynamic brake's force (LSt, EStED) + Hamulec->SetED(brake.max_force > 0.0 ? brake.force / brake.max_force : 0.0); + } +} + +// the force of a diesel-electric vehicle's dynamic brake, against the motion, in place of the drive's one: the motors +// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing +void TMoverParameters::apply_dieselelectric_dynamic_brake() +{ + Ft = V > 0.0 ? -DEDynamicBrake.force : V < 0.0 ? DEDynamicBrake.force : 0.0; + Fw = Ft / NPoweredAxles; + Mw = Fw * WheelDiameter / 2.0; + Mm = Mw / Transmision.Ratio; + Im = dieselelectric_motor_current(Mm); + EngineVoltage = 0.0; + EnginePower = 0.0; +} + // ************************************************************************************************* // Q: 20160713 // Obliczenie predkości obrotowej kół??? @@ -12021,6 +12112,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); extract_value(dizel_AIM, "AIM", Input, "1.25"); extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + LoadFIZ_DieselElectricDynamicBrake(Input); break; } case TEngineType::ElectricInductionMotor: @@ -12229,6 +12321,35 @@ void TMoverParameters::LoadFIZ_RList(std::string const &Input) extract_value(DynamicBrakeRes2, "DynBrakeRes2", Input, ""); } +// the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake +void TMoverParameters::LoadFIZ_DieselElectricDynamicBrake(std::string const &Input) +{ + using enum diesel_electric_dynamic_brake::control; + std::map> const sources{{"Controller", controller}, {"Lever", lever}}; + auto const lookup{sources.find(extract_value("EDBrake", Input))}; + if (lookup == sources.end()) + { + return; + } + auto &brake{DEDynamicBrake}; + brake.source = lookup->second; + auto force{0.0}; // [kN] + auto power{0.0}; // [kW] + extract_value(force, "EDBrakeFmax", Input, ""); + extract_value(power, "EDBrakePmax", Input, ""); + brake.max_force = force * 1000.0; + brake.max_power = power * 1000.0; + extract_value(brake.fade_low, "EDBrakeV0", Input, ""); + extract_value(brake.fade_high, "EDBrakeV1", Input, ""); + extract_value(brake.rate, "EDBrakeRate", Input, ""); + extract_value(brake.blending, "EDBrakeBlending", Input, ""); + if (brake.source == lever) + { + // the lever of its own, which the commands of the dynamic brake controller move + SplitEDPneumaticBrake = true; + } +} + void TMoverParameters::LoadFIZ_UCList(std::string const &Input) { diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp new file mode 100644 index 000000000..f0851d061 --- /dev/null +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -0,0 +1,234 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "drive.h" +#include "real_vehicles.h" + +#include "McZapkie/hamulce.h" + +// the dynamic brake of the diesel-electric vehicles (Engine: EDBrake=, MaSzyna-EU07/maszyna#82): the traction motors +// brake into resistors while the engine runs, with the force of the definition (EDBrakeFmax, the power limit +// EDBrakePmax, the fade below EDBrakeV1 down to EDBrakeV0), set either by the negative range of the integrated +// controller (EDBrake=Controller, the BR285's TRAXX controller) or by a lever of its own (EDBrake=Lever, the +// SplitEDPneumaticBrake one, with the master controller at zero) + +using test::definition; +using test::scenario; +using namespace test::channels; + +namespace { + +std::vector dynamic_brake() { + return { + {"EDLevel", [](auto const &M) { return M.DEDynamicBrake.level; }}, + {"EDForce", [](auto const &M) { return M.DEDynamicBrake.force; }}, + {"DynamicBrakeFlag", [](auto const &M) { return M.DynamicBrakeFlag ? 1.0 : 0.0; }}, + {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + {"DynamicBrakeCtrlPos", [](auto const &M) { return M.DynamicBrakeCtrlPos; }}, + }; +} + +// the BR285 with its dynamic brake: 150 kN up to the power limit of 2000 kW (48 km/h), fading out under 6 km/h +definition br285_braking() { + return definition::fiz("br285_v1/br285") + .set("Engine", "EDBrake", "Controller") + .set("Engine", "EDBrakeFmax", 150) + .set("Engine", "EDBrakePmax", 2000) + .set("Engine", "EDBrakeV0", 2) + .set("Engine", "EDBrakeV1", 6); +} + +// a resistor brake of a locomotive with direct current motors, on the ST44 (M62): a lever of 8 steps, the force +// growing with the speed up to 120 kN at 40 km/h, the resistors taking 1200 kW +definition st44_braking() { + return definition::fiz("st44_v2/m62-1151") + .set("Cntrl", "DBPN", 8) + .set("Engine", "EDBrake", "Lever") + .set("Engine", "EDBrakeFmax", 120) + .set("Engine", "EDBrakePmax", 1200) + .set("Engine", "EDBrakeV0", 0) + .set("Engine", "EDBrakeV1", 40); +} + +// the force of the brakes above at full effort at the speed of the vehicle +double br285_limit(TMoverParameters const &Vehicle) { + return std::min(150000.0, 2000000.0 / std::abs(Vehicle.V)) * std::clamp((Vehicle.Vel - 2.0) / 4.0, 0.0, 1.0); +} +double st44_limit(TMoverParameters const &Vehicle) { + return std::min(120000.0, 1200000.0 / std::abs(Vehicle.V)) * std::clamp(Vehicle.Vel / 40.0, 0.0, 1.0); +} + +// the controller of the BR285 down to the given position, a step a time +void controller_to(TMoverParameters &Locomotive, int Position) { + while (Locomotive.MainCtrlPos > Position && Locomotive.DecMainCtrl(1)) {} + while (Locomotive.MainCtrlPos < Position && Locomotive.IncMainCtrl(1)) {} +} + +} // namespace + +TEST_CASE("diesel-electric dynamic brake: none without its definition") { + // no game vehicle defines it: the diesel-electric ones load without, the BR285's braking positions brake nothing + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::vehicle vehicle{definition::fiz(path)}; + CHECK(vehicle->DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::none); + } + scenario scenario{"dynamic brake/diesel electric/br285 without", motion() + traction() + dynamic_brake()}; + scenario.add("br285_v1/br285", 1); + REQUIRE(scenario.start_up()); + auto &locomotive{scenario.cab()}; + scenario.get_going(); + scenario.full_power(40.0); + auto const speed{locomotive.Vel}; + REQUIRE(speed > 30.0); + scenario.act("braking range"); + controller_to(locomotive, 0); + scenario.wait(15.0); + CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + // coasting: braking with the power of the resistors above, it would lose more than 30 km/h + CHECK(locomotive.Vel > speed - 12.0); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { + // the braking positions of the TRAXX controller: EB+ raises the braking effort, EB holds it, EB- lowers it. + // the force is limited by the power of the resistors at speed, holds below that, fades out at the stop; the + // air brake stays off + scenario scenario{"dynamic brake/diesel electric/br285", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(br285_braking(), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::controller); + CHECK(locomotive.DEDynamicBrake.max_force == doctest::Approx(150000.0)); + CHECK(locomotive.DEDynamicBrake.max_power == doctest::Approx(2000000.0)); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(60.0); + REQUIRE(locomotive.Vel > 60.0); + + scenario.act("EB+"); + controller_to(locomotive, 0); + scenario.wait(10.0); + CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.DynamicBrakeFlag); + REQUIRE(locomotive.Vel > 6.0); + CHECK(-locomotive.Ft == doctest::Approx(br285_limit(locomotive)).epsilon(0.01)); + CHECK(locomotive.Im > 0.0); + CHECK(locomotive.EngineVoltage == doctest::Approx(0.0)); + CHECK(locomotive.BrakePress < 0.1); + + scenario.act("EB- to half"); + controller_to(locomotive, 2); + for (int i = 0; i < 20 && locomotive.eimic_real < -0.5; ++i) { + scenario.wait(1.0); + } + scenario.act("EB"); + controller_to(locomotive, 1); + scenario.wait(2.0); + auto const held{locomotive.eimic_real}; + CHECK(held == doctest::Approx(-0.5).epsilon(0.35)); + scenario.wait(5.0); + CHECK(locomotive.eimic_real == doctest::Approx(held)); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(-held).epsilon(0.01)); + + scenario.act("EB+ to the stop"); + controller_to(locomotive, 0); + for (int i = 0; i < 120 && locomotive.Vel > 20.0; ++i) { + scenario.wait(1.0); + } + // under the power limit the force holds + REQUIRE(locomotive.Vel < 40.0); + REQUIRE(locomotive.Vel > 6.0); + CHECK(-locomotive.Ft == doctest::Approx(150000.0).epsilon(0.01)); + for (int i = 0; i < 120 && locomotive.Vel > 4.0; ++i) { + scenario.wait(1.0); + } + // fading out + CHECK(-locomotive.Ft < 150000.0 * 0.6); + for (int i = 0; i < 120 && locomotive.Vel > 1.5; ++i) { + scenario.wait(1.0); + } + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + // it doesn't hold the train: the air brake does + CHECK(locomotive.Vel > 0.1); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") { + // on a locomotive with direct current motors the lever sets the excitation of the motors: the force grows with + // the speed, up to the limit of the current, then of the resistors' power. it works only with the master + // controller at zero and the engine running + scenario scenario{"dynamic brake/diesel electric/st44 lever", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(st44_braking(), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::lever); + CHECK(locomotive.SplitEDPneumaticBrake); + CHECK(locomotive.DynamicBrakeCtrlPosNo == 8); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(90.0); + REQUIRE(locomotive.Vel > 50.0); + + scenario.act("lever with power on"); + CHECK(locomotive.DynamicBrakeLevelSet(1.0)); + scenario.wait(5.0); + // the master controller at a power position keeps it off + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); + CHECK(locomotive.Ft > 0.0); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + + scenario.act("power off"); + scenario.notch_back(0); + scenario.wait(4.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.DynamicBrakeFlag); + CHECK(-locomotive.Ft == doctest::Approx(st44_limit(locomotive)).epsilon(0.01)); + CHECK(locomotive.ShowCurrent(0) > 0.0); + + scenario.act("half the lever"); + locomotive.DecDynamicBrakeLevel(4.0f); + CHECK(locomotive.DynamicBrakeCtrlPos == doctest::Approx(0.5)); + for (int i = 0; i < 300 && locomotive.Vel > 20.0; ++i) { + scenario.wait(1.0); + } + REQUIRE(locomotive.Vel < 21.0); + REQUIRE(locomotive.Vel > 10.0); + // on the rising part, half the excitation + CHECK(-locomotive.Ft == doctest::Approx(0.5 * st44_limit(locomotive)).epsilon(0.01)); + + scenario.act("engine off"); + locomotive.MainSwitch(false); + scenario.wait(1.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brake") { + // EDBrakeBlending: the LSt valve lets the train brake off the locomotive while the dynamic brake takes over + // (Hamulec->SetED with the share of the force it gives); without, both brake + for (auto const blending : {false, true}) { + CAPTURE(blending); + scenario scenario{std::format("dynamic brake/diesel electric/st44 blending {}", blending), motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(st44_braking().set("Engine", "EDBrakeBlending", blending ? "Yes" : "No"), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.blending == blending); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(150.0); + scenario.notch_back(0); + scenario.act("dynamic and train brake"); + locomotive.DynamicBrakeLevelSet(1.0); + locomotive.BrakeLevelSet(locomotive.Handle->GetPos(bh_FB)); + scenario.wait(6.0); + REQUIRE(locomotive.Vel > 15.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.PipePress < 4.6); + CHECK((locomotive.BrakePress < 0.2) == blending); + scenario.check(); + } +} From 8d2d9badb5723da49a7b4a7769f359b2817221fc Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 23:36:26 +0100 Subject: [PATCH 47/59] feat: own kind of animation for a door wing in the .mmd (eu07/maszyna#70) A vehicle can now have door wings of different kinds on one side, e.g. 111Ainw (Bdhinu) with folding doors at one end and wider ones at the other. A new optional entry in the models section of the .mmd: animdoor: { type: range: rangeout: } gives one wing (door1, door2... of animdoorprefix) its own kind of animation and range; the keys left out keep the values of the .fiz. The wing still follows the door of its side: it is as far along its own range as the door is along DoorMaxShift. The entry may come before or after animdoorprefix; a faulty one is logged and the wing keeps the .fiz kind. Wings without an entry get the same update functions as before, so the existing vehicles, .mmd and .fiz files are unchanged. The door state, the physics, AI, cab controls, sounds and exports are not touched. The parsing and the wing position live in vehicle/doorwings.h, tested in test_door_wings.cpp. --- tests/unit/test_door_wings.cpp | 117 +++++++++++++++++++++++++++ vehicle/DynObj.cpp | 102 ++++++++++++++++++++---- vehicle/DynObj.h | 7 ++ vehicle/doorwings.h | 139 +++++++++++++++++++++++++++++++++ 4 files changed, 348 insertions(+), 17 deletions(-) diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp index 290260f6a..e049d6c61 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -2,6 +2,7 @@ #include "doctest.h" #include "vehicle/doorwings.h" +#include "utilities/parser.h" // the poses of the animated door wings (eu07/maszyna#512): a wing of the main model and its namesake in the low // poly interior get the same pose, worked out once from the door position of the mover @@ -52,3 +53,119 @@ TEST_CASE("door wings: a folding wing turns one way and its larger wing twice as CHECK(closed.larger == 0.f); CHECK(closed.step == 0.f); } + +// a wing with its own kind of animation (eu07/maszyna#70): animdoor: in the .mmd, for vehicles whose doors on one side +// aren't all alike, e.g. 111Ainw with folding doors at one end and wider ones at the other + +namespace { + +// the spec of the .fiz the entries start from: folding doors which turn by 80 degrees +door_wings::wing_spec const fizdoors{0, door_wings::fold_type, 80.f, 0.f}; + +// reads the entry after animdoor: from the text, starting from the spec of the .fiz +std::string read(std::string const &Entry, door_wings::wing_spec &Spec) { + Spec = fizdoors; + cParser parser(Entry, cParser::buffer_TEXT); + return door_wings::read_spec(parser, Spec); +} + +} // namespace + +TEST_CASE("door wings: the kinds of animation are named as DoorOpenMethod of the .fiz") { + CHECK(door_wings::type_from_name("Shift") == door_wings::shift_type); + CHECK(door_wings::type_from_name("Rotate") == door_wings::rotate_type); + CHECK(door_wings::type_from_name("Fold") == door_wings::fold_type); + CHECK(door_wings::type_from_name("Plug") == door_wings::plug_type); + // in any letter case + CHECK(door_wings::type_from_name("plug") == door_wings::plug_type); + CHECK(door_wings::type_from_name("SHIFT") == door_wings::shift_type); + // the same numbers as TMoverParameters::door_data::type + CHECK(door_wings::shift_type == 1); + CHECK(door_wings::rotate_type == 2); + CHECK(door_wings::fold_type == 3); + CHECK(door_wings::plug_type == 4); + CHECK_FALSE(door_wings::type_from_name("Roll").has_value()); + CHECK_FALSE(door_wings::type_from_name("").has_value()); +} + +TEST_CASE("door wings: an animdoor entry gives the wing its own kind, range and plug shift") { + door_wings::wing_spec spec; + CHECK(read("3 { type: Plug range: 0.9 rangeout: 0.06 } endmodels", spec).empty()); + CHECK(spec.number == 3); + CHECK(spec.type == door_wings::plug_type); + CHECK(spec.range == doctest::Approx(0.9f)); + CHECK(spec.range_out == doctest::Approx(0.06f)); +} + +TEST_CASE("door wings: the keys an animdoor entry leaves out keep the values of the .fiz") { + door_wings::wing_spec spec; + SUBCASE("only the kind") { + CHECK(read("2 { type: Rotate }", spec).empty()); + CHECK(spec.number == 2); + CHECK(spec.type == door_wings::rotate_type); + CHECK(spec.range == 80.f); + CHECK(spec.range_out == 0.f); + } + SUBCASE("only the range, keys in any letter case and order") { + CHECK(read("1 { Range: -95 }", spec).empty()); + CHECK(spec.type == door_wings::fold_type); + CHECK(spec.range == -95.f); + } + SUBCASE("nothing") { + CHECK(read("4 { }", spec).empty()); + CHECK(spec.number == 4); + CHECK(spec.type == fizdoors.type); + CHECK(spec.range == fizdoors.range); + } +} + +TEST_CASE("door wings: a faulty animdoor entry says what is wrong with it") { + door_wings::wing_spec spec; + CHECK(read("3 type: Shift range: 0.65", spec) == "no { after the wing number"); + CHECK(read("3 { type: Roll range: 0.65 }", spec) == "unknown door type \"Roll\""); + CHECK(read("3 { type: Shift range: 0,65 }", spec) == "bad number \"0,65\" for \"range:\""); + CHECK(read("3 { type: Shift range: wide }", spec) == "bad number \"wide\" for \"range:\""); + CHECK(read("3 { kind: Shift }", spec) == "unknown key \"kind:\""); + CHECK(read("3 { type: Shift range: }", spec) == "no value for \"range:\""); + CHECK(read("3 { type: Shift range: 0.65", spec) == "no } after the keys"); +} + +TEST_CASE("door wings: the parsed keys go into the spec, pairs of a key and its value") { + door_wings::wing_spec spec{fizdoors}; + CHECK(door_wings::parse_spec({"type:", "Shift", "range:", "0.65"}, spec).empty()); + CHECK(spec.type == door_wings::shift_type); + CHECK(spec.range == doctest::Approx(0.65f)); + CHECK(door_wings::parse_spec({"rangeout:"}, spec) == "no value for \"rangeout:\""); + CHECK(door_wings::parse_spec({}, spec).empty()); +} + +TEST_CASE("door wings: only the wings with an entry animate in their own way, the latest entry counts") { + std::vector specs; + CHECK(door_wings::find(specs, 1) == nullptr); + door_wings::store(specs, {3, door_wings::shift_type, 0.65f, 0.f}); + door_wings::store(specs, {4, door_wings::shift_type, 0.65f, 0.f}); + door_wings::store(specs, {3, door_wings::plug_type, 0.9f, 0.06f}); + CHECK(specs.size() == 2); + CHECK(door_wings::find(specs, 1) == nullptr); + CHECK(door_wings::find(specs, 2) == nullptr); + REQUIRE(door_wings::find(specs, 3) != nullptr); + CHECK(door_wings::find(specs, 3)->type == door_wings::plug_type); + CHECK(door_wings::find(specs, 3)->range == 0.9f); + REQUIRE(door_wings::find(specs, 4) != nullptr); + CHECK(door_wings::find(specs, 4)->type == door_wings::shift_type); +} + +TEST_CASE("door wings: a wing with its own range is as far along it as the door of its side") { + // folding doors of the .fiz turn by 80 degrees; the wide wing slides by 0.9 m + CHECK(door_wings::wing_position(0.f, 80.f, 0.9f) == 0.f); + CHECK(door_wings::wing_position(40.f, 80.f, 0.9f) == doctest::Approx(0.45f)); + CHECK(door_wings::wing_position(80.f, 80.f, 0.9f) == doctest::Approx(0.9f)); + // a wing turning the other way + CHECK(door_wings::wing_position(20.f, 80.f, -100.f) == doctest::Approx(-25.f)); + // no doors in the .fiz: the wing stays closed + CHECK(door_wings::wing_position(0.f, 0.f, 0.9f) == 0.f); + // the pose of the plug wing at the end of its range + auto const open{door_wings::plug(door_wings::wing_position(80.f, 80.f, 0.9f), 0.06f)}; + CHECK(open.x == doctest::Approx(0.06f)); + CHECK(open.z == doctest::Approx(0.87f)); +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..0bfcdac75 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -700,6 +700,62 @@ void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { } } +// a wing animated in its own way (animdoor: of the .mmd): as far along its own range as the door of its side is +void TDynamicObject::UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const position { door_wings::wing_position( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range, Spec.range ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing == nullptr ) { continue; } + switch( Spec.type ) { + case door_wings::shift_type: { + wing->SetTranslate( door_wings::slide( position ) ); + break; + } + case door_wings::rotate_type: { + wing->SetRotate( float3( 1, 0, 0 ), position ); + break; + } + case door_wings::fold_type: { + fold_wing( wing, door_wings::fold( position ) ); + break; + } + case door_wings::plug_type: { + wing->SetTranslate( door_wings::plug( position, Spec.range_out ) ); + break; + } + default: { + break; + } + } + } +} + +void TDynamicObject::bind_door_animation( TAnim &Animation ) { + + if( auto const *spec { door_wings::find( m_doorwings, Animation.iNumber ) } ) { + Animation.yUpdate = [ this, spec = *spec ]( TAnim *pAnim ) { UpdateDoorWing( pAnim, spec ); }; + return; + } + switch( MoverParameters->Doors.type ) { // od razu zapinamy potrzebny typ animacji + case 1: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); + break; + case 2: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); + break; + case 3: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); + break; // obrót 3 kolejnych submodeli + case 4: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); + break; + default: + break; + } +} + void TDynamicObject::UpdatePant(TAnim *pAnim) { // animacja pantografu - 4 obracane ramiona, ślizg piąty float a, b, c; @@ -5882,24 +5938,8 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co if (pAnimations[i + j].smAnimated) { //++iAnimatedDoors; pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - switch( MoverParameters->Doors.type ) - { // od razu zapinamy potrzebny typ animacji - case 1: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); - break; - case 2: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); - break; - case 3: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); - break; // obrót 3 kolejnych submodeli - case 4: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); - break; - default: - break; - } pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste + bind_door_animation( pAnimations[ i + j ] ); // od razu zapinamy potrzebny typ animacji pAnimations[i + j].fMaxDist = 300 * 300; // drzwi to z daleka widać /* // NOTE: no longer used @@ -5910,6 +5950,34 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } + else if( token == "animdoor:" ) { + // own kind of animation of one door wing, in place of the one of the .fiz (eu07/maszyna#70): + // animdoor: { type: range: rangeout: } + // the keys left out keep the values of the .fiz. the wing still follows the door of its side + door_wings::wing_spec spec { + 0, + MoverParameters->Doors.type, + MoverParameters->Doors.range, + MoverParameters->Doors.range_out }; + auto error { door_wings::read_spec( parser, spec ) }; + if( error.empty() + && ( spec.number < 1 || spec.number > iAnimType[ ANIM_DOORS ] ) ) { + error = "no door wing " + std::to_string( spec.number ) + " among the door animations"; + } + if( false == error.empty() ) { + ErrorLog( "Bad model: " + asFileName + " - animdoor: " + error, logtype::model ); + } + else { + door_wings::store( m_doorwings, spec ); + // a wing animdoorprefix has found already gets the new kind of animation now; the ones it + // finds later get it then + auto const index { static_cast( std::accumulate( std::begin( iAnimType ), std::begin( iAnimType ) + ANIM_DOORS, 0 ) + spec.number - 1 ) }; + if( index < pAnimations.size() && pAnimations[ index ].yUpdate ) { + bind_door_animation( pAnimations[ index ] ); + } + } + } + else if( token == "animstepprefix:" ) { // animated doorstep submodel name prefix int i, j; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 49b23c959..c0a7bc1cf 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "audio/sound.h" #include "world/Spring.h" #include "vehicle/mirrors.h" +#include "vehicle/doorwings.h" #include "scripting/scriptscreenrules.h" #include @@ -305,6 +306,12 @@ private: void UpdateDoorRotate(TAnim *pAnim); // animacja drzwi - obrót void UpdateDoorFold(TAnim *pAnim); // animacja drzwi - składanie void UpdateDoorPlug(TAnim *pAnim); // animacja drzwi - odskokowo-przesuwne + // a wing with its own kind of animation, given in the .mmd (animdoor:), in place of the one of the .fiz + void UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ); + // sets the update of a door wing animation, for its own kind if the .mmd gives one, otherwise for the .fiz + void bind_door_animation( TAnim &Animation ); + // door wings animated in their own way, from the .mmd (eu07/maszyna#70) + std::vector m_doorwings; void UpdatePant(TAnim *pAnim); // animacja pantografu void UpdatePlatformTranslate(TAnim *pAnim); // doorstep animation, shift void UpdatePlatformRotate(TAnim *pAnim); // doorstep animation, rotate diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index 07286aac8..1266dafec 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -10,6 +10,13 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include +#include +#include +#include +#include +#include +#include #include @@ -17,6 +24,12 @@ http://mozilla.org/MPL/2.0/. // in the main model and, when the low poly interior has a submodel of the same name, in the interior as well namespace door_wings { +// the kinds of wing animation, numbered as DoorOpenMethod of the .fiz (TMoverParameters::door_data::type) +inline constexpr int shift_type{1}; +inline constexpr int rotate_type{2}; +inline constexpr int fold_type{3}; +inline constexpr int plug_type{4}; + // whether the animation with the given flags (TAnim::iFlags, the kind of animation in bits 4-7) moves a door wing inline bool is_wing(int const Flags) { return (Flags & 0xF0) == 0x10; @@ -49,4 +62,130 @@ inline fold_angles fold(float const Position) { return {Position, -Position - Position, Position}; } +// the animation of one wing given in the .mmd, in place of the one the .fiz sets for all door wings of the vehicle +// (eu07/maszyna#70). the wing still follows the door of its side, over its own range: +// animdoor: { type: range: rangeout: } +// every key is optional; a key left out keeps the value of the .fiz +struct wing_spec { + int number{0}; // of the wing, as in animdoorprefix: door1 is 1 + int type{rotate_type}; + float range{0.f}; // shift or angle of the wing when the door is fully open + float range_out{0.f}; // how far a plug wing is pushed out +}; + +// the kind of wing animation with the given name of DoorOpenMethod, in any letter case +inline std::optional type_from_name(std::string_view const Name) { + std::string name{Name}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (name == "shift") { + return shift_type; + } + if (name == "rotate") { + return rotate_type; + } + if (name == "fold") { + return fold_type; + } + if (name == "plug") { + return plug_type; + } + return std::nullopt; +} + +// the number written in the whole of the text, or nothing +inline std::optional number_from_text(std::string const &Text) { + if (Text.empty()) { + return std::nullopt; + } + char *end{nullptr}; + auto const value{std::strtof(Text.c_str(), &end)}; + if (end != Text.c_str() + Text.size() || false == std::isfinite(value)) { + return std::nullopt; + } + return value; +} + +// applies the keys and values of the block of an animdoor entry (the tokens between the braces) to the spec, which +// comes filled with the values of the .fiz. returns what is wrong with the block, or an empty text when nothing is; +// the keys before the fault are applied +inline std::string parse_spec(std::vector const &Tokens, wing_spec &Spec) { + for (std::size_t index = 0; index < Tokens.size(); index += 2) { + std::string key{Tokens[index]}; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (index + 1 >= Tokens.size()) { + return "no value for \"" + key + "\""; + } + auto const &value{Tokens[index + 1]}; + if (key == "type:") { + auto const type{type_from_name(value)}; + if (false == type.has_value()) { + return "unknown door type \"" + value + "\""; + } + Spec.type = *type; + } + else if (key == "range:" || key == "rangeout:") { + auto const number{number_from_text(value)}; + if (false == number.has_value()) { + return "bad number \"" + value + "\" for \"" + key + "\""; + } + (key == "range:" ? Spec.range : Spec.range_out) = *number; + } + else { + return "unknown key \"" + key + "\""; + } + } + return {}; +} + +// reads an animdoor entry after its key: the wing number and the block in braces, into the spec filled with the values +// of the .fiz. returns what is wrong with the entry, or an empty text when nothing is. the parser is a cParser +template +std::string read_spec(Parser_ &Parser, wing_spec &Spec) { + Parser.getTokens(1, false); + Parser >> Spec.number; + std::string token; + Parser.getTokens(1, false); + Parser >> token; + if (token != "{") { + return "no { after the wing number"; + } + std::vector block; + while (true) { + token.clear(); + Parser.getTokens(1, false); + Parser >> token; + if (token.empty()) { + return "no } after the keys"; + } + if (token == "}") { + break; + } + block.emplace_back(token); + } + return parse_spec(block, Spec); +} + +// the spec given for the wing with the given number, or null when the wing animates as the .fiz says +inline wing_spec const *find(std::vector const &Specs, int const Number) { + auto const lookup{std::find_if(Specs.begin(), Specs.end(), [Number](wing_spec const &Spec) { return Spec.number == Number; })}; + return lookup != Specs.end() ? &(*lookup) : nullptr; +} + +// keeps the spec of a wing; a later entry for the same wing replaces the earlier one +inline void store(std::vector &Specs, wing_spec const &Spec) { + auto lookup{std::find_if(Specs.begin(), Specs.end(), [&Spec](wing_spec const &Stored) { return Stored.number == Spec.number; })}; + if (lookup != Specs.end()) { + *lookup = Spec; + } + else { + Specs.emplace_back(Spec); + } +} + +// the shift or angle of a wing which opens over Wingrange, while the door of its side opens over Doorrange: the wing +// is as far along its range as the door is along the door range +inline float wing_position(float const Doorposition, float const Doorrange, float const Wingrange) { + return Doorrange != 0.f ? Doorposition / Doorrange * Wingrange : 0.f; +} + } // namespace door_wings From aa84e41f0984e38b26a4f0e663ba77e2111748d8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 00:17:22 +0100 Subject: [PATCH 48/59] feat: timetable service flags for the AI driver (eu07/maszyna#95) A timetable can now tell the AI how the train is served, for trams, underground trains and the like. The whole train gets them from a new row of the first box of the header: [ Flagi AI | drzwi_centralne=tak,stopien=nie,kierownik=nie,proba_hamulca=nie ] and a station changes them from there on with entries of its station ware (the second line of the station, next to R2, ph, @): [ | | po,kierownik=nie 1 12.54 | ] - drzwi_centralne=tak: the driver opens all the doors from the cab, those of mixed control too (otherwise left to the passengers) - stopien=tak/nie: the doorsteps switched on/off before the doors open (the AI didn't touch them before; new driver hints for it) - kierownik=nie: no conductor, so no departure signal (direct or by radio) and no first door kept open for him before the departure - proba_hamulca=nie: no running brake test A flag left out keeps today's behaviour, so a timetable without flags drives as before. Old builds skip the header row and keep the station entries as station ware text (none starts with R or holds @, po, pt). The reader moves out of TTrainParameters::LoadTTfile into world/timetablereader.cpp (eu07_core) unchanged, so the tests can run it; the flags come out of the station ware there. It now ends at the end of the file with an error where the old one spun forever (a truncated file, a missing number), and stops at 100 stations instead of writing past the table. Every .txt of the game's sceneries and of the SVN data reads the same as with the old reader (compared field by field against a verbatim copy of it); EU07_UNIT_TESTS_TIMETABLES= reads them in the unit tests and EU07_UNIT_TESTS_TIMETABLES_DUMP writes what was read. --- CMakeLists.txt | 3 + application/driverhints.cpp | 23 +++ application/driverhints_def.h | 2 + tests/unit/test_timetable.cpp | 321 ++++++++++++++++++++++++++++++++++ vehicle/Driver.cpp | 26 ++- vehicle/Driver.h | 1 + vehicle/timetableservice.cpp | 49 ++++++ vehicle/timetableservice.h | 37 ++++ world/mtable.cpp | 307 +++----------------------------- world/mtable.h | 25 +-- world/timetableflags.cpp | 103 +++++++++++ world/timetableflags.h | 59 +++++++ world/timetablereader.cpp | 321 ++++++++++++++++++++++++++++++++++ world/timetablereader.h | 66 +++++++ 14 files changed, 1038 insertions(+), 305 deletions(-) create mode 100644 tests/unit/test_timetable.cpp create mode 100644 vehicle/timetableservice.cpp create mode 100644 vehicle/timetableservice.h create mode 100644 world/timetableflags.cpp create mode 100644 world/timetableflags.h create mode 100644 world/timetablereader.cpp create mode 100644 world/timetablereader.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..7fb845ba3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -553,6 +553,9 @@ set(CORE_SOURCES "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" +"vehicle/timetableservice.cpp" +"world/timetableflags.cpp" +"world/timetablereader.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 0c6f02cc8..2c3fbd66b 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -1150,6 +1150,29 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return IsAnyDoorPermitActive[side::left] == false; } ); break; } + // doorsteps, as the timetable asks (eu07/maszyna#95) + case driver_hint::doorstepon: { + if( AIControllFlag ) { + mvOccupied->PermitDoorStep( true ); + } + remove_hint( driver_hint::doorstepoff ); + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->Doors.step_enabled == true; } ); + break; + } + case driver_hint::doorstepoff: { + if( AIControllFlag ) { + mvOccupied->PermitDoorStep( false ); + } + remove_hint( driver_hint::doorstepon ); + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->Doors.step_enabled == false; } ); + break; + } // consist lights case driver_hint::consistlightson: { if( AIControllFlag ) { diff --git a/application/driverhints_def.h b/application/driverhints_def.h index 2ce896679..6f5c86474 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -72,6 +72,8 @@ DRIVER_HINT_DEF(doorrightpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorrightpermitoff, STRN("Revoke permit to open doors")) DRIVER_HINT_DEF(doorleftpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorleftpermitoff, STRN("Revoke permit to open doors")) +DRIVER_HINT_DEF(doorstepon, STRN("Switch on doorsteps")) +DRIVER_HINT_DEF(doorstepoff, STRN("Switch off doorsteps")) DRIVER_HINT_DEF(hornon, STRN("Sound the horn")) DRIVER_HINT_DEF(hornoff, STRN("Switch off horn")) DRIVER_HINT_DEF(consistlightson, STRN("Switch on consist lights")) diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp new file mode 100644 index 000000000..f4387e7f8 --- /dev/null +++ b/tests/unit/test_timetable.cpp @@ -0,0 +1,321 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "McZapkie/MOVER.h" +#include "utilities/utilities.h" +#include "vehicle/timetableservice.h" +#include "world/timetablereader.h" + +#include +#include +#include +#include +#include + +// the timetables of the trains (.txt next to the scenery, world/timetablereader.cpp) and the service flags they +// give the AI driver (eu07/maszyna#95): the reader as it was, the flags of the header and of the stations, and what +// the driver does with them + +using timetable::service_flags; +using timetable::tristate; + +namespace { + +// a timetable the way the game's sceneries have them: the header, three stations, a speed change at the second one +std::string const timetable_text{ + " ___________________________________________________________________\n" + "[ Rodzaj i numer pociagu | Os1234 ]\n" + "[ Kategoria | Os ]\n" + "%FLAGS%" + "[________________________________________________|__________________]\n" + "[ | Gorna ]\n" + "[ Relacja pociagu | Dolna ]\n" + "[________________________________________________|__________________]\n" + "[ Wymagany % ciezaru hamujacego | 60% ]\n" + "[________________________________________________|__________________]\n" + "[ Seria i obciazenie lokomotywy | EN57 120 ]\n" + "[________________________________________________|__________________]\n" + "[ 1.13 | 60 | Gorna 1 | | ]\n" + "[ | | %WARE1% 1 12.47 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 5.06 |_____| Srodkowa 1 12.54 | 7 ]\n" + "[ | 40 | %WARE2% 1 12.55 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 9.16 | | Dolna 2 13.01 | 6 ]\n" + "[ | | %WARE3% 2 | | ]\n" + "[_______|_____|__________________________________2_________|________]\n"}; + +std::string replaced(std::string Text, std::string const &Key, std::string const &Value) { + for (auto at{Text.find(Key)}; at != std::string::npos; at = Text.find(Key, at + Value.size())) { + Text.replace(at, Key.size(), Value); + } + return Text; +} + +std::string timetable_with(std::string const &Flags, std::string const &Ware1, std::string const &Ware2, std::string const &Ware3) { + return replaced(replaced(replaced(replaced(timetable_text, "%FLAGS%", Flags), "%WARE1%", Ware1), "%WARE2%", Ware2), "%WARE3%", Ware3); +} + +struct read_result { + int error; + Mtable::timetable_data data; +}; + +read_result read(std::string const &Text) { + std::istringstream input{Text}; + read_result result; + result.data.TrainName = "file"; + result.error = Mtable::read_timetable(input, result.data); + return result; +} + +service_flags flags(tristate const Doors, tristate const Doorstep, tristate const Conductor, tristate const Braketest) { + return {Doors, Doorstep, Conductor, Braketest}; +} + +auto const unset{tristate::unset}; +auto const yes{tristate::yes}; +auto const no{tristate::no}; + +// what the timetable gives, but for the service flags: to compare a timetable with flags to one without +std::string contents(Mtable::timetable_data const &Data) { + auto text{std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}\n", Data.TrainName, Data.TrainCategory, Data.TrainLabel, Data.Relation1, Data.Relation2, Data.BrakeRatio, + Data.LocSeries, Data.LocLoad, Data.StationCount)}; + for (auto i{0}; i <= Data.StationCount; ++i) { + auto const &row{Data.TimeTable[i]}; + text += std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}\n", i, row.km, row.vmax, row.StationName, row.StationWare, row.TrackNo, row.Ah, row.Am, row.Dh, row.Dm, + row.tm, row.is_maintenance, row.radio_channel); + } + return text; +} + +std::string flags_text(service_flags const &Flags) { + auto const one{[](tristate const Flag) { return Flag == tristate::unset ? '-' : Flag == tristate::yes ? 'y' : 'n'; }}; + return {one(Flags.central_doors), one(Flags.doorstep), one(Flags.conductor), one(Flags.brake_test)}; +} + +} // namespace + +TEST_CASE("timetable: the reader reads a timetable the way it always did") { + auto const [error, data]{read(timetable_with("", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.Relation2 == "Dolna"); + CHECK(data.BrakeRatio == 60.0); + CHECK(data.LocSeries == "EN57"); + CHECK(data.LocLoad == 120.0); + REQUIRE(data.StationCount == 3); + + auto const &first{data.TimeTable[1]}; + CHECK(first.StationName == "Gorna"); + CHECK(first.km == doctest::Approx(1.13)); + CHECK(first.Ah == -1); // no arrival: LoadTTfile makes it a stop, the first station being the start of the relation + CHECK(first.Dh == 12); + CHECK(first.Dm == 47.f); + CHECK(first.StationWare == "R2,H"); + CHECK(first.radio_channel == 2); + + auto const &second{data.TimeTable[2]}; + CHECK(second.StationName == "Srodkowa"); + CHECK(second.Ah == 12); + CHECK(second.Am == 54.f); + CHECK(second.Dm == 55.f); + CHECK(second.tm == 7.f); + CHECK(second.StationWare == "po"); + CHECK(second.radio_channel == -1); + + auto const &last{data.TimeTable[3]}; + CHECK(last.StationName == "Dolna"); + CHECK(last.TrackNo == 2); + CHECK(last.Ah == 13); + CHECK(last.Dh == 13); // departure as the arrival, for the delay + CHECK(last.radio_channel == 3); + // 60 km/h up to the change at the second station, 40 km/h after it + CHECK(data.TimeTable[1].vmax == 60.f); + CHECK(data.TimeTable[2].vmax == 60.f); + CHECK(data.TimeTable[3].vmax == 40.f); + // a timetable without flags leaves all of them to the vehicles + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } +} + +TEST_CASE("timetable: the row Flagi of the header sets the flags of the whole train") { + auto const [error, data]{read(timetable_with("[ Flagi AI | kierownik=nie, proba_hamulca=nie ]\n", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.Flags == flags(unset, unset, no, no)); + // every station has them + for (auto i{0}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].flags == data.Flags); + } + // and the rest of the header reads as before + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a station's flags hold from that station on") { + auto const [error, data]{read(timetable_with("[ Flagi AI | proba_hamulca=nie ]\n", "R2,H", "po,stopien=nie,drzwi_centralne=tak", "R3,stopien=tak"))}; + + CHECK(error == 0); + CHECK(data.TimeTable[1].flags == flags(unset, unset, unset, no)); + CHECK(data.TimeTable[2].flags == flags(yes, no, unset, no)); + CHECK(data.TimeTable[3].flags == flags(yes, yes, unset, no)); + // the flags are taken out of the station ware, the rest of it stays + CHECK(data.TimeTable[2].StationWare == "po"); + CHECK(data.TimeTable[3].StationWare == "R3"); + CHECK(data.TimeTable[3].radio_channel == 3); +} + +TEST_CASE("timetable: the flags change nothing else the timetable gives") { + auto const plain{read(timetable_with("", "R2,H", "po", "R3"))}; + auto const flagged{read(timetable_with("[ Flagi AI | kierownik=nie ]\n", "kierownik=tak,R2,H", "po,drzwi_centralne=tak", "R3,stopien=nie,proba_hamulca=nie"))}; + + CHECK(flagged.error == plain.error); + CHECK(contents(flagged.data) == contents(plain.data)); +} + +TEST_CASE("timetable: entries which aren't flags stay in the station ware") { + service_flags read_flags; + SUBCASE("no flags: the list as it was, empty entries too") { + CHECK(timetable::extract_flags("po,,R2", read_flags) == "po,,R2"); + CHECK(timetable::extract_flags("", read_flags).empty()); + CHECK(read_flags.empty()); + } + SUBCASE("an unknown key stays, a known one with an unknown value is dropped") { + CHECK(timetable::extract_flags("po,foo=1,kierownik=moze,R2", read_flags) == "po,foo=1,R2"); + CHECK(read_flags.empty()); + } + SUBCASE("keys and values in either case, 1 and 0 for tak and nie") { + CHECK(timetable::extract_flags("Kierownik=NIE,STOPIEN=1,ph", read_flags) == "ph"); + CHECK(read_flags == flags(unset, yes, no, unset)); + } +} + +TEST_CASE("timetable: a truncated timetable is an error, not a hang") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + // cut in the middle of a station, in the middle of the header, right after the top line: the reader used to go + // on reading past the end of the file forever + for (auto const cut : {text.find("Srodkowa"), text.find("Wymagany"), text.find("Rodzaj")}) { + CAPTURE(cut); + auto const [error, data]{read(text.substr(0, cut))}; + CHECK(error == Mtable::timetable_truncated); + } + // cut between two stations: the row the reader expects isn't there + auto const [error, data]{read(text.substr(0, text.find("[ 9.16")))}; + CHECK(error == -4); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a timetable longer than the table is an error") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const begin{text.find("[ 5.06")}; + auto const end{text.find("[ 9.16")}; + auto const station{text.substr(begin, end - begin)}; + std::string stations; + for (auto i{0}; i < Mtable::MaxTTableSize; ++i) { + stations += station; + } + auto const [error, data]{read(text.substr(0, begin) + stations + text.substr(end))}; + CHECK(error == Mtable::timetable_too_long); + CHECK(data.StationCount == Mtable::MaxTTableSize); +} + +TEST_CASE("timetable: the entry whose flags hold at the stop and on the way") { + // before the timetable is loaded, and with none + CHECK(timetable::stop_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(1, 0) == 0); + // making for (or standing at) the first station: its flags at the stop, the header's on the way + CHECK(timetable::stop_flags_entry(1, 3) == 1); + CHECK(timetable::run_flags_entry(1, 3) == 0); + // after the departure from the second station + CHECK(timetable::stop_flags_entry(3, 3) == 3); + CHECK(timetable::run_flags_entry(3, 3) == 2); + // past the end of the timetable + CHECK(timetable::stop_flags_entry(4, 3) == 3); + CHECK(timetable::run_flags_entry(5, 3) == 3); +} + +TEST_CASE("timetable: the AI opens the doors from the cab as the vehicle and the timetable say") { + test::vehicle unit{test::definition::load("wagon")}; + auto const central{flags(yes, unset, unset, unset)}; + auto const notcentral{flags(no, unset, unset, unset)}; + + unit->Doors.open_control = control_t::driver; + CHECK(timetable::opens_doors(unit.mover(), {})); + CHECK(timetable::opens_doors(unit.mover(), notcentral)); // the driver's doors open only from the cab + unit->Doors.open_control = control_t::conductor; + CHECK(timetable::opens_doors(unit.mover(), {})); + // doors of mixed control are left to the passengers, unless the timetable has the driver open them all + unit->Doors.open_control = control_t::mixed; + CHECK_FALSE(timetable::opens_doors(unit.mover(), {})); + CHECK_FALSE(timetable::opens_doors(unit.mover(), notcentral)); + CHECK(timetable::opens_doors(unit.mover(), central)); + // the passengers' own doors and the automatic ones can't be opened from the cab + unit->Doors.open_control = control_t::passenger; + CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); + unit->Doors.open_control = control_t::autonomous; + CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); +} + +TEST_CASE("timetable: the doorsteps, the conductor and the brake test as the timetable says") { + // no flags: the doorsteps as they are, the conductor and the brake test as before + CHECK_FALSE(timetable::doorstep({}).has_value()); + CHECK(timetable::has_conductor({})); + CHECK(timetable::makes_brake_test({})); + + CHECK(timetable::doorstep(flags(unset, no, unset, unset)) == false); + CHECK(timetable::doorstep(flags(unset, yes, unset, unset)) == true); + CHECK_FALSE(timetable::has_conductor(flags(unset, unset, no, unset))); + CHECK(timetable::has_conductor(flags(unset, unset, yes, unset))); + CHECK_FALSE(timetable::makes_brake_test(flags(unset, unset, unset, no))); + CHECK(timetable::makes_brake_test(flags(unset, unset, unset, yes))); +} + +// reads every .txt file under the folder given in EU07_UNIT_TESTS_TIMETABLES (the scenery/ of the game), the way the +// game reads a timetable, and checks none of them has flags; EU07_UNIT_TESTS_TIMETABLES_DUMP names a file to write +// what was read to, to compare the reading of two builds +TEST_CASE("timetable: the timetables of the game, when asked for") { + auto const *source{std::getenv("EU07_UNIT_TESTS_TIMETABLES")}; + if (source == nullptr) { + return; + } + std::vector files; + for (auto const &entry : std::filesystem::recursive_directory_iterator{source}) { + if (entry.is_regular_file() && ToLower(entry.path().extension().string()) == ".txt") { + files.push_back(entry.path()); + } + } + std::ranges::sort(files); + std::string dump; + auto timetables{0}; + for (auto const &file : files) { + auto const name{std::filesystem::relative(file, source).generic_string()}; + CAPTURE(name); + std::ifstream input{file}; + Mtable::timetable_data data; + data.TrainName = file.stem().string(); + auto const error{Mtable::read_timetable(input, data)}; + if (error == 0 && data.StationCount > 0) { + ++timetables; + } + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } + dump += std::format("== {} error {}\n", name, error) + contents(data); + } + MESSAGE(std::format("{} files, {} read as timetables", files.size(), timetables)); + if (auto const *output{std::getenv("EU07_UNIT_TESTS_TIMETABLES_DUMP")}; output != nullptr) { + std::ofstream{output, std::ios::binary} << dump; + } +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb74344bf..6ff904431 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "vehicle/brakesetting.h" #include "vehicle/handover.h" +#include "vehicle/timetableservice.h" #include "world/mtable.h" #include "vehicle/DynObj.h" #include "world/Event.h" @@ -1345,6 +1346,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { // to się wykona tylko raz po zatrzymaniu na W4 record_station( Point, blackbox::station_kinds::stopped ); + // the service flags of this stop hold for its doors and departure + m_stopflags = TrainParams.stop_flags(); if( TrainParams.StationIndex < TrainParams.StationCount ) { // jeśli są dalsze stacje, bez trąbienia przed odjazdem // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop @@ -1443,7 +1446,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać) } - if( false == tsGuardSignal.empty() ) { + if( false == tsGuardSignal.empty() + && true == timetable::has_conductor( m_stopflags ) ) { // jeśli mamy głos kierownika, to odegrać iDrivigFlags |= moveGuardSignal; } @@ -1451,7 +1455,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } // koniec startu z zatrzymania else { cue_action(driver_hint::waitdeparturetime); - if (TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure + if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him + && TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure iDrivigFlags |= moveGuardOpenDoor; GuardOpenDoor(); } @@ -4790,6 +4795,11 @@ void TController::Doors( bool const Open, int const Side ) { auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2; auto const prawe = 3 - lewe; + // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) + if( auto const doorstep { timetable::doorstep( m_stopflags ) }; + doorstep.has_value() && mvOccupied->Doors.step_enabled != *doorstep ) { + cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff ); + } // grant door control permission if it's not automatic // TBD: stricter requirements? if( true == pVehicle->MoverParameters->Doors.permit_needed ) { @@ -4801,10 +4811,9 @@ void TController::Doors( bool const Open, int const Side ) { } } // consist-wide remote signals to open doors doors - if( pVehicle->MoverParameters->Doors.open_control == control_t::conductor - || pVehicle->MoverParameters->Doors.open_control == control_t::driver - // NOTE: disabled for mixed controls, leave it up to passengers to open doors by themselves -/* || ( pVehicle->MoverParameters->Doors.open_control == control_t::mixed ) */ ) { + // NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has + // the driver open all the doors + if( true == timetable::opens_doors( *pVehicle->MoverParameters, m_stopflags ) ) { if( Side & prawe ) { cue_action( driver_hint::doorrightopen ); } @@ -4954,6 +4963,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams = TTrainParameters(NewCommand); // rozkład jazdy tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika m_lastexchangestop.clear(); + m_stopflags = {}; if (NewCommand != "none") { if (false == TrainParams.LoadTTfile( @@ -4988,6 +4998,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams.StationIndexInc(); // przejście do następnej TrainParams.StationStart = TrainParams.StationIndex; asNextStop = TrainParams.NextStop(); + // the flags of the first station until the train stops there + m_stopflags = TrainParams.stop_flags(); m_lastannouncement = announcement_t::idle; iDrivigFlags |= movePrimary; // skoro dostał rozkład, to jest teraz głównym // NewCommand = Global.asCurrentSceneryPath + NewCommand; @@ -8588,6 +8600,8 @@ TController::adjust_desired_speed_for_braking_test() { // if( false == Global.DynamicBrakeTest ) { return; } if( DynamicBrakeTest >= 5 ) { return; } // all done + if( ( DynamicBrakeTest == 0 ) + && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) if( false == is_train() ) { return; } // not applicable if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } // not applicable diff --git a/vehicle/Driver.h b/vehicle/Driver.h index cfa27757e..2ed51b6a1 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -663,6 +663,7 @@ private: std::string m_lastexchangestop; // HACK: safeguard to prevent multiple load exchanges per station int m_lastexchangeplatforms { 0 }; // cached station platforms for last exchange int m_lastexchangedirection { 0 }; // + timetable::service_flags m_stopflags; // service flags of the timetable at the stop the train is at or left last double fLastStopExpDist = -1.0; // odległość wygasania ostateniego przystanku int iRadioChannel = 1; // numer aktualnego kanału radiowego int iGuardRadio = 0; // numer kanału radiowego kierownika (0, gdy nie używa radia) diff --git a/vehicle/timetableservice.cpp b/vehicle/timetableservice.cpp new file mode 100644 index 000000000..913e9d2d4 --- /dev/null +++ b/vehicle/timetableservice.cpp @@ -0,0 +1,49 @@ +/* +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/timetableservice.h" + +#include "McZapkie/MOVER.h" + +namespace timetable { + +bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags) { + switch (Vehicle.Doors.open_control) { + case control_t::conductor: + case control_t::driver: + return true; + case control_t::mixed: + // left to the passengers, unless the timetable has the driver open them all + return Flags.central_doors == tristate::yes; + default: + return false; + } +} + +std::optional doorstep(service_flags const &Flags) { + switch (Flags.doorstep) { + case tristate::yes: + return true; + case tristate::no: + return false; + default: + return std::nullopt; + } +} + +bool has_conductor(service_flags const &Flags) { + return Flags.conductor != tristate::no; +} + +bool makes_brake_test(service_flags const &Flags) { + return Flags.brake_test != tristate::no; +} + +} // namespace timetable diff --git a/vehicle/timetableservice.h b/vehicle/timetableservice.h new file mode 100644 index 000000000..b5c72adf7 --- /dev/null +++ b/vehicle/timetableservice.h @@ -0,0 +1,37 @@ +/* +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 "world/timetableflags.h" + +class TMoverParameters; + +// what the AI driver does at a stop and on the way, as the service flags of the timetable ask (eu07/maszyna#95). with +// no flags each answer is the one the AI gave before the flags +namespace timetable { + +// whether the driver opens the doors of the consist from the cab at a stop, Vehicle being the one he drives: the doors +// the conductor or the driver opens, and with the central door opening also the ones of mixed control, which are +// otherwise left to the passengers +bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags); + +// the state the driver sets the doorsteps to before he opens the doors at a stop, none when he leaves them as they are +std::optional doorstep(service_flags const &Flags); + +// whether a conductor serves the train: gives the departure signal (by radio or by voice) and keeps the first door +// open for himself until the departure +bool has_conductor(service_flags const &Flags); + +// whether the driver makes the running brake test after the departure +bool makes_brake_test(service_flags const &Flags); + +} // namespace timetable diff --git a/world/mtable.cpp b/world/mtable.cpp index 123ae00f6..daf7b6637 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -109,6 +109,16 @@ sound_source TTrainParameters::current_stop_sound() const { return { sound_placement::engine }; } +timetable::service_flags const &TTrainParameters::stop_flags() const { + + return TimeTable[ timetable::stop_flags_entry( StationIndex, StationCount ) ].flags; +} + +timetable::service_flags const &TTrainParameters::run_flags() const { + + return TimeTable[ timetable::run_flags_entry( StationIndex, StationCount ) ].flags; +} + bool TTrainParameters::UpdateMTable( scenario_time const &Time, std::string const &NewName ) { return UpdateMTable( Time.data().wHour, Time.data().wMinute + Time.data().wSecond * 0.0167, NewName ); @@ -257,21 +267,16 @@ void TTrainParameters::UpdateVelocity(int /*Stationcount*/, double vActual) bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double vmax) // wczytanie pliku-tabeli z rozkładem przesuniętym o (fPlus); (vMax) nie ma znaczenia { - std::string lines; std::string s; std::ifstream fin; - bool EndTable; - double vActual; int conversionerror = 0; - EndTable = false; if (TrainName == "") { // jeśli pusty rozkład // UpdateVelocity(StationCount,vMax); //ograniczenie do prędkości startowej } else { - vActual = -1; s = scnpath + TrainName + ".txt"; replace_slashes(s); // Ra 2014-09: ustalić zasady wyznaczenia pierwotnego pliku przy przesuniętych rozkładach @@ -293,284 +298,22 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double } else { /*analiza rozkładu jazdy*/ - conversionerror = 0; - while (fin.good() && !(conversionerror != 0 || EndTable)) - { - std::getline(fin, lines); /*wczytanie linii*/ - if (contains( lines, "___________________") ) /*linia pozioma górna*/ - { - fin >> s; - if (s == "[") /*lewy pion*/ - { - fin >> s; - if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ - do - { - fin >> s; - } while (!(s == "|") || fin.eof()); /*środkowy pion*/ - } - } - else if (lines == "") - { - fin.close(); - break; - } - fin >> s; /*nazwa pociągu*/ - // if LowerCase(s)<>ExtractFileName(TrainName) then {musi być taka sama, jak nazwa - // pliku} - // ConversionError:=-7 {błąd niezgodności} - TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) - while (fin >> s || fin.bad()) - { - if (contains( s,"_______|") ) - { - break; - } - if (s == "Kategoria") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainCategory; - continue; - } - if (s == "Nazwa") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainLabel; - continue; - } - } // while (!(s == "Seria")); - // else - { /*czytaj naglowek*/ - while (fin >> s || !fin.bad()) - { - if (s == "[") - break; - } // while (!() || (fin.eof())); /*pierwsza linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s != "|") - break; - } // while (!(() || fin.eof())); - if( s != "|" ) { - Relation1 = s; - win1250_to_ascii( Relation1 ); - } - else - conversionerror = -5; - while (fin >> s || !fin.bad()) - { - if (s == "Relacja") - break; - } // while ( - // !( || (fin.eof()))); /*druga linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s == "|") - break; - } // while (!( || (fin.eof()))); - fin >> Relation2; - win1250_to_ascii( Relation2 ); - while (fin >> s || !fin.bad()) - { - if (s == "Wymagany") - break; - } // while (!(); - while (fin >> s || !fin.bad()) - { - if (s == "|" || s == "\n") - break; - } // while (!()); - fin >> s; - s = s.substr(0, s.find("%")); - BrakeRatio = atof(s.c_str()); - while (fin >> s || fin.bad()) - { - if (s == "Seria") - break; - } // while (!(s == "Seria")); - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> LocSeries; - fin >> LocLoad; // = s2rE(ReadWord(fin)); - do - { - fin >> s; - } while (!(contains( s,"[______________" ) || fin.bad())); - auto activeradiochannel{ -1 }; - while (!fin.bad() && !EndTable) - { - ++StationCount; - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - TMTableLine *record = &TimeTable[StationCount]; - { - if (s == "[") - fin >> s; - else - conversionerror = -4; - if (false == contains( s,"|") ) - { - record->km = static_cast(atof(s.c_str())); - fin >> s; - } - if (contains( s,"|_____|")) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains( s,"|")) - fin >> s; - fin >> record->StationName; - // get rid of non-ascii chars. TODO: run correct version based on locale - win1250_to_ascii( record->StationName ); - do - { - fin >> s; - } while (!(s == "1" || s == "2" || fin.bad())); - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Ah = atoi( s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu - record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu - } - else - { - record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji - record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - fin >> s; - if (false == contains(s,"|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (s.find("|_____|") != - std::string::npos) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains(s,"|")) - fin >> s; - // stationware. added fix for empty entry - fin >> s; - while( false == ( s == "1" - || s == "2" - || fin.bad() ) ) { - record->StationWare += s; - fin >> s; - } - // cache relevant station data - record->is_maintenance = contains(s, "pt"); - { - auto const stationware { Split( record->StationWare, ',' ) }; - for( auto const &entry : stationware ) { - if( entry.front() != 'R' ) { - continue; - } - auto const [entrytype, entrynumber]{ split_string_and_number( entry ) }; - if( entrytype == "R" - && entrynumber <= 10 ) { - auto const radiochannel { entrynumber }; - if( record->radio_channel == -1 - || radiochannel != activeradiochannel ) { - // if the station has more than one radiochannel listed, - // it generally means we should switch to the one we weren't using so far - // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system - record->radio_channel = radiochannel; - } - } - } - if( record->radio_channel != -1 ) { - activeradiochannel = record->radio_channel; - } - } - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu - record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu - } - else - { - record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji - record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - else - { - record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) - record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(contains( s, "[" ) || fin.bad())); - if (false == contains( s, "_|_")) - fin >> s; - if (false == contains( s, "|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (contains( s, "|_____|") ) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains( s, "|")) - vActual = atof(s.c_str()); - } - while (false == contains( s, "|" ) ) - fin >> s; - while (false == contains(s, "]")) - fin >> s; - if (contains( s,"_|_") ) - EndTable = true; - } /*timetableline*/ - } - } - } /*while eof*/ + timetable_data data; + data.TrainName = TrainName; + conversionerror = read_timetable( fin, data ); fin.close(); + TrainName = data.TrainName; + TrainCategory = data.TrainCategory; + TrainLabel = data.TrainLabel; + Relation1 = data.Relation1; + Relation2 = data.Relation2; + BrakeRatio = data.BrakeRatio; + LocSeries = data.LocSeries; + LocLoad = data.LocLoad; + StationCount = data.StationCount; + for( auto i = 0; i <= MaxTTableSize; ++i ) { + static_cast( TimeTable[ i ] ) = data.TimeTable[ i ]; + } } } // jeśli nazwa pierwszego zgodna z relacją diff --git a/world/mtable.h b/world/mtable.h index 841fea815..31fdd8810 100644 --- a/world/mtable.h +++ b/world/mtable.h @@ -13,32 +13,19 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" +#include "world/timetablereader.h" namespace Mtable { -static int const MaxTTableSize = 100; // można by to robić dynamicznie static char const *const hrsd = "."; // Ra: pozycja zerowa rozkładu chyba nie ma sensu // Ra: numeracja przystanków jest 1..StationCount -struct TMTableLine +// a station of the timetable as the file gives it (TMTableEntry, world/timetablereader.h), with its name announcement +struct TMTableLine : TMTableEntry { - float km{ 0.f }; // kilometraz linii - float vmax{ -1.f }; // predkosc rozkladowa przed przystankiem - // StationName:string[32]; //nazwa stacji ('_' zamiast spacji) - // StationWare:string[32]; //typ i wyposazenie stacji, oddz. przecinkami} - std::string StationName{ "nowhere" }; // nazwa stacji ('_' zamiast spacji) - std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami} - int TrackNo{ 1 }; // ilosc torow szlakowych - int Ah{ -1 }; - float Am{ -1.f }; // godz. i min. przyjazdu, -1 gdy bez postoju - int Dh{ -1 }; - float Dm{ -1.f }; // godz. i min. odjazdu - float tm{ 0.f }; // czas jazdy do tej stacji w min. (z kolumny) - bool is_maintenance{ false }; - int radio_channel{ -1 }; sound_source name_sound{ sound_placement::engine }; }; @@ -58,7 +45,7 @@ class TTrainParameters double BrakeRatio; std::string LocSeries; // seria (typ) pojazdu double LocLoad; - TMTable TimeTable; + TMTable TimeTable; // TimeTable[0].flags holds the service flags of the whole train int StationCount; // ilość przystanków (0-techniczny) int StationIndex; // numer najbliższego (aktualnego) przystanku int StationStart; // numer pierwszej stacji pokazywanej na podglądzie rozkładu @@ -95,6 +82,10 @@ class TTrainParameters int radio_channel() const; // returns: sound file associated with current station, or -1 sound_source current_stop_sound() const; + // service flags (eu07/maszyna#95) which hold at the stop the train makes for or stands at + timetable::service_flags const &stop_flags() const; + // service flags which hold on the way, since the stop the train left last + timetable::service_flags const &run_flags() const; private: void load_sounds(); }; diff --git a/world/timetableflags.cpp b/world/timetableflags.cpp new file mode 100644 index 000000000..5c7d6ae9e --- /dev/null +++ b/world/timetableflags.cpp @@ -0,0 +1,103 @@ +/* +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 "world/timetableflags.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +namespace timetable { + +namespace { + +void apply_one(tristate &Flag, tristate const Other) { + if (Other != tristate::unset) { + Flag = Other; + } +} + +tristate *flag_named(std::string_view const Key, service_flags &Flags) { + if (Key == "drzwi_centralne") { + return &Flags.central_doors; + } + if (Key == "stopien") { + return &Flags.doorstep; + } + if (Key == "kierownik") { + return &Flags.conductor; + } + if (Key == "proba_hamulca") { + return &Flags.brake_test; + } + return nullptr; +} + +} // namespace + +void service_flags::apply(service_flags const &Other) { + apply_one(central_doors, Other.central_doors); + apply_one(doorstep, Other.doorstep); + apply_one(conductor, Other.conductor); + apply_one(brake_test, Other.brake_test); +} + +bool read_flag(std::string_view const Entry, service_flags &Flags) { + auto const separator{Entry.find('=')}; + if (separator == std::string_view::npos) { + return false; + } + auto const key{ToLower(std::string{Entry.substr(0, separator)})}; + auto *flag{flag_named(key, Flags)}; + if (flag == nullptr) { + return false; + } + auto const value{ToLower(std::string{Entry.substr(separator + 1)})}; + if (value == "tak" || value == "1") { + *flag = tristate::yes; + } + else if (value == "nie" || value == "0") { + *flag = tristate::no; + } + else { + ErrorLog("Bad timetable: unknown value of " + key + " in \"" + std::string{Entry} + "\", expected tak or nie"); + } + return true; +} + +std::string extract_flags(std::string const &Ware, service_flags &Flags) { + if (false == contains(Ware, '=')) { + // no flags, the list as it was + return Ware; + } + std::string rest; + for (auto const &entry : Split(Ware, ',')) { + if (read_flag(entry, Flags)) { + continue; + } + if (contains(entry, '=')) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in station ware \"" + Ware + "\""); + } + if (false == rest.empty()) { + rest += ','; + } + rest += entry; + } + return rest; +} + +int stop_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex, 0, std::max(StationCount, 0)); +} + +int run_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex - 1, 0, std::max(StationCount, 0)); +} + +} // namespace timetable diff --git a/world/timetableflags.h b/world/timetableflags.h new file mode 100644 index 000000000..8c463d3f3 --- /dev/null +++ b/world/timetableflags.h @@ -0,0 +1,59 @@ +/* +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 + +// the way a train is served, set by its timetable for the AI driver (eu07/maszyna#95): trams and underground trains +// open all the doors from the cab, have no doorstep, no conductor, no running brake test. each flag the timetable +// leaves out keeps the behaviour of the vehicles, as before the flags. +// +// the whole train: a row of the first box of the header +// [ Flagi AI | kierownik=nie,proba_hamulca=nie ] +// from a station on: entries of its station ware (the second line of the station, with R2, ph, @...) +// [ | | R2,ph,drzwi_centralne=tak,stopien=nie 1 12.47 | ] +// a station's entry holds from that station on, until another station changes it +namespace timetable { + +enum class tristate : std::uint8_t { + unset, // left to the vehicles, as before the flags + yes, + no +}; + +struct service_flags { + tristate central_doors{tristate::unset}; // drzwi_centralne: the driver opens all the doors, of mixed control too + tristate doorstep{tristate::unset}; // stopien: the doorsteps on (tak) or off (nie) before the doors open + tristate conductor{tristate::unset}; // kierownik: no conductor (nie), no departure signal, no door kept open for him + tristate brake_test{tristate::unset}; // proba_hamulca: no running brake test (nie) + + bool operator==(service_flags const &) const = default; + bool empty() const { return *this == service_flags{}; } + // the flags Other sets explicitly override these + void apply(service_flags const &Other); +}; + +// reads one entry, key=value (tak/nie, 1/0), into Flags. returns false for an entry which isn't a flag, so the caller +// keeps it; a flag with a value it doesn't know is reported to the log and taken as handled +bool read_flag(std::string_view Entry, service_flags &Flags); + +// reads the flags out of a station ware list (comma separated entries) into Flags. returns the list without them: the +// list as it was when it had none +std::string extract_flags(std::string const &Ware, service_flags &Flags); + +// the timetable entry whose flags hold at the stop the train makes for or stands at: the current one (StationIndex), +// within 0 (the header's flags) and the last station +int stop_flags_entry(int StationIndex, int StationCount); +// the entry whose flags hold on the way: the station the train left last, 0 (the header's flags) before the first one +int run_flags_entry(int StationIndex, int StationCount); + +} // namespace timetable diff --git a/world/timetablereader.cpp b/world/timetablereader.cpp new file mode 100644 index 000000000..3d340e8bd --- /dev/null +++ b/world/timetablereader.cpp @@ -0,0 +1,321 @@ +/* +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 "world/timetablereader.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +namespace Mtable { + +namespace { + +char const *const hrsd = "."; + +// the rest of the row "Flagi" of the header after its label: flag entries up to the closing bracket. returns true when +// a row with no closing bracket ran into the line under the box +bool read_header_flags(std::istream &fin, timetable_data &Data) { + std::string s; + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + while (fin >> s) { + if (s.starts_with('[')) { + // the next row, or the line under the box + ErrorLog("Bad timetable: row \"Flagi\" of " + Data.TrainName + " without the closing bracket"); + return contains(s, "_______|"); + } + auto const closing{s.ends_with(']')}; + for (auto const &entry : Split(closing ? std::string_view{s}.substr(0, s.size() - 1) : std::string_view{s}, ',')) { + if (false == entry.empty() && false == timetable::read_flag(entry, Data.Flags)) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in row \"Flagi\" of " + Data.TrainName); + } + } + if (closing) { + break; + } + } + return false; +} + +} // namespace + +// the reader as TTrainParameters::LoadTTfile had it, but for: the row "Flagi" of the header and the flags of the +// station ware; the loops end with the end of the file, where they used to spin forever (on a truncated file, or one +// with a number where the reader expects it which isn't one). a file the old reader read gets read the same +int read_timetable(std::istream &fin, timetable_data &Data) { + std::string lines; + std::string s; + bool EndTable{false}; + double vActual{-1}; + int conversionerror{0}; + auto &TimeTable{Data.TimeTable}; + auto &StationCount{Data.StationCount}; + // zapisywanie prędkości maksymalnej do wcześniejszych odcinków + auto const UpdateVelocity{[&TimeTable, &StationCount](double const Velocity) { + int i = StationCount; + while (i >= 0 && TimeTable[i].vmax == -1) { + TimeTable[i].vmax = static_cast(Velocity); // prędkość dojazdu do przystanku i + --i; // ewentualnie do poprzedniego też + } + }}; + + while (fin.good() && !(conversionerror != 0 || EndTable)) { + std::getline(fin, lines); /*wczytanie linii*/ + if (contains(lines, "___________________")) /*linia pozioma górna*/ + { + fin >> s; + if (s == "[") /*lewy pion*/ + { + fin >> s; + if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ + do { + fin >> s; + } while (!(s == "|" || fin.fail())); /*środkowy pion*/ + } + } + else if (lines == "") { + break; + } + fin >> s; /*nazwa pociągu*/ + Data.TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) + while (fin >> s) { + if (contains(s, "_______|")) { + break; + } + if (s == "Kategoria") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainCategory; + continue; + } + if (s == "Nazwa") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainLabel; + continue; + } + if (s == "Flagi") { + // service flags of the whole train (eu07/maszyna#95) + if (read_header_flags(fin, Data)) { + break; + } + continue; + } + } + { /*czytaj naglowek*/ + while (fin >> s) { + if (s == "[") + break; + } /*pierwsza linia z relacją*/ + while (fin >> s) { + if (s != "|") + break; + } + if (s != "|") { + Data.Relation1 = s; + win1250_to_ascii(Data.Relation1); + } + else + conversionerror = -5; + while (fin >> s) { + if (s == "Relacja") + break; + } /*druga linia z relacją*/ + while (fin >> s) { + if (s == "|") + break; + } + fin >> Data.Relation2; + win1250_to_ascii(Data.Relation2); + while (fin >> s) { + if (s == "Wymagany") + break; + } + while (fin >> s) { + if (s == "|" || s == "\n") + break; + } + fin >> s; + s = s.substr(0, s.find("%")); + Data.BrakeRatio = atof(s.c_str()); + while (fin >> s) { + if (s == "Seria") + break; + } + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.LocSeries; + fin >> Data.LocLoad; // = s2rE(ReadWord(fin)); + do { + fin >> s; + } while (!(contains(s, "[______________") || fin.fail())); + // the header's flags hold from the start, entry 0 keeps them for the stations to inherit + TimeTable[0].flags = Data.Flags; + auto activeradiochannel{-1}; + while (!fin.fail() && !EndTable) { + ++StationCount; + if (StationCount > MaxTTableSize) { + --StationCount; + conversionerror = timetable_too_long; + break; + } + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + TMTableEntry *record = &TimeTable[StationCount]; + { + if (s == "[") + fin >> s; + else + conversionerror = -4; + if (false == contains(s, "|")) { + record->km = static_cast(atof(s.c_str())); + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + fin >> record->StationName; + // get rid of non-ascii chars. TODO: run correct version based on locale + win1250_to_ascii(record->StationName); + do { + fin >> s; + } while (!(s == "1" || s == "2" || fin.fail())); + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Ah = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu + record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu + } + else { + record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji + record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (s.find("|_____|") != std::string::npos) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + // stationware. added fix for empty entry + fin >> s; + while (false == (s == "1" || s == "2" || fin.fail())) { + record->StationWare += s; + fin >> s; + } + // cache relevant station data + record->is_maintenance = contains(s, "pt"); + // service flags (eu07/maszyna#95): the ones of the station before, changed by the ones given here + record->flags = TimeTable[StationCount - 1].flags; + record->StationWare = timetable::extract_flags(record->StationWare, record->flags); + { + auto const stationware{Split(record->StationWare, ',')}; + for (auto const &entry : stationware) { + if (entry.front() != 'R') { + continue; + } + auto const [entrytype, entrynumber]{split_string_and_number(entry)}; + if (entrytype == "R" && entrynumber <= 10) { + auto const radiochannel{entrynumber}; + if (record->radio_channel == -1 || radiochannel != activeradiochannel) { + // if the station has more than one radiochannel listed, + // it generally means we should switch to the one we weren't using so far + // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system + record->radio_channel = radiochannel; + } + } + } + if (record->radio_channel != -1) { + activeradiochannel = record->radio_channel; + } + } + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu + record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu + } + else { + record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji + record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + else { + record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) + record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(contains(s, "[") || fin.fail())); + if (false == contains(s, "_|_")) + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + while (false == contains(s, "]") && false == fin.fail()) + fin >> s; + if (contains(s, "_|_")) + EndTable = true; + } /*timetableline*/ + } + if (false == EndTable && conversionerror == 0) { + // the old reader went on reading past the end of the file here, forever + conversionerror = timetable_truncated; + } + } + } /*while eof*/ + return conversionerror; +} + +} // namespace Mtable diff --git a/world/timetablereader.h b/world/timetablereader.h new file mode 100644 index 000000000..aaf43e34c --- /dev/null +++ b/world/timetablereader.h @@ -0,0 +1,66 @@ +/* +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 "world/timetableflags.h" + +// the reader of the timetable files (.txt next to the scenery), without the parts of the engine the timetable +// of a running train needs (sounds, scenario time), so it can be tested on its own +namespace Mtable { + +static int const MaxTTableSize = 100; // można by to robić dynamicznie + +// one station of a timetable, as the file gives it +struct TMTableEntry { + float km{0.f}; // kilometraz linii + float vmax{-1.f}; // predkosc rozkladowa przed przystankiem + std::string StationName{"nowhere"}; // nazwa stacji ('_' zamiast spacji) + std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami, bez flag obsługi + int TrackNo{1}; // ilosc torow szlakowych + int Ah{-1}; + float Am{-1.f}; // godz. i min. przyjazdu, -1 gdy bez postoju + int Dh{-1}; + float Dm{-1.f}; // godz. i min. odjazdu + float tm{0.f}; // czas jazdy do tej stacji w min. (z kolumny) + bool is_maintenance{false}; + int radio_channel{-1}; + // the service flags which hold from this station on: the header's, changed by this and the earlier stations. + // entry 0 holds the header's + timetable::service_flags flags; +}; + +// what a timetable file holds +struct timetable_data { + std::string TrainName; // the name the file is looked up by, then the one the file gives + std::string TrainCategory; + std::string TrainLabel; + std::string Relation1; + std::string Relation2; + double BrakeRatio{0.0}; + std::string LocSeries; + double LocLoad{0.0}; + timetable::service_flags Flags; // of the whole train, the row "Flagi" of the header + int StationCount{0}; // stations 1..StationCount, entry 0 is the technical one + std::array TimeTable; +}; + +// conversion errors of read_timetable, besides the ones it always had (-4: no station row where expected, -5: no +// first station of the relation) +int const timetable_truncated{-9}; // the file ends before the bottom line of the table (the reader used to hang) +int const timetable_too_long{-10}; // more stations than MaxTTableSize (the reader used to write past the table) + +// reads the timetable from Input into Data. returns the conversion error, 0 when read +int read_timetable(std::istream &Input, timetable_data &Data); + +} // namespace Mtable From a3df3a07c8a19ae4260577dcc401e1abb96c8899 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 00:48:28 +0100 Subject: [PATCH 49/59] test: count the shunting seconds in a function of its own, not a lambda holding the vehicle --- tests/unit/test_speed_control.cpp | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index 7b0f7fc52..3f8a9a9ec 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -257,6 +257,18 @@ TEST_CASE("speed control apart: which vehicles' cruise control has a switch of i CHECK(eu07->IsSpeedCtrlSeparate()); } +namespace { + +// Seconds of the scenario going on, a second at a time, counting the seconds with the field shunted and not +void count_shunting(scenario &Scenario, TMoverParameters const &Vehicle, int const Seconds, int &Shunted, int &Unshunted) { + for (int second = 0; second < Seconds; ++second) { + Scenario.wait(1.0); + ++(Vehicle.ScndCtrlPos > 0 ? Shunted : Unshunted); + } +} + +} // namespace + TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the field shunting going on by itself") { scenario scenario{"speed control apart/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; scenario.add("6dg_v1/6dg", 1); @@ -285,13 +297,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the // the shunt goes by itself all the while, by the current of the motors, which the cruise control's demand sets auto shunted{0}; auto unshunted{0}; - auto const run{[&scenario, &loco, &shunted, &unshunted](int const Seconds) { - for (int second = 0; second < Seconds; ++second) { - scenario.wait(1.0); - ++(loco.ScndCtrlPos > 0 ? shunted : unshunted); - } - }}; - run(60); + count_shunting(scenario, loco, 60, shunted, unshunted); CHECK(loco.Vel == doctest::Approx(held).epsilon(0.03)); CHECK_FALSE(loco.SpeedCtrlUnit.Standby); CHECK(loco.eimic_real < loco.eimic); // the cruise control holding the power back @@ -301,7 +307,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the loco.SpeedCtrlInc(); auto const higher{loco.SpeedCtrlValue}; CHECK(higher == doctest::Approx(held + 10.0).epsilon(0.1)); - run(60); + count_shunting(scenario, loco, 60, shunted, unshunted); CHECK(loco.Vel == doctest::Approx(higher).epsilon(0.03)); CHECK(loco.StLinFlag); CHECK(shunted > 0); From 81bae7cdd44b5421f7f9008af5c117c091afb524 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 01:42:49 +0100 Subject: [PATCH 50/59] feat: drag universal cab controls to any position with the mouse (#62) A universal control (window, door, sun blind) whose definition in the .mmd has the new optional key drag: can be dragged with the left mouse button to any position between its ends, and stays where it is let go: universal1: { okno_p mov -0.71 0 0.3 drag: left soundinc: ... } The value is the direction the mouse moves to open the control: up, down, left or right (yes = up, no = off). The drag works like the sliders of the controllers: the cursor is hidden, its move over 0.6 of the window height takes the control from one end to the other. A click without dragging toggles the control as before, and so do the keys: to the end farther from where it is. Push controls aren't dragged. Without the key every universal works as it did; none of the cab definitions has it yet. New commands genericset0..29 set universal N to the position in param1 (0-1); the mouse sends them, and they can be bound to a gamepad axis. The rules (the key's values, the move of the cursor along the direction, the ends, click or drag, the keys) are in vehicle/universaldrag.h, with unit tests. --- input/command.cpp | 60 ++++++++++++ input/command.h | 31 +++++++ input/drivermouseinput.cpp | 87 +++++++++++++++++- input/drivermouseinput.h | 24 ++++- tests/unit/test_universal_drag.cpp | 143 +++++++++++++++++++++++++++++ vehicle/Gauge.cpp | 14 ++- vehicle/Gauge.h | 7 ++ vehicle/Train.cpp | 86 ++++++++++++++--- vehicle/Train.h | 6 ++ vehicle/universaldrag.h | 138 ++++++++++++++++++++++++++++ 10 files changed, 576 insertions(+), 20 deletions(-) create mode 100644 tests/unit/test_universal_drag.cpp create mode 100644 vehicle/universaldrag.h diff --git a/input/command.cpp b/input/command.cpp index 32ba02e94..add272473 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -416,6 +416,36 @@ commanddescription_sequence Commands_descriptions = { {"linebreakeropenc", command_target::vehicle, command_mode::oneoff}, {"linebreakerclosec", command_target::vehicle, command_mode::oneoff}, {"repaircoupler", command_target::simulation, command_mode::oneoff}, + {"genericset0", command_target::vehicle, command_mode::oneoff}, + {"genericset1", command_target::vehicle, command_mode::oneoff}, + {"genericset2", command_target::vehicle, command_mode::oneoff}, + {"genericset3", command_target::vehicle, command_mode::oneoff}, + {"genericset4", command_target::vehicle, command_mode::oneoff}, + {"genericset5", command_target::vehicle, command_mode::oneoff}, + {"genericset6", command_target::vehicle, command_mode::oneoff}, + {"genericset7", command_target::vehicle, command_mode::oneoff}, + {"genericset8", command_target::vehicle, command_mode::oneoff}, + {"genericset9", command_target::vehicle, command_mode::oneoff}, + {"genericset10", command_target::vehicle, command_mode::oneoff}, + {"genericset11", command_target::vehicle, command_mode::oneoff}, + {"genericset12", command_target::vehicle, command_mode::oneoff}, + {"genericset13", command_target::vehicle, command_mode::oneoff}, + {"genericset14", command_target::vehicle, command_mode::oneoff}, + {"genericset15", command_target::vehicle, command_mode::oneoff}, + {"genericset16", command_target::vehicle, command_mode::oneoff}, + {"genericset17", command_target::vehicle, command_mode::oneoff}, + {"genericset18", command_target::vehicle, command_mode::oneoff}, + {"genericset19", command_target::vehicle, command_mode::oneoff}, + {"genericset20", command_target::vehicle, command_mode::oneoff}, + {"genericset21", command_target::vehicle, command_mode::oneoff}, + {"genericset22", command_target::vehicle, command_mode::oneoff}, + {"genericset23", command_target::vehicle, command_mode::oneoff}, + {"genericset24", command_target::vehicle, command_mode::oneoff}, + {"genericset25", command_target::vehicle, command_mode::oneoff}, + {"genericset26", command_target::vehicle, command_mode::oneoff}, + {"genericset27", command_target::vehicle, command_mode::oneoff}, + {"genericset28", command_target::vehicle, command_mode::oneoff}, + {"genericset29", command_target::vehicle, command_mode::oneoff}, }; // Maps of command and coresponding strings @@ -811,6 +841,36 @@ std::unordered_map const commandMap = { {"linebreakeropenc", user_command::linebreakeropenc}, {"linebreakerclosec", user_command::linebreakerclosec}, {"repaircoupler", user_command::repaircoupler}, + {"genericset0", user_command::genericset0}, + {"genericset1", user_command::genericset1}, + {"genericset2", user_command::genericset2}, + {"genericset3", user_command::genericset3}, + {"genericset4", user_command::genericset4}, + {"genericset5", user_command::genericset5}, + {"genericset6", user_command::genericset6}, + {"genericset7", user_command::genericset7}, + {"genericset8", user_command::genericset8}, + {"genericset9", user_command::genericset9}, + {"genericset10", user_command::genericset10}, + {"genericset11", user_command::genericset11}, + {"genericset12", user_command::genericset12}, + {"genericset13", user_command::genericset13}, + {"genericset14", user_command::genericset14}, + {"genericset15", user_command::genericset15}, + {"genericset16", user_command::genericset16}, + {"genericset17", user_command::genericset17}, + {"genericset18", user_command::genericset18}, + {"genericset19", user_command::genericset19}, + {"genericset20", user_command::genericset20}, + {"genericset21", user_command::genericset21}, + {"genericset22", user_command::genericset22}, + {"genericset23", user_command::genericset23}, + {"genericset24", user_command::genericset24}, + {"genericset25", user_command::genericset25}, + {"genericset26", user_command::genericset26}, + {"genericset27", user_command::genericset27}, + {"genericset28", user_command::genericset28}, + {"genericset29", user_command::genericset29}, {"none", user_command::none}}; } // namespace simulation diff --git a/input/command.h b/input/command.h index 664f6a3ba..9fb6021d0 100644 --- a/input/command.h +++ b/input/command.h @@ -414,6 +414,37 @@ enum class user_command linebreakeropenc, linebreakerclosec, repaircoupler, // the broken coupler of the vehicle (payload) at the end (param1) + // sets universal control N to the position given in param1, 0-1 (MaSzyna-EU07/maszyna#62) + genericset0, + genericset1, + genericset2, + genericset3, + genericset4, + genericset5, + genericset6, + genericset7, + genericset8, + genericset9, + genericset10, + genericset11, + genericset12, + genericset13, + genericset14, + genericset15, + genericset16, + genericset17, + genericset18, + genericset19, + genericset20, + genericset21, + genericset22, + genericset23, + genericset24, + genericset25, + genericset26, + genericset27, + genericset28, + genericset29, none = -1 }; diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 222c58a62..d8d389f44 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -28,6 +28,8 @@ void mouse_slider::bind( user_command const &Command ) { m_command = Command; + m_universal.reset(); + m_universaldrag.reset(); auto const *train { simulation::Train }; TMoverParameters const *vehicle { nullptr }; @@ -124,18 +126,47 @@ mouse_slider::bind( user_command const &Command ) { m_analogue ? controledge - m_value * controlsize : controledge - m_value * stepsize - 0.5 * stepsize ); } +void +mouse_slider::bind_universal( int const Index, universal_drag::direction const Drag, float const Position ) { + + m_command = static_cast( static_cast( user_command::genericset0 ) + Index ); + m_universal = Index; + m_universaldrag.emplace( Drag, Position ); + m_value = m_universaldrag->position(); + m_valuerange = 1.0; + m_analogue = true; + m_invertrange = false; + // the cursor is hidden for the drag and put back where it was when the drag ends; the drag follows its moves + // from wherever it is, so it isn't placed anywhere + m_cursorposition = glm::dvec2( Global.cursor_pos ); + Application.set_cursor( GLFW_CURSOR_DISABLED ); +} + void mouse_slider::release() { m_command = user_command::none; + m_universal.reset(); + m_universaldrag.reset(); Application.set_cursor_pos( m_cursorposition.x, m_cursorposition.y ); Application.set_cursor( GLFW_CURSOR_NORMAL ); } -void -mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { +bool +mouse_slider::on_move( double const Mousex, double const Mousey ) { auto const controlsize { Global.window_size.y * EU07_CONTROLLER_MOUSESLIDERSIZE }; + + if( m_universaldrag ) { + // a universal control, dragged the same way as the controllers: the move of the cursor over the size of the + // slider takes it from one end to the other + if( false == m_universaldrag->move( Mousex, Mousey, controlsize ) ) { + return false; + } + m_value = m_universaldrag->position(); + return true; + } + auto const controledge { Global.window_size.y * 0.5 + controlsize * 0.5 }; auto const stepsize { controlsize / m_valuerange }; @@ -143,6 +174,7 @@ mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { m_value = m_analogue ? (controledge - mousey) / controlsize : std::floor((controledge - mousey) / stepsize); if( m_invertrange ) { m_value = ( m_analogue ? 1.0 : m_valuerange ) - m_value; } + return true; } @@ -246,8 +278,8 @@ drivermouse_input::move( double Mousex, double Mousey ) { } else { // control picking mode - if( m_slider.command() != user_command::none ) { - m_slider.on_move( Mousex, Mousey ); + if( m_slider.command() != user_command::none + && true == m_slider.on_move( Mousex, Mousey ) ) { m_relay.post( m_slider.command(), m_slider.value(), @@ -341,7 +373,14 @@ drivermouse_input::button( int const Button, int const Action ) { else { m_pickwaiting = false; if (Button == GLFW_MOUSE_BUTTON_LEFT && m_slider.command() != user_command::none) { - m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + if( auto const universal { m_slider.universal() }; + universal && m_slider.is_click() ) { + // a universal control clicked rather than dragged goes to its end, as a click on any universal does + toggle_universal( *universal ); + } + else { + m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + } m_slider.release(); } // if it's the right mouse button that got released and we had no command active, we were potentially in view panning mode; stop it @@ -392,6 +431,25 @@ drivermouse_input::button( int const Button, int const Action ) { default: { break; } } } + // a universal control with drag: in its definition is dragged to any position between its ends, + // and a click without dragging toggles it as before (MaSzyna-EU07/maszyna#62) + if( Button == GLFW_MOUSE_BUTTON_LEFT ) { + auto const universal { universal_index( mousecommand ) }; + auto const drag { + universal ? + simulation::Train->universal_drag_direction( *universal ) : + universal_drag::direction::none }; + if( drag != universal_drag::direction::none ) { + mousecommand = none; + if( false == pickwaiting ) { + // the button was let go before the control was found under the cursor: a click + toggle_universal( *universal ); + return; + } + m_slider.bind_universal( *universal, drag, simulation::Train->universal_position( *universal ) ); + return; + } + } switch( mousecommand ) { case mastercontrollerincrease: @@ -1162,4 +1220,23 @@ drivermouse_input::adjust_command( user_command Command ) const { return Command; } +std::optional +drivermouse_input::universal_index( user_command const Command ) { + + auto const index { static_cast( Command ) - static_cast( user_command::generictoggle0 ) }; + if( index < 0 + || index > static_cast( user_command::generictoggle29 ) - static_cast( user_command::generictoggle0 ) ) { + return std::nullopt; + } + return index; +} + +void +drivermouse_input::toggle_universal( int const Index ) const { + + auto const toggle { static_cast( static_cast( user_command::generictoggle0 ) + Index ) }; + m_relay.post( toggle, 0, 0, GLFW_PRESS, 0 ); + m_relay.post( toggle, 0, 0, GLFW_RELEASE, 0 ); +} + //--------------------------------------------------------------------------- diff --git a/input/drivermouseinput.h b/input/drivermouseinput.h index 180e0335c..aa2ac0ca3 100644 --- a/input/drivermouseinput.h +++ b/input/drivermouseinput.h @@ -9,8 +9,10 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include "input/command.h" +#include "vehicle/universaldrag.h" // virtual slider; value determined by position of the mouse class mouse_slider { @@ -21,9 +23,14 @@ public: // methods void bind( user_command const &Command ); + // binds the slider to universal control Index, which the mouse drags in the Drag direction from its Position + // to any position between its ends (MaSzyna-EU07/maszyna#62) + void + bind_universal( int const Index, universal_drag::direction const Drag, float const Position ); void release(); - void + // returns whether the value changed + bool on_move( double const Mousex, double const Mousey ); inline user_command @@ -32,10 +39,19 @@ public: double value() const { return m_value; } + // the universal control the slider drags, if any, and whether letting it go now is a click rather than a drag + std::optional + universal() const { + return m_universal; } + bool + is_click() const { + return m_universaldrag && m_universaldrag->is_click(); } private: // members user_command m_command { user_command::none }; + std::optional m_universal; // the universal control dragged, if any + std::optional m_universaldrag; double m_value { 0.0 }; double m_valuerange { 0.0 }; bool m_analogue { false }; @@ -92,6 +108,12 @@ private: // potentially replaces supplied command with a more relevant one user_command adjust_command( user_command Command ) const; + // the universal control a command toggles, if it toggles one + static std::optional + universal_index( user_command const Command ); + // toggles universal control Index, as a click on it does + void + toggle_universal( int const Index ) const; // members command_relay m_relay; diff --git a/tests/unit/test_universal_drag.cpp b/tests/unit/test_universal_drag.cpp new file mode 100644 index 000000000..f520b694f --- /dev/null +++ b/tests/unit/test_universal_drag.cpp @@ -0,0 +1,143 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/universaldrag.h" + +// smooth regulation of the universal cab controls (MaSzyna-EU07/maszyna#62): a universal with "drag: " +// in its definition is dragged with the mouse to any position between its ends and stays there when let go; a click +// and the keys move it to its ends. the mouse and TGauge are not part of the core library, the rules they follow are + +using universal_drag::direction; + +TEST_CASE("universal drag: the values of the drag key") { + CHECK(universal_drag::parse("up") == direction::up); + CHECK(universal_drag::parse("down") == direction::down); + CHECK(universal_drag::parse("left") == direction::left); + CHECK(universal_drag::parse("right") == direction::right); + // yes drags it up, as the sliders of the controllers + CHECK(universal_drag::parse("yes") == direction::up); + CHECK(universal_drag::parse("true") == direction::up); + CHECK(universal_drag::parse("1") == direction::up); + CHECK(universal_drag::parse("no") == direction::none); + CHECK(universal_drag::parse("false") == direction::none); + CHECK(universal_drag::parse("0") == direction::none); + CHECK(universal_drag::parse("none") == direction::none); + // a value it doesn't know is reported, and the control can't be dragged + CHECK_FALSE(universal_drag::parse("sideways").has_value()); + CHECK_FALSE(universal_drag::parse("").has_value()); + CHECK_FALSE(universal_drag::parse("Up").has_value()); +} + +TEST_CASE("universal drag: a push universal can't be dragged, it springs back when let go") { + CHECK(universal_drag::effective(direction::up, true) == direction::none); + CHECK(universal_drag::effective(direction::left, true) == direction::none); + CHECK(universal_drag::effective(direction::up, false) == direction::up); + CHECK(universal_drag::effective(direction::none, false) == direction::none); +} + +TEST_CASE("universal drag: the move of the cursor along the direction") { + auto const size{600.0}; + // the cursor's y grows downwards + CHECK(universal_drag::along(direction::up, 0.0, -60.0, size) == doctest::Approx(0.1)); + CHECK(universal_drag::along(direction::up, 0.0, 60.0, size) == doctest::Approx(-0.1)); + CHECK(universal_drag::along(direction::down, 0.0, 60.0, size) == doctest::Approx(0.1)); + CHECK(universal_drag::along(direction::left, -150.0, 0.0, size) == doctest::Approx(0.25)); + CHECK(universal_drag::along(direction::right, -150.0, 0.0, size) == doctest::Approx(-0.25)); + // the move across the direction doesn't count + CHECK(universal_drag::along(direction::up, 300.0, 0.0, size) == 0.0); + CHECK(universal_drag::along(direction::left, 0.0, 300.0, size) == 0.0); + // nothing to drag + CHECK(universal_drag::along(direction::none, 100.0, 100.0, size) == 0.0); + CHECK(universal_drag::along(direction::up, 0.0, -60.0, 0.0) == 0.0); +} + +TEST_CASE("universal drag: the position is kept between the ends") { + CHECK(universal_drag::clamp(-0.5) == 0.f); + CHECK(universal_drag::clamp(1.5) == 1.f); + CHECK(universal_drag::clamp(0.25) == doctest::Approx(0.25f)); +} + +TEST_CASE("universal drag: the keys and a click move the control to the end farther from its position") { + CHECK(universal_drag::toggled(0.f) == 1.f); + CHECK(universal_drag::toggled(1.f) == 0.f); + // a control left in between + CHECK(universal_drag::toggled(0.3f) == 1.f); + CHECK(universal_drag::toggled(0.7f) == 0.f); + // half way, as the two-state universals always did + CHECK(universal_drag::toggled(0.5f) == 0.f); +} + +TEST_CASE("universal drag: a drag takes the control to a position between its ends, where it stays") { + auto const size{600.0}; + universal_drag::drag drag{direction::up, 0.f}; + // the first position of the cursor is where the drag starts from, even if the hidden cursor was moved + CHECK_FALSE(drag.move(400.0, 500.0, size)); + CHECK(drag.position() == 0.f); + CHECK(drag.is_click()); + // up by a quarter of the size + CHECK(drag.move(400.0, 350.0, size)); + CHECK(drag.position() == doctest::Approx(0.25f)); + // sideways it stays + CHECK_FALSE(drag.move(700.0, 350.0, size)); + CHECK(drag.position() == doctest::Approx(0.25f)); + // back down a little + CHECK(drag.move(700.0, 380.0, size)); + CHECK(drag.position() == doctest::Approx(0.2f)); + CHECK_FALSE(drag.is_click()); + // let go: the position is what the drag left, the control keeps it + CHECK(drag.start() == 0.f); + CHECK(drag.position() == doctest::Approx(0.2f)); +} + +TEST_CASE("universal drag: the control stops at its ends, and moving back takes it back at once") { + auto const size{100.0}; + universal_drag::drag drag{direction::right, 0.9f}; + drag.move(0.0, 0.0, size); + CHECK(drag.move(50.0, 0.0, size)); + CHECK(drag.position() == 1.f); + // further on it stays at the end + CHECK_FALSE(drag.move(200.0, 0.0, size)); + CHECK(drag.position() == 1.f); + // back: from the end, not from where the cursor went past it + CHECK(drag.move(190.0, 0.0, size)); + CHECK(drag.position() == doctest::Approx(0.9f)); + // and the other end + CHECK(drag.move(0.0, 0.0, size)); + CHECK(drag.position() == 0.f); +} + +TEST_CASE("universal drag: a press let go with the cursor barely moved is a click") { + auto const size{600.0}; + universal_drag::drag drag{direction::down, 0.4f}; + drag.move(10.0, 10.0, size); + // a jitter of the hand, under the travel of a click + drag.move(11.0, 13.0, size); + drag.move(10.0, 11.0, size); + CHECK(drag.is_click()); + // the click moves it to the end farther from it, as the key does + CHECK(universal_drag::toggled(drag.position()) == 1.f); + // a drag there and back is a drag, though it ends where it started + universal_drag::drag back{direction::down, 0.4f}; + back.move(0.0, 0.0, size); + back.move(0.0, 60.0, size); + back.move(0.0, 0.0, size); + CHECK_FALSE(back.is_click()); + CHECK(back.position() == doctest::Approx(0.4f)); +} + +TEST_CASE("universal drag: a drag starts from the position the control is set to") { + universal_drag::drag drag{direction::up, 0.6f}; + CHECK(drag.start() == doctest::Approx(0.6f)); + CHECK(drag.position() == doctest::Approx(0.6f)); + // a position out of the range is brought into it + CHECK(universal_drag::drag{direction::up, 3.f}.position() == 1.f); + CHECK(universal_drag::drag{direction::up, -1.f}.position() == 0.f); +} + +TEST_CASE("universal drag: a control which can't be dragged doesn't move") { + universal_drag::drag drag{direction::none, 0.f}; + drag.move(0.0, 0.0, 600.0); + CHECK_FALSE(drag.move(300.0, -300.0, 600.0)); + CHECK(drag.position() == 0.f); + CHECK(drag.is_click()); +} diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index 52bf7795d..6289fe5a2 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -121,8 +121,9 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu Parser.getTokens(); if( Parser.peek() != "{" ) { // old fixed size config - // it has no scaletable:, drop the one of an earlier definition of the same control + // it has no scaletable: nor drag:, drop the ones of an earlier definition of the same control m_scaletable.clear(); + m_drag = universal_drag::direction::none; Parser >> submodelname; gaugetypename = Parser.getToken( true ); Parser.getTokens( 3, false ); @@ -168,6 +169,7 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu } gauge_scale::sort( scratchpad.scaletable ); m_scaletable = std::move( scratchpad.scaletable ); + m_drag = scratchpad.drag; // post-deserialization cleanup // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) if( scratchpad.soundproofing ) { @@ -308,6 +310,16 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { >> soundproofing[ 5 ]; Scratchpad.soundproofing = soundproofing; } + else if( key == "drag:" ) { + // the mouse drags the control to any position between its ends, moving in the given direction to open it + // (MaSzyna-EU07/maszyna#62) + auto const value { Input.getToken( true, "\n\r\t ,;" ) }; + auto const drag { universal_drag::parse( value ) }; + if( false == drag.has_value() ) { + ErrorLog( "Bad model: unknown drag direction \"" + value + "\" of a cab control, it takes up, down, left, right, yes or no", logtype::model ); + } + Scratchpad.drag = drag.value_or( universal_drag::direction::none ); + } else if( key == "scaletable:" ) { // non-uniform scale in format [ value1 scaled1, value2 scaled2, ... ] return Load_scaletable( Input, Scratchpad ); diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index c16509f79..18ddf373a 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" #include "vehicle/gaugescale.h" +#include "vehicle/universaldrag.h" enum class TGaugeAnimation { // typ ruchu @@ -86,6 +87,10 @@ public: // true if the gauge was given a non-uniform scale (scaletable:) bool has_scaletable() const { return false == m_scaletable.empty(); } + // the direction the mouse drags the control in to any position between its ends (drag:, MaSzyna-EU07/maszyna#62), + // none for a control set only to its ends. a push control springs back, so it isn't dragged + universal_drag::direction drag() const { + return universal_drag::effective( m_drag, is_push() ); } // members TSubModel *SubModel { nullptr }; // McZapkie-310302: zeby mozna bylo sprawdzac czy zainicjowany poprawnie TSubModel *SubModelOn { nullptr }; // optional submodel visible when the state input is set @@ -96,6 +101,7 @@ private: std::optional< std::array > soundproofing; bool duplicate { false }; // the definition is a duplicate submodel of the control defined before std::vector scaletable; // as read, in the units of the config + universal_drag::direction drag { universal_drag::direction::none }; }; // methods // imports member data pair from the config file @@ -127,6 +133,7 @@ private: float m_endvalue { -1.f }; // end value of accepted value range bool m_interpolatescale { false }; std::vector m_scaletable; // optional non-uniform scale, sorted by value; replaces scale and offset + universal_drag::direction m_drag { universal_drag::direction::none }; // the mouse drags the control smoothly, drag: char m_datatype { '\0' }; // typ zmiennej parametru: f-float, d-double, i-int, b-bool; none until one is assigned union { diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 50659934c..f2766a265 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -537,6 +537,36 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = { {user_command::generictoggle27, &TTrain::OnCommand_generictoggle}, {user_command::generictoggle28, &TTrain::OnCommand_generictoggle}, {user_command::generictoggle29, &TTrain::OnCommand_generictoggle}, + {user_command::genericset0, &TTrain::OnCommand_genericset}, + {user_command::genericset1, &TTrain::OnCommand_genericset}, + {user_command::genericset2, &TTrain::OnCommand_genericset}, + {user_command::genericset3, &TTrain::OnCommand_genericset}, + {user_command::genericset4, &TTrain::OnCommand_genericset}, + {user_command::genericset5, &TTrain::OnCommand_genericset}, + {user_command::genericset6, &TTrain::OnCommand_genericset}, + {user_command::genericset7, &TTrain::OnCommand_genericset}, + {user_command::genericset8, &TTrain::OnCommand_genericset}, + {user_command::genericset9, &TTrain::OnCommand_genericset}, + {user_command::genericset10, &TTrain::OnCommand_genericset}, + {user_command::genericset11, &TTrain::OnCommand_genericset}, + {user_command::genericset12, &TTrain::OnCommand_genericset}, + {user_command::genericset13, &TTrain::OnCommand_genericset}, + {user_command::genericset14, &TTrain::OnCommand_genericset}, + {user_command::genericset15, &TTrain::OnCommand_genericset}, + {user_command::genericset16, &TTrain::OnCommand_genericset}, + {user_command::genericset17, &TTrain::OnCommand_genericset}, + {user_command::genericset18, &TTrain::OnCommand_genericset}, + {user_command::genericset19, &TTrain::OnCommand_genericset}, + {user_command::genericset20, &TTrain::OnCommand_genericset}, + {user_command::genericset21, &TTrain::OnCommand_genericset}, + {user_command::genericset22, &TTrain::OnCommand_genericset}, + {user_command::genericset23, &TTrain::OnCommand_genericset}, + {user_command::genericset24, &TTrain::OnCommand_genericset}, + {user_command::genericset25, &TTrain::OnCommand_genericset}, + {user_command::genericset26, &TTrain::OnCommand_genericset}, + {user_command::genericset27, &TTrain::OnCommand_genericset}, + {user_command::genericset28, &TTrain::OnCommand_genericset}, + {user_command::genericset29, &TTrain::OnCommand_genericset}, {user_command::vehiclemoveforwards, &TTrain::OnCommand_vehiclemoveforwards}, {user_command::vehiclemovebackwards, &TTrain::OnCommand_vehiclemovebackwards}, {user_command::vehicleboost, &TTrain::OnCommand_vehicleboost}, @@ -6994,19 +7024,9 @@ void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) } else { - // two-state switch - if (item.GetDesiredValue() < 0.5) - { - // turn on - // visual feedback - item.UpdateValue(1.0); - } - else - { - // turn off - // visual feedback - item.UpdateValue(0.0); - } + // two-state switch, or one dragged in between its ends with the mouse: to the end farther from it + // visual feedback + item.UpdateValue(universal_drag::toggled(item.GetDesiredValue())); } } else if (Command.action == GLFW_RELEASE && item.type() == TGaugeType::push) @@ -7018,6 +7038,46 @@ void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) } } +// sets a universal control to the position given in param1, from 0 to 1 (MaSzyna-EU07/maszyna#62): the mouse drags +// the ones with drag: in their definition, and it can be bound to an axis of a gamepad. it stays where it is set +void TTrain::OnCommand_genericset(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_RELEASE) + { + return; + } + auto const itemindex = static_cast(Command.command) - static_cast(user_command::genericset0); + auto &item = Train->ggUniversals[itemindex]; + if (item.is_push()) + { + // an impulse switch springs back, it has no position to be left in + return; + } + // visual feedback + item.UpdateValue(universal_drag::clamp(Command.param1)); +} + +universal_drag::direction TTrain::universal_drag_direction(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size()) || ggUniversals[Index].SubModel == nullptr) + { + return universal_drag::direction::none; + } + return ggUniversals[Index].drag(); +} + +float TTrain::universal_position(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size())) + { + return 0.f; + } + return ggUniversals[Index].GetDesiredValue(); +} + void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Command) { diff --git a/vehicle/Train.h b/vehicle/Train.h index a547eef72..e6cc0f3ba 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -172,6 +172,11 @@ class TTrain { inline std::string GetLabel( TSubModel const *Control ) const { return m_controlmapper.find( Control ); } + // the direction the mouse drags universal control Index in to any position between its ends, none if the control + // is only set to its ends (MaSzyna-EU07/maszyna#62) + universal_drag::direction universal_drag_direction( int const Index ) const; + // the position universal control Index is set to, from 0 to 1 + float universal_position( int const Index ) const; void UpdateCab(); bool Update( double const Deltatime ); void UpdateDirectionRelays(); @@ -518,6 +523,7 @@ class TTrain { static void OnCommand_cabchangeforward( TTrain *Train, command_data const &Command ); static void OnCommand_cabchangebackward( TTrain *Train, command_data const &Command ); static void OnCommand_generictoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_genericset( TTrain *Train, command_data const &Command ); static void OnCommand_vehiclemoveforwards( TTrain *Train, command_data const &Command ); static void OnCommand_vehiclemovebackwards( TTrain *Train, command_data const &Command ); static void OnCommand_vehicleboost( TTrain *Train, command_data const &Command ); diff --git a/vehicle/universaldrag.h b/vehicle/universaldrag.h new file mode 100644 index 000000000..d25f93c57 --- /dev/null +++ b/vehicle/universaldrag.h @@ -0,0 +1,138 @@ +/* +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 + +// smooth regulation of the universal cab controls (MaSzyna-EU07/maszyna#62): a universal whose definition in the +// .mmd has "drag: " can be dragged with the mouse to any position between its ends (0 and 1), and stays +// where it is let go, like a window opened a crack or a sun blind pulled half way down. a click without dragging and +// the keys still move it to its ends, as they do any universal. universals without the key work as they always did +namespace universal_drag { + +// the way the mouse moves to take the control towards its end 1 (to open it); none: the control can't be dragged +enum class direction { none, up, down, left, right }; + +// the direction the value of the drag: key gives, nothing for a value it doesn't know +inline std::optional parse(std::string_view const Value) { + if (Value == "yes" || Value == "true" || Value == "1" || Value == "up") { + return direction::up; + } + if (Value == "down") { + return direction::down; + } + if (Value == "left") { + return direction::left; + } + if (Value == "right") { + return direction::right; + } + if (Value == "no" || Value == "false" || Value == "0" || Value == "none") { + return direction::none; + } + return std::nullopt; +} + +// a push (impulse) universal springs back when it is let go, so it can't be left anywhere in between +inline direction effective(direction const Drag, bool const Push) { + return Push ? direction::none : Drag; +} + +// the position of the control, kept between its ends +inline float clamp(double const Position) { + return static_cast(std::clamp(Position, 0.0, 1.0)); +} + +// how far the cursor moving by Dx, Dy pixels (y grows downwards, as the cursor's does) takes the control along the +// Drag direction, as a fraction of its full travel; Size is the move in pixels which takes it from one end to the other +inline double along(direction const Drag, double const Dx, double const Dy, double const Size) { + if (Size <= 0.0) { + return 0.0; + } + switch (Drag) { + case direction::up: + return -Dy / Size; + case direction::down: + return Dy / Size; + case direction::left: + return -Dx / Size; + case direction::right: + return Dx / Size; + default: + return 0.0; + } +} + +// the position the keys and a click move the control to: the end farther from the position it is set to, as for +// the two-state universals: a control open less than half way opens fully, one open half way or more closes +inline float toggled(float const Desired) { + return Desired < 0.5f ? 1.f : 0.f; +} + +// the travel of the cursor along the direction of the drag, as a fraction of the full travel of the control, under +// which letting the button go counts as a click rather than a drag +inline constexpr double click_travel{0.02}; + +// one drag of a control, from the press of the mouse button to its release +class drag { + + public: + drag(direction const Drag, float const Position) : m_direction{Drag}, m_position{clamp(Position)}, m_start{m_position} {} + + // the cursor moved to X, Y; Size is the move in pixels which takes the control from one end to the other. + // the first position of the cursor is only where the drag starts from: when the cursor gets hidden for the drag + // it can be put elsewhere. returns whether the position of the control changed + bool move(double const X, double const Y, double const Size) { + if (false == m_started) { + m_started = true; + m_x = X; + m_y = Y; + return false; + } + auto const step{along(m_direction, X - m_x, Y - m_y, Size)}; + m_x = X; + m_y = Y; + m_travel += std::abs(step); + // the position follows each move from where it is, so after the control reached its end, moving the cursor + // back takes it back at once rather than after the overshoot is undone + auto const position{clamp(m_position + step)}; + if (position == m_position) { + return false; + } + m_position = position; + return true; + } + // the position the control is dragged to + float position() const { + return m_position; + } + // the position the control was in when the drag started + float start() const { + return m_start; + } + // whether letting the button go now is a click rather than a drag: the cursor barely moved along the direction + bool is_click() const { + return m_travel < click_travel; + } + + private: + direction m_direction; + float m_position; + float m_start; + bool m_started{false}; + double m_x{0.0}; + double m_y{0.0}; + double m_travel{0.0}; // the moves of the cursor along the direction, either way, as fractions of the full travel +}; + +} // namespace universal_drag From 795883335dc3c04e4c896a093613576c21b151c0 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 02:30:55 +0100 Subject: [PATCH 51/59] feat: orbit, shunting, coupling and trackside views of the train (eu07/maszyna#551) [Shift]+[F4] goes on after the four views it had (front of the train, its rear, a bogie, drive-by) to four views that go with one vehicle of the train: - orbit: around the middle of the vehicle. Left/right arrows (and the mouse) turn the camera around it, up/down arrows bring it closer and further (from outside the body to 250 m), PgUp/PgDn (and the mouse) raise and lower it; it never goes below 0.5 m above the rails. It turns with the vehicle. - shunting: straight down from above the vehicle, the way the user drives up the screen, going with it. Arrows move it along and across the train, PgUp/PgDn up and down (from above the roof to 300 m). - coupling: low beside a coupler, looking at it. At an end of the train with another vehicle (not coupled) closer than 150 m, it starts at that end and steps back from the track as the gap grows, looking between the two couplers. Left/right arrows pick the side of the track, up/down the distance, PgUp/PgDn the height. - trackside: a railfan beside the line ahead of the train, looking at the vehicle picked as the train comes and goes by. Once its tail is 40 m past (or the train is 1 km away) the railfan walks to a new spot ahead, 15 s of the train's run away (80-500 m, along the curve of the line), on the other side of the track. [ and ] pick the vehicle the view goes with (the coupling, in the coupling view), towards the front and the rear of the train; the view starts with the vehicle the user drives. [ and ] are bound to nothing by default nor in the shipped eu07_input-keyboard.ini; [Ctrl]+[ / ] stay the debug train moves. The camera follows from pure functions in vehicle/cameraviews.cpp (eu07_core), tested in tests/unit/test_camera_views.cpp; application/consistviews.cpp hands them the vehicles of the train and keeps what the user set. The four older views and their order don't change. "consistviews no" in eu07.ini keeps the cycle of [Shift]+[F4] to the four older views. The black box writes the new views as 4-7 (blackbox_doc.md). --- CMakeLists.txt | 2 + application/consistviews.cpp | 311 +++++++++++++++++++++++++ application/consistviews.h | 74 ++++++ application/drivermode.cpp | 44 +++- application/drivermode.h | 11 + blackbox_doc.md | 2 +- tests/unit/test_camera_views.cpp | 386 +++++++++++++++++++++++++++++++ utilities/Globals.cpp | 8 + utilities/Globals.h | 1 + vehicle/blackbox.h | 2 +- vehicle/cameraviews.cpp | 281 ++++++++++++++++++++++ vehicle/cameraviews.h | 182 +++++++++++++++ 12 files changed, 1300 insertions(+), 4 deletions(-) create mode 100644 application/consistviews.cpp create mode 100644 application/consistviews.h create mode 100644 tests/unit/test_camera_views.cpp create mode 100644 vehicle/cameraviews.cpp create mode 100644 vehicle/cameraviews.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..1374a587e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -182,6 +182,7 @@ set(SOURCES "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" "application/drivermode.cpp" +"application/consistviews.cpp" "application/driveruilayer.cpp" "application/driveruipanels.cpp" "input/editorkeyboardinput.cpp" @@ -550,6 +551,7 @@ set(CORE_SOURCES "vehicle/brakesetting.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" +"vehicle/cameraviews.cpp" "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" diff --git a/application/consistviews.cpp b/application/consistviews.cpp new file mode 100644 index 000000000..15762d437 --- /dev/null +++ b/application/consistviews.cpp @@ -0,0 +1,311 @@ +/* +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 "application/consistviews.h" + +#include +#include + +#include "vehicle/Camera.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" + +namespace { + +// more vehicles than any train has: a guard against a loop in the couplings +std::size_t constexpr train_limit{1000}; +// metres the vehicle picked moves before the trackside view takes the way it went for the way of the train +double constexpr direction_step{0.5}; + +cameraviews::vehicle_pose pose_of(TDynamicObject const *Vehicle) { + cameraviews::vehicle_pose pose; + pose.position = Vehicle->GetPosition(); + pose.front = Vehicle->VectorFront(); + pose.length = Vehicle->MoverParameters->Dim.L; + pose.width = Vehicle->MoverParameters->Dim.W; + pose.height = Vehicle->MoverParameters->Dim.H; + return pose; +} + +// the end of the Vehicle the Other vehicle is beyond, -1 when it's beyond neither +int end_towards(TDynamicObject const *Vehicle, TDynamicObject const *Other) { + for (auto const side : {end::front, end::rear}) { + if (Vehicle->MoverParameters->Neighbours[side].vehicle == Other) { + return side; + } + } + return -1; +} + +// the end of the Vehicle at an end of the train, away from the Inner vehicle next to it (nullptr when it's alone) +int outer_end(TDynamicObject const *Vehicle, TDynamicObject const *Inner, int const Alone) { + if (Inner == nullptr) { + return Alone; + } + auto const inner{end_towards(Vehicle, Inner)}; + return inner < 0 ? Alone : 1 - inner; +} + +cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, int const End) { + cameraviews::coupler coupler; + coupler.position = Vehicle->CouplerPosition(static_cast(End)); + coupler.outward = Vehicle->VectorFront() * (End == end::front ? 1.0 : -1.0); + coupler.width = Vehicle->MoverParameters->Dim.W; + return coupler; +} + +// the driver's way: the front (1) or the rear (-1) of the Driven vehicle, as the user drives it +int driven_way(TDynamicObject const *Driven) { + auto const cab{Driven->MoverParameters->CabOccupied < 0 ? -1 : 1}; + auto const direction{Driven->MoverParameters->DirActive < 0 ? -1 : 1}; + return cab * direction; +} + +// the coupler of the Vehicle furthest along the Way (or furthest back, with a negative Way) +glm::dvec3 end_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { + auto const front{Vehicle->CouplerPosition(end::front)}; + auto const rear{Vehicle->CouplerPosition(end::rear)}; + return glm::dot(front - rear, Way) >= 0.0 ? front : rear; +} + +// the front of the Vehicle, or its rear when that faces the Way +glm::dvec3 facing_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { + auto const front{cameraviews::flat_front(Vehicle->VectorFront())}; + return glm::dot(front, Way) < 0.0 ? -front : front; +} + +bool usable(cameraviews::placement const &Place) { + auto const finite{[](glm::dvec3 const &Value) { return std::isfinite(Value.x) && std::isfinite(Value.y) && std::isfinite(Value.z); }}; + if (false == (finite(Place.eye) && finite(Place.target) && finite(Place.up))) { + return false; + } + auto const look{Place.target - Place.eye}; + if (glm::length(look) < 0.01 || glm::length(Place.up) < 0.5) { + return false; + } + // a camera looking along its own up has no way to tell left from right + return std::abs(glm::dot(glm::normalize(look), glm::normalize(Place.up))) < 0.999; +} + +} // namespace + +std::vector consist_views::train_of(TDynamicObject *Driven) { + std::vector train; + if (Driven == nullptr) { + return train; + } + auto const *controller{Driven->Mechanik != nullptr ? Driven->Mechanik : Driven->ctOwner}; + auto *first{controller != nullptr ? controller->Vehicle(end::front) : nullptr}; + if (first == nullptr) { + first = Driven; + } + for (auto *vehicle{first}; vehicle != nullptr && train.size() < train_limit; vehicle = vehicle->Next()) { + if (std::ranges::find(train, vehicle) != train.end()) { + break; + } + train.push_back(vehicle); + } + if (std::ranges::find(train, Driven) == train.end()) { + // the controller's list is behind the couplings: the driven vehicle alone, until it catches up + train.assign(1, Driven); + } + return train; +} + +TDynamicObject *consist_views::pick(std::vector const &Train, TDynamicObject *Driven) { + auto picked{std::ranges::find(Train, m_vehicle)}; + if (m_vehicle == nullptr || picked == Train.end()) { + picked = std::ranges::find(Train, Driven); + } + if (picked == Train.end()) { + picked = Train.begin(); + } + auto index{static_cast(picked - Train.begin())}; + if (m_view != kind::coupling) { + index = cameraviews::step_index(index, static_cast(Train.size()), m_step); + m_step = 0; + } + m_vehicle = Train[index]; + return m_vehicle; +} + +double consist_views::gap_beyond(TDynamicObject const *Vehicle, int const End) { + auto const &neighbour{Vehicle->MoverParameters->Neighbours[End]}; + if (neighbour.vehicle == nullptr || Vehicle->MoverParameters->Couplers[End].CouplingFlag != 0) { + return -1.0; + } + if (neighbour.distance > cameraviews::coupler_watch_range) { + return -1.0; + } + return std::max(0.0, static_cast(neighbour.distance)); +} + +consist_views::coupling_place consist_views::coupling_at(std::vector const &Train, int const Index) { + auto const count{static_cast(Train.size())}; + coupling_place place; + if (Index > 0 && Index < count) { + // between two vehicles of the train + auto *ahead{Train[Index - 1]}; + auto const *behind{Train[Index]}; + auto const aheadend{end_towards(ahead, behind)}; + auto const behindend{end_towards(behind, ahead)}; + place.vehicle = ahead; + place.coupler = coupler_of(ahead, aheadend < 0 ? end::rear : aheadend); + place.other = true; + place.otherposition = behind->CouplerPosition(static_cast(behindend < 0 ? end::front : behindend)); + return place; + } + // an end of the train, perhaps with another vehicle coming closer to it + auto const front{Index <= 0}; + auto *vehicle{front ? Train.front() : Train.back()}; + auto const *inner{count > 1 ? Train[front ? 1 : count - 2] : nullptr}; + auto const outer{outer_end(vehicle, inner, front ? end::front : end::rear)}; + place.vehicle = vehicle; + place.coupler = coupler_of(vehicle, outer); + auto const &neighbour{vehicle->MoverParameters->Neighbours[outer]}; + place.gap = gap_beyond(vehicle, outer); + if (place.gap >= 0.0 && (neighbour.vehicle_end == end::front || neighbour.vehicle_end == end::rear)) { + place.other = true; + place.otherposition = neighbour.vehicle->CouplerPosition(static_cast(neighbour.vehicle_end)); + } + return place; +} + +cameraviews::train_motion consist_views::motion_of(std::vector const &Train, TDynamicObject const *Driven) { + auto const position{m_vehicle->GetPosition()}; + if (false == m_moved) { + // standing, the train is to go the way the user drives + m_direction = cameraviews::flat_front(m_vehicle->VectorFront()) * + static_cast(cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), driven_way(Driven))); + m_lastposition = position; + m_moved = true; + } + else if (std::hypot(position.x - m_lastposition.x, position.z - m_lastposition.z) > direction_step) { + m_direction = cameraviews::flat_front(position - m_lastposition); + m_lastposition = position; + } + std::vector positions; + positions.reserve(Train.size()); + for (auto const *vehicle : Train) { + positions.emplace_back(vehicle->GetPosition()); + } + auto const [head, tail]{cameraviews::train_ends(positions, m_direction)}; + cameraviews::train_motion motion; + motion.direction = m_direction; + motion.head = end_along(Train[head], m_direction); + motion.tail = end_along(Train[tail], -m_direction); + motion.speed = std::abs(m_vehicle->GetVelocity()) / 3.6; + motion.width = m_vehicle->MoverParameters->Dim.W; + if (Train.size() > 1) { + auto const *behind{Train[head == 0 ? 1 : head - 1]}; + motion.curvature = cameraviews::line_curvature(Train[head]->GetPosition(), facing_along(Train[head], m_direction), behind->GetPosition(), facing_along(behind, m_direction)); + } + return motion; +} + +cameraviews::placement consist_views::place_orbit(TCamera &Camera, double const Seconds) { + auto const pose{pose_of(m_vehicle)}; + if (m_orbit.radius <= 0.0) { + m_orbit = cameraviews::orbit_start(pose); + } + // the mouse turns the camera around the vehicle rather than the view away from it + glm::dvec2 const turn{Camera.Angle.x, Camera.Angle.y}; + Camera.Angle = {}; + m_orbit = cameraviews::orbit_moved(m_orbit, Camera.Velocity, turn, Seconds, pose); + return cameraviews::orbit_placement(m_orbit, pose); +} + +cameraviews::placement consist_views::place_shunting(TCamera const &Camera, std::vector const &Train, TDynamicObject const *Driven, double const Seconds) { + auto const pose{pose_of(m_vehicle)}; + auto length{0.0}; + for (auto const *vehicle : Train) { + length += vehicle->MoverParameters->Dim.L; + } + m_topdown = cameraviews::topdown_moved(m_topdown, Camera.Velocity, Seconds, pose, 0.5 * length + 50.0); + auto const facing{cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), Driven->MoverParameters->CabOccupied)}; + return cameraviews::topdown_placement(m_topdown, pose, facing); +} + +cameraviews::placement consist_views::place_coupling(TCamera const &Camera, std::vector const &Train, double const Seconds) { + auto const count{static_cast(Train.size())}; + if (m_coupling < 0) { + auto const front{coupling_at(Train, 0)}; + auto const rear{coupling_at(Train, count)}; + m_coupling = cameraviews::first_coupling(front.gap, rear.gap, count); + } + m_coupling = cameraviews::step_index(std::min(m_coupling, count), count + 1, m_step); + m_step = 0; + auto const place{coupling_at(Train, m_coupling)}; + m_vehicle = place.vehicle; + m_coupler = cameraviews::coupler_moved(m_coupler, Camera.Velocity, Seconds); + return cameraviews::coupler_placement(m_coupler, place.coupler, place.other ? &place.otherposition : nullptr); +} + +cameraviews::placement consist_views::place_trackside(std::vector const &Train, TDynamicObject const *Driven) { + auto const motion{motion_of(Train, Driven)}; + if (cameraviews::trackside_expired(m_trackside, motion)) { + m_trackside = cameraviews::trackside_next(m_trackside, motion); + } + return cameraviews::trackside_placement(m_trackside, cameraviews::orbit_centre(pose_of(m_vehicle))); +} + +TDynamicObject *consist_views::enter(kind const View, TDynamicObject *Driven) { + m_view = View; + m_step = 0; + if (View == kind::coupling) { + // each time the view starts at the end of the train something comes closer to, or at its front + m_coupling = -1; + } + if (View == kind::trackside) { + // and the railfan finds a new spot ahead of the train + m_trackside.placed = false; + m_moved = false; + } + auto const train{train_of(Driven)}; + if (train.empty()) { + return nullptr; + } + return pick(train, Driven); +} + +void consist_views::select(int const Step) { + m_step += Step; +} + +TDynamicObject *consist_views::update(TCamera &Camera, TDynamicObject *Driven, double const Seconds) { + auto const train{train_of(Driven)}; + if (train.empty()) { + return nullptr; + } + pick(train, Driven); + cameraviews::placement place; + switch (m_view) { + case kind::orbit: + place = place_orbit(Camera, Seconds); + break; + case kind::shunting: + // straight down, the mouse would only tilt it off the train + Camera.Angle = {}; + place = place_shunting(Camera, train, Driven, Seconds); + break; + case kind::coupling: + place = place_coupling(Camera, train, Seconds); + break; + case kind::trackside: + place = place_trackside(train, Driven); + break; + } + if (usable(place)) { + Camera.Pos = place.eye; + Camera.LookAt = place.target; + Camera.vUp = place.up; + } + return m_vehicle; +} diff --git a/application/consistviews.h b/application/consistviews.h new file mode 100644 index 000000000..1c86345c0 --- /dev/null +++ b/application/consistviews.h @@ -0,0 +1,74 @@ +/* +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 "vehicle/cameraviews.h" + +class TCamera; +class TDynamicObject; + +// The outside views of the user's train that go with one of its vehicles (eu07/maszyna#551), after the four views +// [Shift]+[F4] had before: the orbit around a vehicle, the shunting view from above, the view beside a coupling +// and the trackside view of a railfan. [ and ] pick the vehicle (the coupling) the view goes with. The camera +// follows from cameraviews.h; this class hands over the vehicles of the train and keeps what the user set. +class consist_views { + +public: + enum class kind { orbit, shunting, coupling, trackside }; + + // starts the View of the train of the Driven vehicle, with the vehicle (or the coupling) picked before when it's + // still in the train; returns the vehicle the camera goes with, nullptr when there's no train + TDynamicObject *enter(kind View, TDynamicObject *Driven); + // picks the vehicle Step places towards the rear of the train (towards its front for a negative Step); the + // coupling in the coupling view + void select(int Step); + // places the Camera for this frame of Seconds (real time): the movement keys come from its Velocity, the mouse of + // the orbit from its Angle. returns the vehicle the camera goes with, nullptr when the train is gone + TDynamicObject *update(TCamera &Camera, TDynamicObject *Driven, double Seconds); + +private: + struct coupling_place { + TDynamicObject *vehicle{nullptr}; // the vehicle the coupler is on + cameraviews::coupler coupler; + bool other{false}; + glm::dvec3 otherposition{}; // the facing coupler of the vehicle beyond, coupled or coming closer + double gap{-1.0}; // at an end of the train: the distance to a vehicle coming closer, negative for none + }; + + // the vehicles of the train of the Driven vehicle, from its front to its rear + static std::vector train_of(TDynamicObject *Driven); + // the vehicle the camera goes with in the Train: the one picked before, or the Driven one + TDynamicObject *pick(std::vector const &Train, TDynamicObject *Driven); + // the Index coupling of the Train, 0 its front end, Train.size() its rear end + static coupling_place coupling_at(std::vector const &Train, int Index); + // the distance to a vehicle not coupled beyond the End of the Vehicle, negative for none + static double gap_beyond(TDynamicObject const *Vehicle, int End); + // keeps up the way the train goes and works out where its ends are, for the trackside view + cameraviews::train_motion motion_of(std::vector const &Train, TDynamicObject const *Driven); + + cameraviews::placement place_orbit(TCamera &Camera, double Seconds); + cameraviews::placement place_shunting(TCamera const &Camera, std::vector const &Train, TDynamicObject const *Driven, double Seconds); + cameraviews::placement place_coupling(TCamera const &Camera, std::vector const &Train, double Seconds); + cameraviews::placement place_trackside(std::vector const &Train, TDynamicObject const *Driven); + + kind m_view{kind::orbit}; + TDynamicObject *m_vehicle{nullptr}; // the vehicle picked; only compared with the vehicles of the train, never followed + int m_step{0}; // vehicles to step over in the next update, from [ and ] + int m_coupling{-1}; // the coupling picked in the coupling view, -1 not yet + cameraviews::orbit m_orbit; + cameraviews::topdown m_topdown; + cameraviews::coupler_view m_coupler; + cameraviews::trackside m_trackside; + glm::dvec3 m_lastposition{}; // of the vehicle picked, where the trackside view last saw it move + glm::dvec3 m_direction{0.0, 0.0, -1.0}; // the way the train goes, for the trackside view + bool m_moved{false}; // m_lastposition is known +}; diff --git a/application/drivermode.cpp b/application/drivermode.cpp index cde7e80d7..47ab3ae0c 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -739,7 +739,12 @@ void driver_mode::update_camera(double const Deltatime) // reset window state, it'll be set again if applicable in a check below Global.CabWindowOpen = false; - if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) + if (consist_view_active()) + { + // the orbit, shunting, coupling and trackside views place the camera themselves + update_consist_view(Deltatime); + } + else if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) { // jeśli jazda w kabinie, przeliczyć trzeba parametry kamery /* @@ -1102,6 +1107,17 @@ void driver_mode::OnKeyDown(int cKey) } break; } + case GLFW_KEY_LEFT_BRACKET: + case GLFW_KEY_RIGHT_BRACKET: + { + // in the orbit, shunting, coupling and trackside views: the vehicle (coupling) towards the front, or the rear, + // of the train. [Ctrl] with them moves the train in the debug mode, bound in the keyboard settings + if (false == Global.ctrlState && consist_view_active()) + { + m_consistviews.select(cKey == GLFW_KEY_LEFT_BRACKET ? -1 : 1); + } + break; + } default: { break; @@ -1111,6 +1127,18 @@ void driver_mode::OnKeyDown(int cKey) return; // nie są przekazywane do pojazdu wcale } +bool driver_mode::consist_view_active() const +{ + return FreeFlyModeFlag && m_externalview && m_externalviewmode >= view::orbit && Camera.m_owner != nullptr && false == DebugCameraFlag; +} + +void driver_mode::update_consist_view(double const Deltatime) +{ + auto *controlled{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; + // the camera goes with the vehicle picked, or stays where it is once the train is gone + Camera.m_owner = m_consistviews.update(Camera, controlled, Deltatime); +} + // places camera outside the controlled vehicle, or nearest if nothing is under control // depending on provided switch the view is placed right outside, or at medium distance void driver_mode::DistantView(bool const Near) @@ -1159,7 +1187,8 @@ void driver_mode::ExternalView() if (true == m_externalview) { // we're already in some external view mode, so select next one on the list - m_externalviewmode = clamp_circular(++m_externalviewmode, static_cast(view::count_)); + // the views of the train's vehicles come after the four older ones, unless they're turned off in eu07.ini + m_externalviewmode = clamp_circular(++m_externalviewmode, static_cast(Global.ConsistViews ? view::count_ : view::orbit)); } FreeFlyModeFlag = true; @@ -1262,6 +1291,17 @@ void driver_mode::ExternalView() DistantView(false); break; } + case view::orbit: + case view::shunting: + case view::coupling: + case view::trackside: + { + // the camera goes with a vehicle of the train, placed by update_consist_view() from the next frame on + auto const kind{static_cast(m_externalviewmode - view::orbit)}; + Camera.m_owner = m_consistviews.enter(kind, vehicle); + Camera.m_owneroffset = {}; + break; + } default: { break; diff --git a/application/drivermode.h b/application/drivermode.h index e0406043d..7e86e99f6 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "input/gamepadinput.h" #include "Console.h" #include "vehicle/Camera.h" +#include "application/consistviews.h" #include "utilities/Classes.h" #ifdef WITH_UART #include "utilities/uart.h" @@ -55,6 +56,11 @@ private: consistrear, bogie, driveby, + // the views of consist_views (eu07/maszyna#551), left out of the cycle with consistviews off in eu07.ini + orbit, + shunting, + coupling, + trackside, count_ }; @@ -97,6 +103,10 @@ private: void CabView(); void ExternalView(); void DistantView( bool const Near = false ); + // whether the camera shows one of the views of consist_views now + bool consist_view_active() const; + // places the camera of the view of consist_views for the frame + void update_consist_view( double const Deltatime ); void set_picking( bool const Picking ); // members @@ -107,6 +117,7 @@ private: int m_externalviewmode { view::consistfront }; // selected external view mode bool m_externalview { true }; std::array m_externalviewconfigs; + consist_views m_consistviews; // the orbit, shunting, coupling and trackside views TDynamicObject *pDynamicNearest { nullptr }; // vehicle nearest to the active camera. TODO: move to camera double fTime50Hz { 0.0 }; // bufor czasu dla komunikacji z PoKeys double const m_primaryupdaterate { 1.0 / 100.0 }; diff --git a/blackbox_doc.md b/blackbox_doc.md index c58cae100..ab330dc2e 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -388,7 +388,7 @@ moved more than 0.5 m or turned more than 0.05 rad. |---------|------------------------------------------------------------------------------| | `f64` | t | | `u8` | mode: 0 from the cab, 1 an outside view of the user's train, 2 the free camera, 3 the debug camera | -| `u8` | the outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by; 0 in the other modes | +| `u8` | the outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by, 4 the orbit around a vehicle, 5 the shunting view from above, 6 beside a coupling, 7 trackside; 0 in the other modes | | `u32` | number of the vehicle the camera goes with, 0 for none | | `dvec3` | position | | `f32` | heading [rad] of where it looks, as that of a vehicle: towards (sin, cos) in (x, z) | diff --git a/tests/unit/test_camera_views.cpp b/tests/unit/test_camera_views.cpp new file mode 100644 index 000000000..2529efbb9 --- /dev/null +++ b/tests/unit/test_camera_views.cpp @@ -0,0 +1,386 @@ +#include "stdafx.h" +#include "doctest.h" + +#include +#include + +#include "vehicle/cameraviews.h" + +// the outside views of the train that go with one of its vehicles (eu07/maszyna#551): orbit, shunting from above, +// beside a coupling, trackside. The camera follows from the place of the vehicle and the keys alone. + +namespace { + +using cameraviews::move_keys; + +// a 20 m coach standing at Position, facing Front +cameraviews::vehicle_pose coach(glm::dvec3 const &Position = {100.0, 50.0, 200.0}, glm::dvec3 const &Front = {0.0, 0.0, -1.0}) { + cameraviews::vehicle_pose pose; + pose.position = Position; + pose.front = Front; + pose.length = 20.0; + pose.width = 3.0; + pose.height = 4.0; + return pose; +} + +double flat_distance(glm::dvec3 const &A, glm::dvec3 const &B) { + return std::hypot(A.x - B.x, A.z - B.z); +} + +// a key held, as TCamera::Velocity has it outside the cab +double constexpr key{1.0}; + +} // namespace + +TEST_CASE("camera views: the orbit starts outside the vehicle, ahead of it on its left, above the rails") { + auto const pose{coach()}; + auto const orbit{cameraviews::orbit_start(pose)}; + auto const place{cameraviews::orbit_placement(orbit, pose)}; + auto const centre{cameraviews::orbit_centre(pose)}; + + CHECK(place.target == centre); + CHECK(glm::distance(place.eye, centre) == doctest::Approx(orbit.radius)); + CHECK(orbit.radius >= cameraviews::orbit_min_radius(pose)); + auto const offset{place.eye - centre}; + CHECK(glm::dot(offset, pose.front) > 0.0); // ahead + CHECK(glm::dot(offset, glm::dvec3{-1.0, 0.0, 0.0}) > 0.0); // on the left of a vehicle facing -z + CHECK(place.eye.y > pose.position.y + pose.height); +} + +TEST_CASE("camera views: the orbit radius stays between the body of the vehicle and its limit") { + auto const pose{coach()}; + auto orbit{cameraviews::orbit_start(pose)}; + // the up arrow held for a minute brings the camera as close as the body lets it + for (int frame = 0; frame < 600; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, 0.0, -key}, {}, 0.1, pose); + } + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_min_radius(pose))); + // the diagonal of the body, so it's outside at any angle + CHECK(orbit.radius > 0.5 * std::hypot(pose.length, pose.width)); + + for (int frame = 0; frame < 600; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, 0.0, key}, {}, 0.1, pose); + } + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_max_radius)); + + // a radius not set yet becomes the default one of the vehicle + cameraviews::orbit unset; + CHECK(cameraviews::orbit_clamped(unset, pose).radius == doctest::Approx(cameraviews::orbit_start(pose).radius)); +} + +TEST_CASE("camera views: the orbit keeps above the rails however low it goes") { + auto const pose{coach()}; + for (auto const radius : {12.0, 25.0, 100.0, 250.0}) { + CAPTURE(radius); + auto orbit{cameraviews::orbit_start(pose)}; + orbit.radius = radius; + for (int frame = 0; frame < 300; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, -key, 0.0}, {}, 0.1, pose); + } + auto const place{cameraviews::orbit_placement(orbit, pose)}; + CHECK(place.eye.y >= pose.position.y + cameraviews::rail_clearance - 1e-9); + CHECK(orbit.elevation >= cameraviews::orbit_min_elevation - 1e-9); + } + // up to its highest it doesn't go over the top + auto orbit{cameraviews::orbit_start(pose)}; + for (int frame = 0; frame < 300; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, key, 0.0}, {}, 0.1, pose); + } + CHECK(orbit.elevation == doctest::Approx(cameraviews::orbit_max_elevation)); + // the mouse moved up a lot at once is held the same way + orbit = cameraviews::orbit_moved(orbit, {}, {10.0, 0.0}, 0.0, pose); + CHECK(orbit.elevation == doctest::Approx(cameraviews::orbit_lowest_elevation(pose, orbit.radius))); +} + +TEST_CASE("camera views: the left key takes the orbit clockwise around the vehicle, as a step to the left") { + auto const pose{coach()}; + cameraviews::orbit orbit; + orbit.radius = 30.0; + orbit = cameraviews::orbit_clamped(orbit, pose); + auto const ahead{cameraviews::orbit_placement(orbit, pose)}; + CHECK(glm::dot(ahead.eye - ahead.target, pose.front) > 0.0); + + // a little to the left from in front of the vehicle: the camera comes round to its right side + auto const moved{cameraviews::orbit_moved(orbit, move_keys{-key, 0.0, 0.0}, {}, 0.5, pose)}; + CHECK(moved.azimuth < orbit.azimuth); + auto const place{cameraviews::orbit_placement(moved, pose)}; + CHECK((place.eye - place.target).x > 0.0); // the right of a vehicle facing -z is +x + + // so does the mouse moved to the right (TCamera::Angle.y goes down) + CHECK(cameraviews::orbit_moved(orbit, {}, {0.0, -0.2}, 0.0, pose).azimuth == doctest::Approx(orbit.azimuth - 0.2)); + + // all the way round, the azimuth stays within half a turn either way + auto round{orbit}; + for (int frame = 0; frame < 200; ++frame) { + round = cameraviews::orbit_moved(round, move_keys{key, 0.0, 0.0}, {}, 0.1, pose); + REQUIRE(std::abs(round.azimuth) <= std::numbers::pi + 1e-9); + } +} + +TEST_CASE("camera views: the orbit turns with the vehicle and moves with it") { + auto const north{coach({0.0, 10.0, 0.0}, {0.0, 0.0, -1.0})}; + // the same vehicle further on, turned to face east (+x) on a slope + auto const east{coach({500.0, 20.0, -300.0}, glm::normalize(glm::dvec3{1.0, 0.05, 0.0}))}; + auto const orbit{cameraviews::orbit_start(north)}; + + auto const before{cameraviews::orbit_placement(orbit, north)}; + auto const after{cameraviews::orbit_placement(orbit, east)}; + auto const a{before.eye - before.target}; + auto const b{after.eye - after.target}; + CHECK(b.y == doctest::Approx(a.y)); + // a quarter turn clockwise from above: -z becomes +x, so the offset (x, z) becomes (-z, x) + CHECK(b.x == doctest::Approx(-a.z)); + CHECK(b.z == doctest::Approx(a.x)); + CHECK(after.target == cameraviews::orbit_centre(east)); +} + +TEST_CASE("camera views: a longer vehicle picked keeps the orbit outside its body") { + auto const shortvehicle{coach()}; + auto longvehicle{coach()}; + longvehicle.length = 40.0; + cameraviews::orbit orbit; + orbit.radius = cameraviews::orbit_min_radius(shortvehicle); + orbit = cameraviews::orbit_clamped(orbit, longvehicle); + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_min_radius(longvehicle))); + CHECK(orbit.radius > 20.0); +} + +TEST_CASE("camera views: the shunting view looks straight down, the way the user drives up the screen") { + auto const pose{coach()}; + cameraviews::topdown view; + view = cameraviews::topdown_clamped(view, pose, 100.0); + CHECK(view.height >= cameraviews::topdown_min_height(pose)); + + auto const place{cameraviews::topdown_placement(view, pose, 1)}; + CHECK(place.eye.x == doctest::Approx(pose.position.x)); + CHECK(place.eye.z == doctest::Approx(pose.position.z)); + CHECK(place.eye.y == doctest::Approx(pose.position.y + view.height)); + CHECK(place.target.x == doctest::Approx(place.eye.x)); + CHECK(place.target.z == doctest::Approx(place.eye.z)); + CHECK(place.up.z == doctest::Approx(-1.0)); // the front of the vehicle up the screen + + // driven from the rear cab, its rear is up the screen + CHECK(cameraviews::topdown_placement(view, pose, -1).up.z == doctest::Approx(1.0)); + + // the vehicle turned to face east: the screen turns with it + auto const east{coach({0.0, 0.0, 0.0}, {1.0, 0.0, 0.0})}; + CHECK(cameraviews::topdown_placement(view, east, 1).up.x == doctest::Approx(1.0)); +} + +TEST_CASE("camera views: the shunting view moves along and across the train and up, within its limits") { + auto const pose{coach()}; + auto const along{60.0}; + auto view{cameraviews::topdown_clamped({}, pose, along)}; + auto const height{view.height}; + + // the up arrow moves it up the screen, the way the user drives + auto const forward{cameraviews::topdown_moved(view, move_keys{0.0, 0.0, -key}, 1.0, pose, along)}; + CHECK(forward.along > 0.0); + auto const place{cameraviews::topdown_placement(forward, pose, -1)}; + CHECK(place.eye.z > pose.position.z); // driven from the rear cab, up the screen is +z + // the right arrow to the right of the screen + auto const right{cameraviews::topdown_moved(view, move_keys{key, 0.0, 0.0}, 1.0, pose, along)}; + CHECK(cameraviews::topdown_placement(right, pose, 1).eye.x > pose.position.x); + CHECK(cameraviews::topdown_placement(right, pose, -1).eye.x < pose.position.x); + + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::topdown_moved(view, move_keys{key, -key, -key}, 0.1, pose, along); + } + CHECK(view.along == doctest::Approx(along)); + CHECK(view.across == doctest::Approx(cameraviews::topdown_max_across)); + CHECK(view.height == doctest::Approx(cameraviews::topdown_min_height(pose))); + CHECK(view.height < height); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::topdown_moved(view, move_keys{0.0, key, 0.0}, 0.1, pose, along); + } + CHECK(view.height == doctest::Approx(cameraviews::topdown_max_height)); +} + +TEST_CASE("camera views: the way the user drives, seen from another vehicle of the train") { + glm::dvec3 const north{0.0, 0.0, -1.0}; + glm::dvec3 const south{0.0, 0.0, 1.0}; + CHECK(cameraviews::driving_facing(north, north, 1) == 1); + CHECK(cameraviews::driving_facing(north, north, -1) == -1); + CHECK(cameraviews::driving_facing(north, north, 0) == 1); // no cab occupied counts as the front one + // a vehicle turned round in the train + CHECK(cameraviews::driving_facing(south, north, 1) == -1); + CHECK(cameraviews::driving_facing(south, north, -1) == 1); +} + +TEST_CASE("camera views: [ and ] step through the vehicles of the train and stop at its ends") { + CHECK(cameraviews::step_index(2, 5, 1) == 3); + CHECK(cameraviews::step_index(2, 5, -1) == 1); + CHECK(cameraviews::step_index(0, 5, -1) == 0); + CHECK(cameraviews::step_index(4, 5, 1) == 4); + CHECK(cameraviews::step_index(1, 5, 10) == 4); + CHECK(cameraviews::step_index(3, 1, 1) == 0); // a vehicle alone + CHECK(cameraviews::step_index(3, 0, 1) == 0); // no train + // a picked vehicle beyond the end of a train which got shorter + CHECK(cameraviews::step_index(7, 3, 0) == 2); +} + +TEST_CASE("camera views: the head and the tail of a train are its ends the way it goes") { + std::vector const positions{{0.0, 0.0, 0.0}, {0.0, 0.0, 20.0}, {0.0, 0.0, 40.0}}; + CHECK(cameraviews::train_ends(positions, {0.0, 0.0, -1.0}) == std::pair{0, 2}); + CHECK(cameraviews::train_ends(positions, {0.0, 0.0, 1.0}) == std::pair{2, 0}); + CHECK(cameraviews::train_ends({}, {0.0, 0.0, 1.0}) == std::pair{-1, -1}); +} + +TEST_CASE("camera views: the coupling view starts where another vehicle comes closer") { + auto const count{5}; + CHECK(cameraviews::first_coupling(-1.0, -1.0, count) == 0); + CHECK(cameraviews::first_coupling(30.0, -1.0, count) == 0); + CHECK(cameraviews::first_coupling(-1.0, 30.0, count) == count); + CHECK(cameraviews::first_coupling(50.0, 10.0, count) == count); + CHECK(cameraviews::first_coupling(10.0, 50.0, count) == 0); + // a vehicle too far away doesn't count + CHECK(cameraviews::first_coupling(-1.0, cameraviews::coupler_watch_range + 1.0, count) == 0); +} + +TEST_CASE("camera views: the coupling view stands beside the coupler and steps back for the vehicle coming closer") { + cameraviews::coupler coupler; + coupler.position = {0.0, 10.0, -10.0}; + coupler.outward = {0.0, 0.0, -1.0}; + coupler.width = 3.0; + cameraviews::coupler_view const view; + + auto const alone{cameraviews::coupler_placement(view, coupler, nullptr)}; + CHECK(alone.eye.x == doctest::Approx(-(1.5 + view.distance))); // on the left of the outward way, -x + CHECK(alone.eye.z > coupler.position.z); // a little back towards its vehicle + CHECK(alone.eye.y == doctest::Approx(coupler.position.y + cameraviews::buffer_height + view.height)); + CHECK(alone.target.z < coupler.position.z); // looking out past the coupler + + // a vehicle 30 m away: the camera steps back from the track and looks between the two couplers + glm::dvec3 const other{0.0, 10.0, -40.0}; + auto const coming{cameraviews::coupler_placement(view, coupler, &other)}; + CHECK(coming.eye.x < alone.eye.x); + CHECK(coming.target.z == doctest::Approx(-25.0)); + CHECK(coming.target.y == doctest::Approx(10.0 + cameraviews::buffer_height)); + // closer, the camera comes back to the track with it + glm::dvec3 const closer{0.0, 10.0, -12.0}; + CHECK(cameraviews::coupler_placement(view, coupler, &closer).eye.x == doctest::Approx(alone.eye.x)); + // far away, it stops stepping back + glm::dvec3 const distant{0.0, 10.0, -500.0}; + CHECK(cameraviews::coupler_placement(view, coupler, &distant).eye.x == doctest::Approx(-(1.5 + cameraviews::coupler_max_distance))); +} + +TEST_CASE("camera views: the keys of the coupling view") { + cameraviews::coupler_view view; + view = cameraviews::coupler_moved(view, move_keys{key, 0.0, 0.0}, 0.1); + CHECK(view.side == -1.0); + view = cameraviews::coupler_moved(view, {}, 0.1); + CHECK(view.side == -1.0); // stays on its side without the key + view = cameraviews::coupler_moved(view, move_keys{-key, 0.0, 0.0}, 0.1); + CHECK(view.side == 1.0); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::coupler_moved(view, move_keys{0.0, key, key}, 0.1); + } + CHECK(view.distance == doctest::Approx(cameraviews::coupler_max_distance)); + CHECK(view.height == doctest::Approx(cameraviews::coupler_max_height)); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::coupler_moved(view, move_keys{0.0, -key, -key}, 0.1); + } + CHECK(view.distance == doctest::Approx(cameraviews::coupler_min_distance)); + CHECK(view.height == doctest::Approx(cameraviews::coupler_min_height)); + // the lowest still above the rails + CHECK(cameraviews::buffer_height + cameraviews::coupler_min_height > 0.0); +} + +TEST_CASE("camera views: along an arc of the line, and its curvature from two vehicles") { + glm::dvec3 const start{0.0, 5.0, 0.0}; + glm::dvec3 const north{0.0, 0.0, -1.0}; + auto const [straight, straightway]{cameraviews::along_arc(start, north, 0.0, 100.0)}; + CHECK(straight.z == doctest::Approx(-100.0)); + CHECK(straight.y == doctest::Approx(5.0)); + CHECK(straightway.z == doctest::Approx(-1.0)); + + // a quarter of a circle of 500 m to the left: from going north to going west + auto const radius{500.0}; + auto const [point, way]{cameraviews::along_arc(start, north, 1.0 / radius, 0.5 * std::numbers::pi * radius)}; + CHECK(point.x == doctest::Approx(-radius)); + CHECK(point.z == doctest::Approx(-radius)); + CHECK(way.x == doctest::Approx(-1.0)); + CHECK(way.z == doctest::Approx(0.0).epsilon(1e-9)); + + // two vehicles 25 m apart on that circle, the one ahead turned to the left of the one behind + auto const angle{25.0 / radius}; + glm::dvec3 const centre{-radius, 0.0, 0.0}; + glm::dvec3 const behind{0.0, 0.0, 0.0}; + glm::dvec3 const ahead{centre + glm::dvec3{radius * std::cos(angle), 0.0, -radius * std::sin(angle)}}; + glm::dvec3 const aheadway{-std::sin(angle), 0.0, -std::cos(angle)}; + auto const curvature{cameraviews::line_curvature(ahead, aheadway, behind, north)}; + CHECK(curvature == doctest::Approx(1.0 / radius).epsilon(0.01)); + // the other way round it turns to the right + CHECK(cameraviews::line_curvature(ahead, glm::dvec3{-aheadway.x, 0.0, aheadway.z}, behind, north) < 0.0); + // too close to tell + CHECK(cameraviews::line_curvature(behind, aheadway, behind, north) == 0.0); +} + +TEST_CASE("camera views: the railfan waits for the train ahead of it and moves on once it's gone by") { + cameraviews::train_motion train; + train.direction = {0.0, 0.0, -1.0}; + train.head = {0.0, 0.0, 0.0}; + train.tail = {0.0, 0.0, 100.0}; + train.speed = 20.0; // 72 km/h + train.width = 3.0; + + cameraviews::trackside view; + REQUIRE(cameraviews::trackside_expired(view, train)); + view = cameraviews::trackside_next(view, train); + REQUIRE(view.placed); + // ahead of the head by the 15 s it needs to get there, beside the line on the right, at the eye of a man + CHECK(view.spot.z == doctest::Approx(-20.0 * cameraviews::trackside_lead_time)); + CHECK(view.spot.x == doctest::Approx(1.5 + cameraviews::trackside_distance)); + CHECK(view.spot.y == doctest::Approx(cameraviews::trackside_eye_height)); + + // the train comes and goes by: the railfan stays until its tail is well past + auto const spot{view.spot}; + for (int step = 0; step < 50; ++step) { + auto const run{10.0 * step}; + auto passing{train}; + passing.head.z -= run; + passing.tail.z -= run; + auto const tailpast{spot.z - passing.tail.z}; + CAPTURE(run); + CHECK(cameraviews::trackside_expired(view, passing) == (tailpast > cameraviews::trackside_passed)); + } + // and then walks to the other side of the line, ahead again + auto gone{train}; + gone.head.z -= 500.0; + gone.tail.z -= 500.0; + auto const next{cameraviews::trackside_next(view, gone)}; + CHECK(next.side == -view.side); + CHECK(next.spot.x == doctest::Approx(-(1.5 + cameraviews::trackside_distance))); + CHECK(next.spot.z < gone.head.z); + CHECK(false == cameraviews::trackside_expired(next, gone)); +} + +TEST_CASE("camera views: the railfan's spot ahead keeps to the line in a curve, and nearby when the train stands") { + cameraviews::train_motion train; + train.direction = {0.0, 0.0, -1.0}; + train.speed = 40.0; + auto const radius{400.0}; + train.curvature = 1.0 / radius; + cameraviews::trackside const view; + auto const next{cameraviews::trackside_next(view, train)}; + // the centre of the curve is on the left of the head, the railfan on the right of the line: outside the circle + glm::dvec3 const centre{-radius, 0.0, 0.0}; + CHECK(flat_distance(next.spot, centre) == doctest::Approx(radius + 0.5 * train.width + cameraviews::trackside_distance)); + // no further round than a quarter of the circle + CHECK(next.spot.z >= -radius - 1e-6); + + // a train standing still gets a railfan at the shortest lead + auto standing{train}; + standing.speed = 0.0; + standing.curvature = 0.0; + auto const nearby{cameraviews::trackside_next(view, standing)}; + CHECK(nearby.spot.z == doctest::Approx(-cameraviews::trackside_min_lead)); + // and as long as it stands, the railfan stays + CHECK(false == cameraviews::trackside_expired(nearby, standing)); + // a train gone far away (moved by the user, or a long way back) gets a new railfan + auto away{standing}; + away.head = {0.0, 0.0, 2000.0}; + away.tail = {0.0, 0.0, 2100.0}; + CHECK(cameraviews::trackside_expired(nearby, away)); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..c5b62edfa 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -443,6 +443,13 @@ bool global_settings::ConfigParseInput(cParser& Parser, const std::string& token return true; } + if (token == "consistviews") + { + // no: [Shift]+[F4] cycles through the four views of the train it had before the views of its vehicles + ParseOne(Parser, ConsistViews); + return true; + } + if (token == "input.gamepad") { ParseOne(Parser, InputGamepad); @@ -1746,6 +1753,7 @@ global_settings::export_as_text( std::ostream &Output ) const { << fMouseXScale << " " << fMouseYScale << "\n"; export_as_text( Output, "mousecontrol", InputMouse ); + export_as_text( Output, "consistviews", ConsistViews ); export_as_text( Output, "enabletraction", bEnableTraction ); export_as_text( Output, "loadtraction", bLoadTraction ); export_as_text( Output, "friction", fFriction ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 8d32a463c..83d6d87c1 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -232,6 +232,7 @@ struct global_settings { int iFeedbackPort{ 0 }; // dodatkowy adres dla informacji zwrotnych bool InputGamepad{ true }; // whether gamepad support is enabled bool InputMouse{ true }; // whether control pick mode can be activated + bool ConsistViews{ true }; // whether [Shift]+[F4] goes on to the orbit, shunting, coupling and trackside views of the train (eu07/maszyna#551) double fBrakeStep { 1.0 }; // krok zmiany hamulca innych niż FV4a dla klawiszy [Num3] i [Num9] double brake_speed { 3.0 }; // prędkość przesuwu hamulca dla FV4a // parametry kalibracyjne wejść z pulpitu diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 473cf677c..58735ff60 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -301,7 +301,7 @@ struct station_event { struct camera_state { double time{0.0}; std::uint8_t mode{camera_modes::free}; - std::uint8_t view{0}; // of an outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by + std::uint8_t view{0}; // of an outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by, 4 orbit, 5 shunting, 6 coupling, 7 trackside std::uint32_t vehicle{no_vehicle}; // the vehicle the camera goes with, no_vehicle for none glm::dvec3 position{0.0}; float heading{0.0f}; // [rad] of where it looks, from +z towards +x, as the heading of a vehicle diff --git a/vehicle/cameraviews.cpp b/vehicle/cameraviews.cpp new file mode 100644 index 000000000..ef0975088 --- /dev/null +++ b/vehicle/cameraviews.cpp @@ -0,0 +1,281 @@ +/* +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/cameraviews.h" + +#include +#include +#include + +namespace cameraviews { + +namespace { + +glm::dvec3 const world_up{0.0, 1.0, 0.0}; + +// radians per second of the left and right keys, and of the page keys, for a key held +double constexpr orbit_turn_rate{1.2}; +double constexpr orbit_climb_rate{0.8}; +// the radius grows (or shrinks) e times in a second of a key held +double constexpr orbit_zoom_rate{1.0}; +// the height of the shunting view grows (or shrinks) e times in a second of a key held +double constexpr topdown_zoom_rate{0.8}; +// metres per second of the shunting view moved along and across, for each metre of its height +double constexpr topdown_pan_rate{0.6}; +// metres per second of the coupling view moved closer, further, up and down +double constexpr coupler_move_rate{3.0}; +// metres the coupling view stands back from the coupler, towards its vehicle +double constexpr coupler_step_back{2.0}; +// the share of the gap to the vehicle coming closer the coupling view keeps from the side of the train +double constexpr coupler_gap_share{0.7}; + +double flat_distance(glm::dvec3 const &A, glm::dvec3 const &B) { + return std::hypot(A.x - B.x, A.z - B.z); +} + +} // namespace + +glm::dvec3 flat_front(glm::dvec3 const &Front) { + glm::dvec3 const flat{Front.x, 0.0, Front.z}; + auto const length{glm::length(flat)}; + if (length < 1e-6) { + return {0.0, 0.0, -1.0}; + } + return flat / length; +} + +glm::dvec3 flat_left(glm::dvec3 const &Flatfront) { + return glm::cross(world_up, Flatfront); +} + +int step_index(int const Index, int const Count, int const Step) { + if (Count <= 0) { + return 0; + } + return std::clamp(Index + Step, 0, Count - 1); +} + +std::pair train_ends(std::vector const &Positions, glm::dvec3 const &Direction) { + if (Positions.empty()) { + return {-1, -1}; + } + auto const way{flat_front(Direction)}; + auto const along{[&way](glm::dvec3 const &Position) { return glm::dot(Position, way); }}; + auto const [tail, head]{std::ranges::minmax_element(Positions, {}, along)}; + return {static_cast(head - Positions.begin()), static_cast(tail - Positions.begin())}; +} + +int driving_facing(glm::dvec3 const &Front, glm::dvec3 const &Drivenfront, int const Cab) { + auto const cab{Cab < 0 ? -1 : 1}; + auto const aligned{glm::dot(flat_front(Front), flat_front(Drivenfront)) < 0.0 ? -1 : 1}; + return cab * aligned; +} + +// orbit + +glm::dvec3 orbit_centre(vehicle_pose const &Vehicle) { + return Vehicle.position + world_up * (0.4 * Vehicle.height); +} + +double orbit_min_radius(vehicle_pose const &Vehicle) { + return 0.5 * std::hypot(Vehicle.length, Vehicle.width) + 1.0; +} + +orbit orbit_start(vehicle_pose const &Vehicle) { + orbit start; + start.azimuth = 0.6; + start.elevation = 0.25; + start.radius = std::max(orbit_min_radius(Vehicle), Vehicle.length + 5.0); + return orbit_clamped(start, Vehicle); +} + +double orbit_lowest_elevation(vehicle_pose const &Vehicle, double const Radius) { + auto const centre{0.4 * Vehicle.height}; + auto const sine{std::clamp((rail_clearance - centre) / std::max(Radius, 1e-3), -1.0, 1.0)}; + return std::max(orbit_min_elevation, std::asin(sine)); +} + +orbit orbit_clamped(orbit Orbit, vehicle_pose const &Vehicle) { + if (Orbit.radius <= 0.0) { + Orbit.radius = orbit_start(Vehicle).radius; + } + Orbit.radius = std::clamp(Orbit.radius, orbit_min_radius(Vehicle), std::max(orbit_min_radius(Vehicle), orbit_max_radius)); + Orbit.elevation = std::clamp(Orbit.elevation, orbit_lowest_elevation(Vehicle, Orbit.radius), orbit_max_elevation); + Orbit.azimuth = std::remainder(Orbit.azimuth, 2.0 * std::numbers::pi); + return Orbit; +} + +orbit orbit_moved(orbit Orbit, move_keys const &Keys, glm::dvec2 const &Turn, double const Seconds, vehicle_pose const &Vehicle) { + Orbit = orbit_clamped(Orbit, Vehicle); + // the left key takes the camera to the left around the vehicle, as a step to the left would while looking at it: + // clockwise seen from above. so does the mouse moved to the right, which turns the view to the right + Orbit.azimuth += Keys.x * orbit_turn_rate * Seconds + Turn.y; + // the mouse moved down looks down at the vehicle, from higher up + Orbit.elevation += Keys.y * orbit_climb_rate * Seconds - Turn.x; + // the up arrow (a negative z) brings the camera closer + Orbit.radius *= std::exp(Keys.z * orbit_zoom_rate * Seconds); + return orbit_clamped(Orbit, Vehicle); +} + +placement orbit_placement(orbit const &Orbit, vehicle_pose const &Vehicle) { + auto const front{flat_front(Vehicle.front)}; + auto const left{flat_left(front)}; + auto const around{std::cos(Orbit.azimuth) * front + std::sin(Orbit.azimuth) * left}; + auto const way{std::cos(Orbit.elevation) * around + std::sin(Orbit.elevation) * world_up}; + placement place; + place.target = orbit_centre(Vehicle); + place.eye = place.target + Orbit.radius * way; + place.up = world_up; + return place; +} + +// shunting view + +double topdown_min_height(vehicle_pose const &Vehicle) { + return Vehicle.height + 3.0; +} + +topdown topdown_clamped(topdown View, vehicle_pose const &Vehicle, double const Alonglimit) { + auto const lowest{topdown_min_height(Vehicle)}; + if (View.height <= 0.0) { + View.height = 1.5 * Vehicle.length; + } + View.height = std::clamp(View.height, lowest, std::max(lowest, topdown_max_height)); + auto const along{std::max(0.0, Alonglimit)}; + View.along = std::clamp(View.along, -along, along); + View.across = std::clamp(View.across, -topdown_max_across, topdown_max_across); + return View; +} + +topdown topdown_moved(topdown View, move_keys const &Keys, double const Seconds, vehicle_pose const &Vehicle, double const Alonglimit) { + View = topdown_clamped(View, Vehicle, Alonglimit); + auto const pan{View.height * topdown_pan_rate * Seconds}; + // the up arrow (a negative z) moves the view up the screen, the way the user drives + View.along -= Keys.z * pan; + View.across += Keys.x * pan; + View.height *= std::exp(Keys.y * topdown_zoom_rate * Seconds); + return topdown_clamped(View, Vehicle, Alonglimit); +} + +placement topdown_placement(topdown const &View, vehicle_pose const &Vehicle, int const Facing) { + auto const up{flat_front(Vehicle.front) * (Facing < 0 ? -1.0 : 1.0)}; + // looking down with the screen up the way the user drives, the right of the screen is the right of that way + auto const right{-flat_left(up)}; + placement place; + auto const ground{Vehicle.position + up * View.along + right * View.across}; + place.target = ground; + place.eye = ground + world_up * View.height; + place.up = up; + return place; +} + +// coupling view + +coupler_view coupler_moved(coupler_view View, move_keys const &Keys, double const Seconds) { + if (Keys.x < 0.0) { + View.side = 1.0; + } + else if (Keys.x > 0.0) { + View.side = -1.0; + } + View.distance = std::clamp(View.distance + Keys.z * coupler_move_rate * Seconds, coupler_min_distance, coupler_max_distance); + View.height = std::clamp(View.height + Keys.y * coupler_move_rate * Seconds, coupler_min_height, coupler_max_height); + return View; +} + +placement coupler_placement(coupler_view const &View, coupler const &Coupler, glm::dvec3 const *Other) { + auto const outward{flat_front(Coupler.outward)}; + auto const aside{flat_left(outward) * (View.side < 0.0 ? -1.0 : 1.0)}; + auto const buffers{Coupler.position + world_up * buffer_height}; + auto distance{View.distance}; + placement place; + if (Other != nullptr) { + auto const otherbuffers{*Other + world_up * buffer_height}; + distance = std::max(distance, coupler_gap_share * flat_distance(Coupler.position, *Other)); + place.target = 0.5 * (buffers + otherbuffers); + } + else { + place.target = buffers + outward; + } + distance = std::min(distance, coupler_max_distance); + place.eye = buffers - outward * coupler_step_back + aside * (0.5 * Coupler.width + distance) + world_up * View.height; + place.up = world_up; + return place; +} + +int first_coupling(double const Frontgap, double const Reargap, int const Count) { + auto const watched{[](double const Gap) { return Gap >= 0.0 && Gap <= coupler_watch_range; }}; + auto const front{watched(Frontgap)}; + auto const rear{watched(Reargap)}; + if (rear && (false == front || Reargap < Frontgap)) { + return std::max(Count, 0); + } + return 0; +} + +// trackside view + +std::pair along_arc(glm::dvec3 const &Start, glm::dvec3 const &Direction, double const Curvature, double const Distance) { + auto const way{flat_front(Direction)}; + if (std::abs(Curvature) < 1e-6) { + return {Start + way * Distance, way}; + } + auto const left{flat_left(way)}; + auto const angle{Curvature * Distance}; + auto const point{Start + way * (std::sin(angle) / Curvature) + left * ((1.0 - std::cos(angle)) / Curvature)}; + auto const heading{way * std::cos(angle) + left * std::sin(angle)}; + return {point, heading}; +} + +double line_curvature(glm::dvec3 const &Positiona, glm::dvec3 const &Directiona, glm::dvec3 const &Positionb, glm::dvec3 const &Directionb) { + auto const distance{flat_distance(Positiona, Positionb)}; + if (distance < 1.0) { + return 0.0; + } + auto const ahead{flat_front(Directiona)}; + auto const behind{flat_front(Directionb)}; + // the vehicle ahead turned to the left of the one behind it: a turn about the up axis, anticlockwise from above + auto const angle{std::atan2(glm::cross(behind, ahead).y, glm::dot(behind, ahead))}; + return angle / distance; +} + +bool trackside_expired(trackside const &View, train_motion const &Train) { + if (false == View.placed) { + return true; + } + auto const way{flat_front(Train.direction)}; + auto const offset{View.spot - Train.tail}; + auto const passed{glm::dot(glm::dvec3{offset.x, 0.0, offset.z}, way) < -trackside_passed}; + return passed || flat_distance(View.spot, Train.head) > trackside_max_distance; +} + +trackside trackside_next(trackside const &View, train_motion const &Train) { + auto lead{std::clamp(Train.speed * trackside_lead_time, trackside_min_lead, trackside_max_lead)}; + // along a sharp curve the line comes round: the spot stays within a quarter of the circle + if (auto const quarter{0.5 * std::numbers::pi}; std::abs(Train.curvature) * lead > quarter) { + lead = quarter / std::abs(Train.curvature); + } + auto const [point, heading]{along_arc(Train.head, Train.direction, Train.curvature, lead)}; + trackside next; + next.side = View.placed ? -View.side : View.side; + next.spot = point + flat_left(heading) * (next.side * (0.5 * Train.width + trackside_distance)) + world_up * trackside_eye_height; + next.placed = true; + return next; +} + +placement trackside_placement(trackside const &View, glm::dvec3 const &Target) { + placement place; + place.eye = View.spot; + place.target = Target; + place.up = world_up; + return place; +} + +} // namespace cameraviews diff --git a/vehicle/cameraviews.h b/vehicle/cameraviews.h new file mode 100644 index 000000000..a23d09e55 --- /dev/null +++ b/vehicle/cameraviews.h @@ -0,0 +1,182 @@ +/* +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 + +// The outside views of the user's train that go with one of its vehicles (eu07/maszyna#551): the orbit around a +// vehicle, the shunting view from above, the view beside a coupling and the trackside view of a railfan. Each one +// is worked out here from the place of the vehicle and the keys of the user alone, so it can be tested without the +// game; application/consistviews.cpp hands over the vehicles of the train and turns the results into the camera. +// The world has y up; the rails are at the height of the place of a vehicle (TDynamicObject::GetPosition). +namespace cameraviews { + +// a vehicle of the train, as the views see it +struct vehicle_pose { + glm::dvec3 position{}; // its middle, at the height of the rails + glm::dvec3 front{0.0, 0.0, -1.0}; // unit, towards its front coupler + double length{20.0}; + double width{3.0}; + double height{4.0}; +}; + +// where the camera stands, the point it looks at and its up +struct placement { + glm::dvec3 eye{}; + glm::dvec3 target{}; + glm::dvec3 up{0.0, 1.0, 0.0}; +}; + +// the movement keys of the camera as TCamera::Velocity has them outside the cab: x to the right, y up, z backwards +// (the up arrow gives a negative z), 1 for a key held, 5 with ctrl +using move_keys = glm::dvec3; + +// the Front of a vehicle flattened on the ground, unit; a vehicle standing upright (no heading) faces -z +glm::dvec3 flat_front(glm::dvec3 const &Front); +// to the left of the flat Front, unit +glm::dvec3 flat_left(glm::dvec3 const &Flatfront); + +// the index after Step vehicles (or couplings) from Index, among Count of them, held at the first and the last +int step_index(int Index, int Count, int Step); + +// the two ends of a train whose vehicles stand at Positions, going in the Direction: the index of the vehicle +// at its head (furthest along the Direction) and at its tail +std::pair train_ends(std::vector const &Positions, glm::dvec3 const &Direction); + +// +1 when the front of the vehicle the view goes with points the way the user drives, -1 when it points back: +// the Front of that vehicle, the Front of the vehicle the user drives and its occupied cab (1 the front one, +// -1 the rear one, 0 none) +int driving_facing(glm::dvec3 const &Front, glm::dvec3 const &Drivenfront, int Cab); + +// orbit: around the middle of the vehicle, the left and right keys (and the mouse) turn the camera around it, +// the up and down arrows bring it closer and further away, the page keys (and the mouse) raise and lower it +struct orbit { + double azimuth{0.0}; // radians around the vehicle from its front, towards its left + double elevation{0.0}; // radians above the horizon of the middle of the vehicle + double radius{0.0}; // metres from the middle of the vehicle, 0 for the default one of the vehicle +}; + +inline constexpr double orbit_max_radius{250.0}; +inline constexpr double orbit_max_elevation{1.4}; // radians, about 80 degrees +inline constexpr double orbit_min_elevation{-0.5}; // radians, about -30 degrees, if the rails let it +inline constexpr double rail_clearance{0.5}; // metres the camera keeps above the rails + +// the first orbit around a vehicle: ahead of it on its left, a little above it, as far as the vehicle is long +orbit orbit_start(vehicle_pose const &Vehicle); +// the point the orbit goes around: the middle of the vehicle, a little lower than half of its height +glm::dvec3 orbit_centre(vehicle_pose const &Vehicle); +// the nearest the camera comes to the middle of the Vehicle: outside its body whichever way it looks +double orbit_min_radius(vehicle_pose const &Vehicle); +// the lowest elevation at the Radius which keeps the camera above the rails +double orbit_lowest_elevation(vehicle_pose const &Vehicle, double Radius); +// the Orbit held within its limits around the Vehicle (radius 0 becomes the default one) +orbit orbit_clamped(orbit Orbit, vehicle_pose const &Vehicle); +// the Orbit after Seconds of the Keys held and the mouse moved by Turn (radians: x up and down, y to the left and +// right, as TCamera::Angle takes them), within its limits around the Vehicle +orbit orbit_moved(orbit Orbit, move_keys const &Keys, glm::dvec2 const &Turn, double Seconds, vehicle_pose const &Vehicle); +// the camera of the Orbit around the Vehicle, looking at its middle +placement orbit_placement(orbit const &Orbit, vehicle_pose const &Vehicle); + +// shunting view: straight down from above the vehicle, the way the user drives up the screen; it goes with the +// vehicle, the up and down arrows move it along the train, left and right across, the page keys up and down +struct topdown { + double height{0.0}; // metres above the rails, 0 for the default one of the vehicle + double along{0.0}; // metres from the middle of the vehicle along it, the way the user drives + double across{0.0}; // metres from the middle of the vehicle across it, to the right of the screen +}; + +inline constexpr double topdown_max_height{300.0}; +inline constexpr double topdown_max_across{60.0}; + +// the lowest the camera comes: above the roof of the Vehicle +double topdown_min_height(vehicle_pose const &Vehicle); +// the View held within its limits: Alonglimit metres along the vehicle either way +topdown topdown_clamped(topdown View, vehicle_pose const &Vehicle, double Alonglimit); +// the View after Seconds of the Keys held; the further the camera, the faster it moves +topdown topdown_moved(topdown View, move_keys const &Keys, double Seconds, vehicle_pose const &Vehicle, double Alonglimit); +// the camera of the View over the Vehicle; Facing +1 puts the front of the vehicle up the screen, -1 its rear +placement topdown_placement(topdown const &View, vehicle_pose const &Vehicle, int Facing); + +// coupling view: beside a coupler, low, looking along the train at it; when another vehicle comes closer to it +// the camera steps back from the track to keep both couplers in sight, looking between them +inline constexpr double buffer_height{1.06}; // metres above the rails + +struct coupler { + glm::dvec3 position{}; // the coupler at the height of the rails (TDynamicObject::CouplerPosition) + glm::dvec3 outward{0.0, 0.0, -1.0}; // unit, from its vehicle out through the coupler + double width{3.0}; // of its vehicle +}; + +struct coupler_view { + double side{1.0}; // 1 on the left of the outward way, -1 on the right + double height{0.4}; // metres above the buffers + double distance{2.5}; // metres from the side of the vehicle, before the vehicle coming closer moves it further +}; + +inline constexpr double coupler_min_distance{1.0}; +inline constexpr double coupler_max_distance{40.0}; +inline constexpr double coupler_min_height{-0.8}; // metres above the buffers: a little above the rails +inline constexpr double coupler_max_height{10.0}; +inline constexpr double coupler_watch_range{150.0}; // metres to a vehicle that still counts as coming closer + +// the View after Seconds of the Keys held: left and right move it to that side of the track, the arrows closer +// and further, the page keys up and down +coupler_view coupler_moved(coupler_view View, move_keys const &Keys, double Seconds); +// the camera beside the Coupler; Other is the facing coupler of the vehicle coming closer, when there is one +placement coupler_placement(coupler_view const &View, coupler const &Coupler, glm::dvec3 const *Other); +// the coupling of a train of Count vehicles the view starts at, numbered from 0 (its front end) to Count (its rear +// end): the end with another vehicle, not coupled, closer than coupler_watch_range (the closer one of the two), +// otherwise the front. Frontgap and Reargap are the distances to such vehicles, negative for none +int first_coupling(double Frontgap, double Reargap, int Count); + +// trackside view: a railfan standing beside the line ahead of the train, looking at it as it comes and goes by; +// once the whole train has gone past (or gone far away) the railfan walks to a new spot ahead of it, on the other +// side of the line +struct trackside { + glm::dvec3 spot{}; // the eye of the railfan + double side{-1.0}; // 1 on the left of the line, -1 on the right + bool placed{false}; +}; + +// the train as the trackside view sees it +struct train_motion { + glm::dvec3 head{}; // the vehicle at its head, the way it goes, at the height of the rails + glm::dvec3 tail{}; // the vehicle at its tail + glm::dvec3 direction{0.0, 0.0, -1.0}; // unit, flat, the way it goes + double speed{0.0}; // m/s + double curvature{0.0}; // 1/m of the line at the head, positive turning left + double width{3.0}; // of the vehicles +}; + +inline constexpr double trackside_eye_height{1.7}; +inline constexpr double trackside_distance{8.0}; // metres from the side of the train +inline constexpr double trackside_passed{40.0}; // metres the tail goes past the spot before the railfan moves on +inline constexpr double trackside_max_distance{1000.0}; // metres to the head before the railfan moves on anyway +inline constexpr double trackside_lead_time{15.0}; // seconds the train needs to reach the new spot +inline constexpr double trackside_min_lead{80.0}; +inline constexpr double trackside_max_lead{500.0}; + +// whether the railfan at the View has seen the Train go by and moves on +bool trackside_expired(trackside const &View, train_motion const &Train); +// the next spot of the railfan, ahead of the Train along its line, on the other side than the View had +trackside trackside_next(trackside const &View, train_motion const &Train); +// the camera of the railfan at the View, looking at the Target +placement trackside_placement(trackside const &View, glm::dvec3 const &Target); + +// the point and the way Distance metres on from Start going in the (flat, unit) Direction along a line which +// turns by Curvature (1/m, positive to the left) +std::pair along_arc(glm::dvec3 const &Start, glm::dvec3 const &Direction, double Curvature, double Distance); +// the curvature of the line under two vehicles of a train going its way: A ahead of B, each at its Position with +// its front (or rear) towards the way of the train; 0 when they stand too close to tell +double line_curvature(glm::dvec3 const &Positiona, glm::dvec3 const &Directiona, glm::dvec3 const &Positionb, glm::dvec3 const &Directionb); + +} // namespace cameraviews From 66b8a673616b84032f41b9abb8fb9d0650d8e4d4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 08:54:50 +0100 Subject: [PATCH 52/59] fix(timetable): read the table from its start, bound the station index both ways read_timetable() went on from the StationCount it was given and checked only the upper bound, so TimeTable[StationCount] and TimeTable[StationCount - 1] could index out of the table (Sonar cpp:S3519). It now resets the count and the table first, and checks both bounds before the next station. --- tests/unit/test_timetable.cpp | 18 ++++++++++++++++++ world/timetablereader.cpp | 9 ++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp index f4387e7f8..a41aafcce 100644 --- a/tests/unit/test_timetable.cpp +++ b/tests/unit/test_timetable.cpp @@ -229,6 +229,24 @@ TEST_CASE("timetable: a timetable longer than the table is an error") { CHECK(data.StationCount == Mtable::MaxTTableSize); } +TEST_CASE("timetable: the reader starts from an empty table, whatever the data held before") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const [error, fresh]{read(text)}; + REQUIRE(error == 0); + // a count past the table, a negative one, a stale one: the reader used to go on from it and index out of the table + for (auto const count : {Mtable::MaxTTableSize, Mtable::MaxTTableSize + 7, -3, 2}) { + CAPTURE(count); + std::istringstream input{text}; + Mtable::timetable_data data; + data.TrainName = "file"; + data.StationCount = count; + data.TimeTable[fresh.StationCount + 1].StationName = "stale"; + CHECK(Mtable::read_timetable(input, data) == 0); + CHECK(contents(data) == contents(fresh)); + CHECK(data.TimeTable[fresh.StationCount + 1].StationName == "nowhere"); + } +} + TEST_CASE("timetable: the entry whose flags hold at the stop and on the way") { // before the timetable is loaded, and with none CHECK(timetable::stop_flags_entry(0, 0) == 0); diff --git a/world/timetablereader.cpp b/world/timetablereader.cpp index 3d340e8bd..087c0205c 100644 --- a/world/timetablereader.cpp +++ b/world/timetablereader.cpp @@ -58,6 +58,9 @@ int read_timetable(std::istream &fin, timetable_data &Data) { int conversionerror{0}; auto &TimeTable{Data.TimeTable}; auto &StationCount{Data.StationCount}; + // the table is read from its start, whatever Data held before + StationCount = 0; + TimeTable.fill(TMTableEntry{}); // zapisywanie prędkości maksymalnej do wcześniejszych odcinków auto const UpdateVelocity{[&TimeTable, &StationCount](double const Velocity) { int i = StationCount; @@ -164,12 +167,12 @@ int read_timetable(std::istream &fin, timetable_data &Data) { TimeTable[0].flags = Data.Flags; auto activeradiochannel{-1}; while (!fin.fail() && !EndTable) { - ++StationCount; - if (StationCount > MaxTTableSize) { - --StationCount; + // both bounds, so TimeTable[StationCount] and TimeTable[StationCount - 1] below stay in the table + if (StationCount < 0 || StationCount >= MaxTTableSize) { conversionerror = timetable_too_long; break; } + ++StationCount; do { fin >> s; } while (!(s == "[" || fin.fail())); From ebe0a42be7891edc797e262c49ac42286d404f3e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 09:17:19 +0100 Subject: [PATCH 53/59] fix(camera): the trackside view sets the train's way again when the vehicle picked changes pick() kept m_lastposition of the vehicle before, so the next motion_of() took the step between the two vehicles for a move: the direction could point back along the train, the ends swapped and the railfan went to a spot 80+ m behind the tail. Now a change of the vehicle sets m_moved to false, and the way is set again from the way the user drives. --- application/consistviews.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/application/consistviews.cpp b/application/consistviews.cpp index 15762d437..49815f6e8 100644 --- a/application/consistviews.cpp +++ b/application/consistviews.cpp @@ -132,6 +132,11 @@ TDynamicObject *consist_views::pick(std::vector const &Train, index = cameraviews::step_index(index, static_cast(Train.size()), m_step); m_step = 0; } + if (Train[index] != m_vehicle) { + // m_lastposition is of the vehicle before: the way the train goes is set again from the way the user drives, + // or the step between the two vehicles would be taken for a move + m_moved = false; + } m_vehicle = Train[index]; return m_vehicle; } From 0645096e13180a5943c00aa306c68e247c883ff6 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 09:33:02 +0100 Subject: [PATCH 54/59] feat(physics): ship with physics.derailment monitor as the default 144 tracks in 12 of the bundled scenarios have a speed limit above the overturning speed of the reference vehicles, so the criteria as the default would change how they play. Until those limits are corrected in the pctga data, the default (and a name not known) is monitor: the legacy draw decides, and the log tells where new would derail a vehicle. new stays opt-in. --- tests/unit/test_derailment_vehicle.cpp | 8 +++++--- utilities/Globals.h | 14 ++++++++------ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index d6c94b9b0..99b6c0417 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -314,9 +314,11 @@ TEST_CASE("derailment: the names of the models in eu07.ini") { CHECK(derailment_model_of("off") == model::off); CHECK(derailment_model_of("no") == model::off); CHECK(derailment_model_of("monitor") == model::monitor); - // a name it doesn't know is the default - CHECK(derailment_model_of("physical") == model::physical); - CHECK(global_settings{}.derailment == model::physical); + // a name it doesn't know is the default: monitor, the legacy draw decides and the criteria go to the log, until the + // speed limits of the bundled sceneries are checked against them + CHECK(derailment_model_of("physical") == model::monitor); + CHECK(derailment_model_of("") == model::monitor); + CHECK(global_settings{}.derailment == model::monitor); CHECK_FALSE(global_settings{}.track_check); // written back the way it's read for (auto const value : {model::off, model::old, model::physical, model::monitor}) { diff --git a/utilities/Globals.h b/utilities/Globals.h index bc206913c..efbd7c5ca 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -298,9 +298,11 @@ struct global_settings { // by the criteria of McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops // it; off, it stays on the rails at any speed; monitor, the legacy draw decides and the log tells where the criteria - // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was + // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was. + // monitor is the default until the speed limits of the bundled sceneries are checked against the criteria (some + // tracks allow more than the reference vehicle survives there): new is opt-in until then enum class derailment_model { off, old, physical, monitor }; - derailment_model derailment = derailment_model::physical; + derailment_model derailment = derailment_model::monitor; // the collisions of rail vehicles past their buffers (physics.collisions in eu07.ini): new, the ends crush, a vehicle // may ride up onto the other one or be pushed off the track (McZapkie/collision.h); old, the legacy rule of the safe // closing speed weighed by the masses; monitor, the legacy rule decides and the log tells what the crush would be @@ -473,13 +475,13 @@ inline std::string_view name_of( global_settings::collision_model const Model ) default: { return "new"; } } } -// the models of physics.derailment by their names in eu07.ini: new (the default, also for a name it doesn't know), old, off -// or no, monitor +// the models of physics.derailment by their names in eu07.ini: new, old, off or no, monitor (the default, also for a +// name it doesn't know) inline global_settings::derailment_model derailment_model_of(std::string_view const Name) { + if( Name == "new" ) { return global_settings::derailment_model::physical; } if( Name == "old" ) { return global_settings::derailment_model::old; } if( Name == "off" || Name == "no" ) { return global_settings::derailment_model::off; } - if( Name == "monitor" ) { return global_settings::derailment_model::monitor; } - return global_settings::derailment_model::physical; + return global_settings::derailment_model::monitor; } inline std::string_view name_of( global_settings::derailment_model const Model ) { switch( Model ) { From edc961486fd845f5c4b8aa7e30366a5548a4a17a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 09:52:07 +0100 Subject: [PATCH 55/59] fix(physics): the diesel-electric dynamic brake lets the vehicle come to rest without a fade With EDBrakeV0 = EDBrakeV1 = 0 the whole force acted down to the stop and turned round each time the speed crossed zero; in FTrain it never let the stop of ComputeMovement() catch it, so the speed swung round zero. Near the stop the force is now no more than what stops the vehicle within the step. --- McZapkie/MOVER.h | 2 +- McZapkie/Mover.cpp | 11 +++++---- tests/unit/test_dynamic_brake_diesel.cpp | 30 ++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 1411ff4bd..4a3b2dba5 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2591,7 +2591,7 @@ class TMoverParameters void update_dieselelectric_dynamic_brake(double dt); double dieselelectric_dynamic_brake_demand() const; // 0..1, the effort the driver asks for double dieselelectric_dynamic_brake_limit() const; // [N] the force at full effort at the speed - void apply_dieselelectric_dynamic_brake(); // the force in place of the drive's one + void apply_dieselelectric_dynamic_brake(double dt); // the force in place of the drive's one, over the step dt double dieselelectric_motor_current(double Moment) const; // the current of the motors giving the moment double FrictionForce() const; double BrakeForceR(double ratio, double velocity) const; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 9c0b6b881..7f0ed3361 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -6615,7 +6615,7 @@ double TMoverParameters::TractionForce(double dt) if (DEDynamicBrake.level > 0.0) { // braking: no power asked for, so the drive above gave no force - apply_dieselelectric_dynamic_brake(); + apply_dieselelectric_dynamic_brake(dt); } break; } // DieselElectric @@ -7019,10 +7019,13 @@ void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) } // the force of a diesel-electric vehicle's dynamic brake, against the motion, in place of the drive's one: the motors -// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing -void TMoverParameters::apply_dieselelectric_dynamic_brake() +// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing. near the +// stop no more than what stops the vehicle within the step dt: with no fade (EDBrakeV0 = EDBrakeV1 = 0) the whole force +// would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it +void TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) { - Ft = V > 0.0 ? -DEDynamicBrake.force : V < 0.0 ? DEDynamicBrake.force : 0.0; + auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(V) / dt) : DEDynamicBrake.force}; + Ft = V > 0.0 ? -force : V < 0.0 ? force : 0.0; Fw = Ft / NPoweredAxles; Mw = Fw * WheelDiameter / 2.0; Mm = Mw / Transmision.Ratio; diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index f0851d061..fc3f30f27 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -232,3 +232,33 @@ TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brak scenario.check(); } } + +TEST_CASE("diesel-electric dynamic brake: without a fade it brings the vehicle to rest") { + // EDBrakeV0 = EDBrakeV1 = 0 (the defaults): the whole force down to the stop. near it no more than what stops the + // vehicle within the step, or the force turned round each time the speed crossed zero and the vehicle never + // came to rest, the air brake being off + scenario scenario{"dynamic brake/diesel electric/br285 no fade", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(definition::fiz("br285_v1/br285").set("Engine", "EDBrake", "Controller").set("Engine", "EDBrakeFmax", 150), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.fade_low == doctest::Approx(0.0)); + REQUIRE(locomotive.DEDynamicBrake.fade_high == doctest::Approx(0.0)); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(30.0); + REQUIRE(locomotive.Vel > 10.0); + + scenario.act("EB+ to the stop"); + controller_to(locomotive, 0); + for (int i = 0; i < 120 && locomotive.V != 0.0; ++i) { + scenario.wait(1.0); + } + CHECK(locomotive.BrakePress < 0.1); + // at rest, and staying there: no speed either way, no force + for (int i = 0; i < 5; ++i) { + scenario.wait(1.0); + CHECK(locomotive.V == 0.0); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + } + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + scenario.check(); +} From 68c704e51338d361915d1850011602fc0159d72b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 10:00:49 +0100 Subject: [PATCH 56/59] fix(config): a scenery switches a script runtime off as before, only switching it on is refused keep() put python.enabled, luascreens.enabled, wasm.enabled and lua.fulllibraries back in either direction, so a scenery with config python.enabled no endconfig, which the release honoured, was overridden and got an error in the log. They are put back now only when the scenery turned them on; switched off they stay so, silently. --- script_screens_doc.md | 5 +-- tests/unit/test_ini_only_settings.cpp | 49 +++++++++++++++++++++------ utilities/inionlysettings.cpp | 20 ++++++++--- utilities/inionlysettings.h | 3 +- 4 files changed, 59 insertions(+), 18 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 7ebf14caf..0be028952 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -264,7 +264,8 @@ again: |---------------------|---------|------------------------------------------------------------------------------------------| | `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | -Only `eu07.ini` sets it: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set +Only `eu07.ini` turns it on: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, `extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, -`feedbackmode`, `feedbackport`, `python.enabled`, `luascreens.enabled` and `wasm.enabled`. +`feedbackmode`, `feedbackport`, nor does it switch on `python.enabled`, `luascreens.enabled` or `wasm.enabled` when +`eu07.ini` has them off. A scenery may still switch those three off, or `lua.fulllibraries` off, as it always could. diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp index 8ae73fe43..f90e9b2f9 100644 --- a/tests/unit/test_ini_only_settings.cpp +++ b/tests/unit/test_ini_only_settings.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace { @@ -32,17 +33,43 @@ TEST_CASE("ini only settings: a scenery's config block doesn't give its scripts CHECK(changed == std::vector{"lua.fulllibraries"}); } -TEST_CASE("ini only settings: what eu07.ini turned on stays on") { - auto const settings{std::make_unique()}; - settings->lua_fulllibraries = true; - settings->python_enabled = false; - ini_only_settings const ini{*settings}; - settings->lua_fulllibraries = false; - settings->python_enabled = true; - auto const changed{ini.restore(*settings)}; - CHECK(settings->lua_fulllibraries); - CHECK_FALSE(settings->python_enabled); - CHECK(changed.size() == 2); +TEST_CASE("ini only settings: a scenery switches a runtime off, but not on") { + auto const python{[](global_settings &Settings) -> bool & { return Settings.python_enabled; }}; + auto const luascreens{[](global_settings &Settings) -> bool & { return Settings.luascreens_enabled; }}; + auto const wasm{[](global_settings &Settings) -> bool & { return Settings.wasm_enabled; }}; + auto const fulllibraries{[](global_settings &Settings) -> bool & { return Settings.lua_fulllibraries; }}; + using setting = bool &(*)(global_settings &); + for (auto const &[key, switched] : {std::pair{"python.enabled", python}, {"luascreens.enabled", luascreens}, + {"wasm.enabled", wasm}, {"lua.fulllibraries", fulllibraries}}) { + CAPTURE(key); + { + // on in eu07.ini, off in the scenery: off, and nothing in the log + auto const settings{std::make_unique()}; + switched(*settings) = true; + ini_only_settings const ini{*settings}; + // "config python.enabled no endconfig" in the .scn, as the release honoured it + switched(*settings) = false; + CHECK(ini.restore(*settings).empty()); + CHECK_FALSE(switched(*settings)); + } + { + // off in eu07.ini, on in the scenery: back off, and told + auto const settings{std::make_unique()}; + switched(*settings) = false; + ini_only_settings const ini{*settings}; + switched(*settings) = true; + CHECK(ini.restore(*settings) == std::vector{key}); + CHECK_FALSE(switched(*settings)); + } + // as eu07.ini set it: kept, nothing told + for (auto const value : {false, true}) { + auto const settings{std::make_unique()}; + switched(*settings) = value; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(switched(*settings) == value); + } + } } TEST_CASE("ini only settings: a scenery runs no program, opens no connection and switches no runtime back on") { diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp index 836954bf1..9d6c587c2 100644 --- a/utilities/inionlysettings.cpp +++ b/utilities/inionlysettings.cpp @@ -23,6 +23,17 @@ template void keep(Type_ &Current, Type_ const &Kept, std::stri } } +// a switch a scenery may turn off but not on: puts Kept back into Current, and adds Key to Changed, only when the +// scenery turned it on. turned off it stays so, as before these keys were kept +void keep_off(bool &Current, bool const Kept, std::string_view const Key, std::vector &Changed) +{ + if (Current && false == Kept) + { + Current = false; + Changed.push_back(Key); + } +} + } // namespace ini_only_settings::ini_only_settings(global_settings const &Settings) @@ -74,9 +85,10 @@ std::vector ini_only_settings::restore(global_settings &Settin #endif keep(Settings.iFeedbackMode, m_feedback_mode, "feedbackmode", changed); keep(Settings.iFeedbackPort, m_feedback_port, "feedbackport", changed); - keep(Settings.python_enabled, m_python_enabled, "python.enabled", changed); - keep(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); - keep(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); - keep(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + // a scenery may switch a runtime off, and keep its scripts in the sandbox + keep_off(Settings.python_enabled, m_python_enabled, "python.enabled", changed); + keep_off(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); + keep_off(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); + keep_off(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); return changed; } diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h index eff5c067f..667703b94 100644 --- a/utilities/inionlysettings.h +++ b/utilities/inionlysettings.h @@ -22,7 +22,8 @@ http://mozilla.org/MPL/2.0/. // (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports // (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a // script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled) or take its own scripts -// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set +// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set; a scenery may still switch a runtime off, or +// keep its scripts in the sandbox when eu07.ini didn't, as it always could class ini_only_settings { public: From aa2200418a2f5f8b33c33db99e167e4ca374a9ca Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 10:06:41 +0100 Subject: [PATCH 57/59] fix(doors): an animdoor entry without its } leaves the rest of the .mmd to be read read_spec() took every token up to the end of the file into the block when the closing brace was missing, so endmodels, sounds:, the lights and the rest were lost. The block now ends at the first token that is neither a key nor the value right after one (or at endmodels), and that token is put back for the caller. --- tests/unit/test_door_wings.cpp | 38 +++++++++++++++++++++++++++++++++- vehicle/doorwings.h | 17 ++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp index e049d6c61..9eff62441 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -125,11 +125,47 @@ TEST_CASE("door wings: a faulty animdoor entry says what is wrong with it") { CHECK(read("3 { type: Roll range: 0.65 }", spec) == "unknown door type \"Roll\""); CHECK(read("3 { type: Shift range: 0,65 }", spec) == "bad number \"0,65\" for \"range:\""); CHECK(read("3 { type: Shift range: wide }", spec) == "bad number \"wide\" for \"range:\""); - CHECK(read("3 { kind: Shift }", spec) == "unknown key \"kind:\""); + CHECK(read("3 { kind: Shift }", spec) == "no } after the keys, \"kind:\" is none of them"); CHECK(read("3 { type: Shift range: }", spec) == "no value for \"range:\""); CHECK(read("3 { type: Shift range: 0.65", spec) == "no } after the keys"); } +TEST_CASE("door wings: an animdoor entry without its } leaves the entries after it to the .mmd") { + // the first token that is neither a key nor the value of one ends the entry, and is read next by the caller + auto const next{[](std::string const &Text) { + door_wings::wing_spec spec{fizdoors}; + cParser parser(Text, cParser::buffer_TEXT); + auto const error{door_wings::read_spec(parser, spec)}; + std::vector rest; + std::string token; + do { + token.clear(); + parser.getTokens(1, false); + parser >> token; + if (false == token.empty()) { + rest.emplace_back(token); + } + } while (false == token.empty()); + return std::pair{error, rest}; + }}; + { + auto const [error, rest]{next("3 { type: Plug range: 0.9\nsounds: horn.wav\nlights: 1\nendmodels")}; + CHECK(error == "no } after the keys, \"sounds:\" is none of them"); + CHECK(rest == std::vector{"sounds:", "horn.wav", "lights:", "1", "endmodels"}); + } + { + auto const [error, rest]{next("3 { type: Plug range: endmodels")}; + CHECK(error == "no } after the keys, \"endmodels\" is none of them"); + CHECK(rest == std::vector{"endmodels"}); + } + { + // a whole entry leaves the rest as it is + auto const [error, rest]{next("3 { type: Plug range: 0.9 } sounds: horn.wav endmodels")}; + CHECK(error.empty()); + CHECK(rest == std::vector{"sounds:", "horn.wav", "endmodels"}); + } +} + TEST_CASE("door wings: the parsed keys go into the spec, pairs of a key and its value") { door_wings::wing_spec spec{fizdoors}; CHECK(door_wings::parse_spec({"type:", "Shift", "range:", "0.65"}, spec).empty()); diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index 1266dafec..db05b03fc 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -137,8 +137,17 @@ inline std::string parse_spec(std::vector const &Tokens, wing_spec return {}; } +// whether the token is one of the keys of an animdoor block, in any letter case +inline bool is_spec_key(std::string const &Token) { + std::string key{Token}; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return key == "type:" || key == "range:" || key == "rangeout:"; +} + // reads an animdoor entry after its key: the wing number and the block in braces, into the spec filled with the values -// of the .fiz. returns what is wrong with the entry, or an empty text when nothing is. the parser is a cParser +// of the .fiz. returns what is wrong with the entry, or an empty text when nothing is. the parser is a cParser. a block +// without its } ends at the first token that is neither a key nor the value right after one (or at endmodels): that +// token is left for the caller, so the entries after a faulty one are read as ever template std::string read_spec(Parser_ &Parser, wing_spec &Spec) { Parser.getTokens(1, false); @@ -150,6 +159,7 @@ std::string read_spec(Parser_ &Parser, wing_spec &Spec) { return "no { after the wing number"; } std::vector block; + auto value{false}; // the token is the value of the key before it while (true) { token.clear(); Parser.getTokens(1, false); @@ -160,6 +170,11 @@ std::string read_spec(Parser_ &Parser, wing_spec &Spec) { if (token == "}") { break; } + if (token == "endmodels" || (false == value && false == is_spec_key(token))) { + Parser.injectString(token); + return "no } after the keys, \"" + token + "\" is none of them"; + } + value = false == value; block.emplace_back(token); } return parse_spec(block, Spec); From 0bd805fb19722e6e98574a9e4791b3b56140ef3e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 13:01:32 +0100 Subject: [PATCH 58/59] docs: scenario README, a Connect first order releases the hand brake now --- tests/scenarios/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index b6eab8326..7ab7646e7 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -290,9 +290,9 @@ into the game dir. What they add to the scenery: A train whose trainset has velocity 0 has a driver that sleeps in `Wait_for_orders` when nobody is in the cab: the player would drive it, so the fragment has to give the orders the player's hands stand for, with `PutValues` from an event the vehicle itself sets off (`event0` of the -track it stands on). The first of them must not be the one to couple (`Shunt -2 -3`): a driver -whose first order is `Connect` never releases the hand brake a cold locomotive starts with. The -mission trains of velocity 0.1 wait for their signal and need nothing. +track it stands on). The first of them may be the one to couple (`Shunt -2 -3`): a driver whose +first order is `Connect` releases the hand brake a cold locomotive starts with +(`eu07_td_cold_connect`). The mission trains of velocity 0.1 wait for their signal and need nothing. The cases and what they showed on master of 2026-11-11: From f90005e649ab4c44c07e1f8c7ca8ef07e16b3c86 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 17:36:15 +0100 Subject: [PATCH 59/59] fix(physics): a legacy derailment makes no crash inside its own train With physics.collisions new and the legacy derailment (the default physics.derailment monitor), a vehicle derailed the old way manufactured collisions with the vehicles coupled to it: - Derail() cuts its speed by 35 % in one step; the coupled vehicles kept theirs and ran into it at a third of the speed of the train (moczniki_eu06_eu07, tomaszewo_raj49843). The vehicles coupled to it now get the same change of velocity. - crush_hit() took it as an immovable wall and its motion ignored every force (decelerating at g, then stuck by resistances x1e20), so the train behind it stopped against it at once and crushed by the energy of the whole train (l053-sluzba-2-night: 0.3 m on both ends at 8 km/h). It is now a wall only to vehicles not coupled to it; it keeps the legacy deceleration of g as a friction of its weight, and the forces of its train act on it, so the train pushes it on and it holds the train back. Alone it stops as before. - Vehicles of the pile-up found inside each other kept what their springs took in pressed past the stop as buffer energy, which let a later small closing velocity crush them; a pair parting at the start of the step and knocked back in during it was crushed with the springs added to its closing velocity (l053_calkowo-sluzba-tlk-1, linia61_osobowy3: crush at -7.1 km/h). The contact found inside each other takes in nothing until the buffers part, and a pair parting at the start of the step is left to the legacy collision. The monitor test of a locomotive into a wagon at 60 km/h now counts one hit: the second one was the locomotive resting on the legacy wall, parting at the start of the step, at 0.3 km/h. --- McZapkie/MOVER.h | 6 +- McZapkie/Mover.cpp | 93 +++++++++++++-- McZapkie/collision.cpp | 10 +- McZapkie/collision.h | 8 +- tests/unit/test_collisions.cpp | 202 ++++++++++++++++++++++++++++++++- tests/unit/vehicle.cpp | 4 +- tests/unit/vehicle.h | 4 + 7 files changed, 307 insertions(+), 20 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index ba0a76951..ab1ae9dba 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2463,6 +2463,9 @@ class TMoverParameters // was a broken coupler to repair bool repair_coupler(int const End); void Derail(DerailReason Reason); + // the velocity of the vehicles coupled to this one changes by the Change along the axis of this one [m/s], as the + // legacy derailment changes the velocity of this one (physics.collisions new) + void change_train_velocity(double Change); // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m]; monitor: what // they would do, to the log void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); @@ -2476,7 +2479,8 @@ class TMoverParameters // what resetconsist does to a vehicle: no damage of any kind, the alarm chain released, back on the rails void repair_damage(); // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other - // derailment, which stops it as the legacy model does + // derailment, which stops it as the legacy model does (with physics.collisions new by a friction of its weight, the + // forces of the vehicles coupled to it acting on it) derailment::outcome Derailed{derailment::outcome::none}; // 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 diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 3ce03219d..48543c7f4 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -69,6 +69,21 @@ int DirPatch(int Coupler1, int Coupler2) return Coupler1 != Coupler2 ? 1 : -1; } +namespace +{ + +// physics.collisions new: a rail vehicle derailed the legacy way keeps the deceleration of the legacy model, g, as the +// friction of its weight, and the forces of the vehicles coupled to it act on it as on any other: the train behind it +// pushes it on, and it holds the train back. alone it stops as the legacy model has it. the legacy model stops it +// whatever pushes it, and the train behind it stopped at once against it, in a hit no train had +bool legacy_derailed_slides(TMoverParameters const &Vehicle) +{ + return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && TestFlag(Vehicle.DamageFlag, dtrain_out) && + Vehicle.Derailed == derailment::outcome::none; +} + +} // namespace + int DirF(int CouplerN) { switch (CouplerN) @@ -1423,8 +1438,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the // velocity once more, and the vehicles would bounce off the stop faster than they hit it auto const accelerationspike{physical ? 0.0 : 1.0}; - // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit - auto const wall = [crushing](TMoverParameters const &Vehicle) { return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || Vehicle.Derailed == derailment::outcome::none); }; + // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with + // the crush, the vehicles coupled to the wall push it on (crush_hit()) + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { + return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); + }; if (false == wall(*this)) { auto const accelerationchange{(velocity - V) / dt}; @@ -1604,6 +1623,9 @@ bool TMoverParameters::crush_hit(int const End, double const dt) auto const overlap{-static_cast(Neighbours[End].distance)}; if (overlap > stop + collision::inside_margin + closing * dt) { + // nor is what their springs took in pressed past the stop and back a hit, for as long as the buffers touch + thiscoupler.contact.inside(); + othercoupler.contact.inside(); if (false == thiscoupler.inside_reported) { thiscoupler.inside_reported = true; @@ -1612,9 +1634,19 @@ bool TMoverParameters::crush_hit(int const End, double const dt) } return false; } - // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it - auto const wall{TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; - auto const otherwall{TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; + // parting at the start of the step: what closes the pair in now is the knock of a hit of either vehicle in the step, + // or of the vehicles inside each other next to it, not a hit of this pair. the legacy collision takes it; a pair + // still closing in at the start of the next step is a hit + if (thiscoupler.closing < 0.0) + { + return false; + } + // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it from outside its + // train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it + // stopped the whole train at once, and the vehicles behind it crushed by the energy of the train + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; + auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; if (wall && otherwall) { return false; @@ -2031,8 +2063,16 @@ void TMoverParameters::Derail(DerailReason const Reason) EventFlag = true; MainSwitch(false, range_t::local); + auto const velocity{V}; AccS *= 0.65; V *= 0.65; + // physics.collisions new: the vehicles coupled to it lose the speed with it. the cut in a step stands for the + // train coming to a stop with the vehicle; the coupled ones keeping their speed would run into it at a third of + // the speed of the train, and crush their ends and ride up onto it for a hit no train had + if (Global.collisions == global_settings::collision_model::physical && TestFlag(CategoryFlag, 1)) + { + change_train_velocity(V - velocity); + } RunningShape.R = 0; if (Vel < 5.0) { @@ -2057,6 +2097,28 @@ void TMoverParameters::Derail(DerailReason const Reason) } } +void TMoverParameters::change_train_velocity(double const Change) +{ + // the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one + std::vector> train{{this, 1}}; + for (std::size_t i = 0; i < train.size(); ++i) + { + auto const [vehicle, direction] = train[i]; + for (int end = end::front; end <= end::rear; ++end) + { + auto const &coupler{vehicle->Couplers[end]}; + auto *other{coupler.Connected}; + if (other == nullptr || coupler.CouplingFlag == coupling::faux || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) + { + continue; + } + auto const otherdirection{direction * DirPatch(end, coupler.ConnectedNr)}; + other->V += Change * otherdirection; + train.emplace_back(other, otherdirection); + } + } +} + // ************************************************************************************************* // Oblicza przemieszczenie taboru // ************************************************************************************************* @@ -2099,11 +2161,12 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() - if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) AccS = -Sign(V) * g * 1; // random(0.0, 0.1) // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger - auto const stuck{Derailed != derailment::outcome::none && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) AccS = 0.0; @@ -2212,9 +2275,9 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) - auto const stuck{Derailed != derailment::outcome::none && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) AccS = 0.0; @@ -2237,8 +2300,9 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh // simple mode skips calculation of vertical acceleration AccVert = 0.0; - // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() - if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && Vel < 1.0) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) { V = 0.0; AccS = 0.0; @@ -5803,6 +5867,11 @@ void TMoverParameters::ComputeTotalForce(double dt) // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side FStand = derailment::sliding_friction(Derailed) * (TotalMass - Mred) * g; } + else if (legacy_derailed_slides(*this)) + { + // derailed the legacy way with physics.collisions new: the deceleration of g of the legacy model, as a friction + FStand = TotalMass * g; + } else { // HACK: crude way to reduce speed after derailment diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp index ef3874b93..2fb085e69 100644 --- a/McZapkie/collision.cpp +++ b/McZapkie/collision.cpp @@ -171,8 +171,8 @@ void contact_energy::update(bool const Pressed, bool const Solid, double const C reset(); return; } - if (Solid) { - // pressed all the way, the buffers take in nothing more + if (Solid || m_inside) { + // pressed all the way, the buffers take in nothing more; nor do those of vehicles inside each other return; } auto const force{std::max(Force, 0.0)}; @@ -185,6 +185,11 @@ void contact_energy::update(bool const Pressed, bool const Solid, double const C } } +void contact_energy::inside() { + m_absorbed = 0.0; + m_inside = true; +} + void contact_energy::crushed(double const Work) { m_crushed += std::max(Work, 0.0); } @@ -199,6 +204,7 @@ double contact_energy::budget(double const Mass, double const Closing, double co void contact_energy::reset() { m_absorbed = 0.0; m_crushed = 0.0; + m_inside = false; } hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input) { diff --git a/McZapkie/collision.h b/McZapkie/collision.h index fb719315d..01239a3cd 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -136,12 +136,17 @@ inline constexpr double inside_margin{0.5}; // buffers pressed and the pair closing in. springing back they keep what they still hold, so a train pushing at a // stand never builds up what it feeds into their damping. the buffers pressed all the way from the start of the // contact took in nothing: vehicles put down inside each other, or knocked onto each other by a hit elsewhere, bring -// in only the kinetic energy they close in with +// in only the kinetic energy they close in with. nor do the buffers of vehicles found inside each other in the +// contact (inside_margin) take in anything until they part: their springs pressed past the stop and back throw the +// pair about, which is no hit class contact_energy { public: // the step of the pair: whether its buffers press, and all the way; the closing velocity [m/s] and the force // pressing the buffers [N] at the start of the step; how far they're pressed in [m]; the length of the step [s] void update(bool Pressed, bool Solid, double Closing, double Force, double Compression, double Dt); + // the vehicles of the pair are inside each other: what the buffers took in is gone, and they take in nothing more + // until the contact is over + void inside(); // the crush of the hit took the energy [J] void crushed(double Work); // the energy the crush may take now, closing in at the velocity [m/s] with the reduced mass [kg], the buffers of @@ -155,6 +160,7 @@ public: private: double m_absorbed{0.0}; double m_crushed{0.0}; + bool m_inside{false}; }; // ---- the hit past the buffers diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 3dead8771..6aee28e98 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -748,10 +748,11 @@ TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush wi }; // the legacy rule: over 15 km/h weighed by the ratio of the masses. the crush: the light wagon is crushed deep and // climbs onto the locomotive at 60 km/h; two locomotives at 25 km/h crush their ends 0.1-0.3 m and stay on the rails - // the monitor tells of each hit once: the wagon derailed by the legacy rule is a wall, which the locomotive behind - // it hits once more; the locomotives derailed both stay where they are + // the monitor tells of each hit once: the wagon derailed by the legacy rule is a wall the locomotive presses on into + // until it springs back, the same hit (the wall slowing down took the pair from parting at the start of a step to + // closing in at 0.3 km/h, which was told of as a second hit); the locomotives derailed both stay where they are for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new, monitored] : { - collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false, 2}, + collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false, 1}, collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false, 1}, collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true, 1}, }) { @@ -1308,3 +1309,198 @@ TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { train.run(10.0); CHECK(train[0]->crush_reports + train[1]->crush_reports == 1); } + +// ---- the legacy derailment (physics.derailment old or monitor) in a train, with physics.collisions new + +namespace { + +// what the vehicles of the train did to each other +struct train_damage { + double crush{0.0}; // the deepest crush of an end [m] + double energy{0.0}; // the crush of all the ends took [J] + int derailed{0}; // in a collision + int broken{0}; // couplings torn off + std::string list; // which vehicle, for the messages +}; + +train_damage damage_of(consist &Train) { + train_damage result; + for (std::size_t i = 0; i < Train.size(); ++i) { + auto const &vehicle{Train[i].mover()}; + result.crush = std::max(result.crush, crush_of(vehicle)); + for (auto const end : {end::front, end::rear}) { + result.energy += vehicle.crush_curve_at(end).energy(0.0, vehicle.Couplers[end].crush); + } + result.derailed += vehicle.CollisionDerail != NONE; + if (i + 1 < Train.size()) { + result.broken += vehicle.Couplers[end::rear].broken; + } + if (crush_of(vehicle) > 0.0 || vehicle.CollisionDerail != NONE) { + result.list += std::format("{} crushed {:.2f} m{}; ", i, crush_of(vehicle), vehicle.CollisionDerail != NONE ? ", derailed" : ""); + } + } + return result; +} + +// the kinetic energy of the vehicles of the train [J] +double kinetic_of(consist &Train) { + auto energy{0.0}; + for (std::size_t i = 0; i < Train.size(); ++i) { + energy += 0.5 * Train[i]->TotalMass * Train[i]->V * Train[i]->V; + } + return energy; +} + +} // namespace + +TEST_CASE("collisions: the cut of the speed of the legacy derailment is no hit inside the train (moczniki_eu06_eu07, tomaszewo_raj49843)") { + // the legacy derailment takes 35 % of the speed of the vehicle off in a step: the coaches coupled behind it, at the + // speed they had, ran into it at a third of the speed of the train, crushed their ends and rode up onto it + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + // an SU46 with its coaches at 95 km/h, as in moczniki_eu06_eu07; an electric locomotive at 48 km/h, as in + // tomaszewo_raj49843 + for (auto const &[path, speed] : {std::pair{"su46_v2/303d", 95.0}, std::pair{"4e_v1/4e", 48.0}}) { + CAPTURE(path); + // too fast in a curve, the draw in the movement of the vehicle; off the end of the track, in its next step + for (auto const reason : {TOO_HIGH_SPEED, END_OF_TRACK}) { + CAPTURE(reason); + consist train; + auto &locomotive{train.add(definition::fiz(path), 0, coupling::faux, speed)}; + for (int i = 0; i < 3; ++i) { + train.add(coach(41.0e3), 0, consist::full_coupling, speed); + } + train.run(2.0); + if (reason == END_OF_TRACK) { + locomotive.damage_track(dtrack_norail); + } + else { + locomotive->Derail(reason); + } + train.step(); + REQUIRE(derailed(locomotive.mover())); + // the train loses the speed with it + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK(train[i].speed() == doctest::Approx(locomotive.speed()).epsilon(0.03)); + } + train.run(15.0); + auto const damage{damage_of(train)}; + INFO(damage.list); + CHECK(damage.crush < cl::crush_mark); + CHECK(damage.derailed == 0); + CHECK(damage.broken == 0); + } + } + } +} + +TEST_CASE("collisions: the train behind a vehicle that ran off the end of the track doesn't crush into it (l053-sluzba-2-night, l053_calkowo-sluzba-tlk-1, linia61_osobowy3)") { + // the vehicle derailed the legacy way at the end of the track stopped as a wall the train behind it ran into: the + // vehicles behind it pressed into each other past their stops, and crushed by more than the energy of the train + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + // pulled: an M62 leading wagons of 22 t at 30 km/h (l053_calkowo-sluzba-tlk-1, linia61_osobowy3); pushed: an SM42 + // at the back of wagons of 35 t at 33 km/h, the leading wagon goes off (l053-sluzba-2-night) + for (auto const pushed : {false, true}) { + CAPTURE(pushed); + auto const speed{pushed ? 33.0 : 30.0}; + consist train; + if (false == pushed) { + train.add(definition::fiz("st44_v2/m62-1151"), 0, coupling::faux, speed); + } + constexpr int wagons{6}; + for (int i = 0; i < wagons; ++i) { + auto &wagon{train.add(definition::fiz("430w_v2/430w"), 0, consist::full_coupling, speed)}; + if (pushed) { + wagon->AssignLoad("coal", 12.0f); + wagon->ComputeMass(); + } + } + if (pushed) { + train.add(definition::fiz("sm42_v1/6d1"), 0, consist::full_coupling, speed); + } + train.run(2.0); + auto const kinetic{kinetic_of(train)}; + train[0].damage_track(dtrack_norail); + train.run(20.0); + REQUIRE(derailed(train[0].mover())); + auto const damage{damage_of(train)}; + INFO(damage.list); + MESSAGE(std::format("{}: crush {:.3f} m, {:.0f} kJ of the {:.0f} kJ of the train", pushed ? "pushed" : "pulled", damage.crush, damage.energy / 1000.0, kinetic / 1000.0)); + CHECK(damage.crush < cl::crush_mark); + CHECK(damage.energy <= kinetic); + CHECK(damage.derailed == 0); + CHECK(damage.broken == 0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK_FALSE(derailed(train[i].mover())); + } + } + } +} + +TEST_CASE("collisions: the buffers of vehicles found inside each other take in nothing for the budget of the crush") { + cl::contact_energy contact; + // pressed in at 2 m/s under 1 MN for 0.1 s: 200 kJ, past the 120 kJ the buffers of both ends take + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + REQUIRE(contact.absorbed() == doctest::Approx(200.0e3)); + CHECK(contact.budget(11.0e3, 1.7, 120.0e3) > 0.0); + // found inside each other: what their springs made of it is no hit (l053_calkowo-sluzba-tlk-1: 163 kJ "in the + // buffers" let a pair crush with 15 kJ of motion) + contact.inside(); + CHECK(contact.absorbed() == 0.0); + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + CHECK(contact.absorbed() == 0.0); + CHECK(contact.budget(11.0e3, 1.7, 120.0e3) < 0.0); + // the buffers apart, the next contact is a hit again + contact.update(false, false, 0.0, 0.0, 0.0, 0.01); + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + CHECK(contact.absorbed() == doctest::Approx(200.0e3)); +} + +TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l053_calkowo-sluzba-tlk-1, linia61_osobowy3)") { + // the log had "closing at -7.1 km/h at the start of the step" on a crush of a pair knocked back onto each other in + // the step: the legacy collision takes such a knock, a pair still closing in at the start of a step is a hit + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const parting : {true, false}) { + CAPTURE(parting); + consist train; + auto &front{train.add(definition::fiz("430w_v2/430w"))}; + // behind it with the buffers pressed to their stop, moving back away from it, or standing + auto &back{train.add(definition::fiz("430w_v2/430w"), 0, coupling::faux, parting ? -3.0 : 0.0, -0.3)}; + // one step, the way the consist steps it, with the vehicle behind knocked forwards onto the front one between + // the forces and the movement, as a hit of another vehicle in the step does + constexpr double dt{0.01}; + for (auto *vehicle : {&front, &back}) { + vehicle->begin_step(); + } + for (auto *vehicle : {&front, &back}) { + vehicle->forces(dt); + } + REQUIRE((front->Couplers[end::rear].closing < 0.0) == parting); + back->V = 25.0 * kmh; + for (auto *vehicle : {&front, &back}) { + vehicle->move({}, dt, (*vehicle)->Loc, 5.0); + } + auto const crush{front->Couplers[end::rear].crush + back->Couplers[end::front].crush}; + if (parting) { + CHECK(crush == 0.0); + // the legacy collision pushed them apart + CHECK(back->V < 25.0 * kmh); + } + else { + // closing in from a stand, the knock is a hit past the energy of the buffers + CHECK(crush > 0.0); + } + } +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 61609d3ba..8872c6a6e 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -195,6 +195,7 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { double vehicle::fast_move(track const &Track, double Dt, TLocation const &Location) { // TDynamicObject::FastUpdate(), the iterations of a frame before the last one auto param{parameters_of(Track, *m_mover)}; + param.DamageFlag = m_trackdamage; return m_mover->FastComputeMovement(Dt, shape_of(Track), param, Location, TRotation{0.0, 0.0, 0.0}); } @@ -217,7 +218,8 @@ void vehicle::forces(double Dt) { double vehicle::move(track const &Track, double Dt, TLocation const &Location, double Trainpipe) { auto const shape{shape_of(Track)}; - auto const param{parameters_of(Track, *m_mover)}; + auto param{parameters_of(Track, *m_mover)}; + param.DamageFlag = m_trackdamage; TRotation const rotation{0.0, 0.0, 0.0}; // what TDynamicObject::Update() does before the movement. a raised pantograph touches the wire at once, diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index 1e7db3599..05c03dbf6 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -92,6 +92,9 @@ public: // keeps the main reservoir at the given pressure [bar], as a running compressor or a coupled vehicle // feeding it would; a negative value leaves it alone void hold_main_reservoir(double Pressure) { m_reservoirpressure = Pressure; } + // the track under this vehicle alone has the damage flags (dtrack_*) from now on: dtrack_norail runs it off the + // end of the track in its next step, as the legacy derailment has it + void damage_track(int Flags) { m_trackdamage = Flags; } // advances the physics by one frame of Track.iterations steps of Dt, the way the simulation loop does void step(track const &Track = {}, double Dt = 0.01); @@ -116,6 +119,7 @@ private: int m_cab{0}; double m_pipepressure{-1.0}; double m_reservoirpressure{-1.0}; + int m_trackdamage{0}; trace *m_trace{nullptr}; double m_time{0.0}; // of the simulation, since the vehicle got created };