From 4bd7565a81c15fea580bc614e6292dba8b296bec Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sat, 28 Nov 2026 06:44:54 +0100 Subject: [PATCH 01/20] fix: read the WiperList wiper mask as a number, not a character byteSum is a uint8_t, and cParser reads an unsigned char as one character of the token: "5" became 53, and "12" became '1' (49), wiper 0 alone instead of wipers 2 and 3. The single digits in the current data kept the right low bits by chance. Read it as an int, clamped to the byte's range. --- McZapkie/Mover.cpp | 5 +++- tests/unit/test_wipers.cpp | 50 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 tests/unit/test_wipers.cpp diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 7ee85203a..154284413 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -11925,7 +11925,10 @@ bool TMoverParameters::readWiperList(std::string const &line) WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); return false; } - parser >> WiperList[idx].byteSum >> WiperList[idx].WiperSpeed >> WiperList[idx].interval >> WiperList[idx].outBackDelay; + // the mask of the wipers is a number: read into the uint8_t directly, the parser would take only its first character + int bytesum{0}; + parser >> bytesum >> WiperList[idx].WiperSpeed >> WiperList[idx].interval >> WiperList[idx].outBackDelay; + WiperList[idx].byteSum = static_cast(std::clamp(bytesum, 0, 255)); return true; } diff --git a/tests/unit/test_wipers.cpp b/tests/unit/test_wipers.cpp new file mode 100644 index 000000000..cc6c7042e --- /dev/null +++ b/tests/unit/test_wipers.cpp @@ -0,0 +1,50 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +using test::definition; +using test::vehicle; + +// the first number of a WiperList row is the mask of the wipers working in that position of the wiper switch, +// bit n for the wiper n. it's a number: read as a character "5" was 53 and "12" was '1', the wiper 0 alone + +namespace { + +definition wiper_list(nlohmann::ordered_json const &Rows) { + return definition::load("cab_vehicle") + .set("WiperList", "rows", Rows) + .set("WiperList", "Size", static_cast(Rows.size())) + .set("WiperList", "Angle", 58); +} + +} // namespace + +TEST_CASE("wipers: the mask of the wipers of a WiperList row is read as a number") { + vehicle cab{wiper_list(nlohmann::ordered_json::array({ + {"0", "0.7", "0.0", "0.5"}, + {"5", "0.7", "7.0", "0.5"}, + {"12", "0.6", "0.7", "0.0"}, + {"15", "0.5", "0.5", "0.25"}, + }))}; + REQUIRE(cab->WiperListSize == 4); + + CHECK(cab->WiperList[0].byteSum == 0); + CHECK(cab->WiperList[1].byteSum == 5); + CHECK(cab->WiperList[2].byteSum == 12); + CHECK(cab->WiperList[3].byteSum == 15); + + // and the numbers after it still land in their own fields + CHECK(cab->WiperList[1].interval == doctest::Approx(7.0)); + CHECK(cab->WiperList[2].WiperSpeed == doctest::Approx(0.6)); + CHECK(cab->WiperList[3].outBackDelay == doctest::Approx(0.25)); +} + +TEST_CASE("wipers: a mask out of the range of a byte is clamped to it") { + vehicle cab{wiper_list(nlohmann::ordered_json::array({ + {"-1", "0.7", "0.0", "0.5"}, + {"300", "0.7", "0.0", "0.5"}, + }))}; + + CHECK(cab->WiperList[0].byteSum == 0); + CHECK(cab->WiperList[1].byteSum == 255); +} From d6dba363e326ecf64ca9a6bf93ec51442e52e996 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 29 Nov 2026 05:29:37 +0100 Subject: [PATCH 02/20] feat(derailment): a derailment is told to the scenery, the black box and the test mode Every way a vehicle leaves the rails records what derailed it and its speed in the mover (DerailedBy, DerailVelocity), by any physics.derailment model and the collisions. After all vehicles moved, TDynamicObject::new_derailment() notices each derailment once, and state_manager::report_derailment() tells: - the log: "derailment: derailed () on track at km/h"; - a scenery that asked for it: its memory cell __simulation.derailment gets " ", the speed and the code of the cause, then its events __simulation.derailment and :derailed run with the vehicle as activator. Nothing is made at the start, so a scenery without them runs as before (no draw of the random numbers for a new node); - the black box: a derailment record with the new phase 2, for any model, and every derailment record gets the finer cause and the track at its end; - the test mode: test.fail_on_derailment yes (default no) ends the run of a tested train that derailed with the new result derailment, exit code 15; otherwise the verdict line ends with " [derailed: ...]". run.py knows exit code 15 and shows the derailment of the train under test in the summary. New cases eu07_td_buckle_derails_ends_test and eu07_td_off_track_end_scenery_told; the other 83 end as before and their physics logs are byte-identical to staging. --- McZapkie/MOVER.h | 6 ++ McZapkie/Mover.cpp | 21 +++++++ McZapkie/derailment.cpp | 29 ++++++++++ McZapkie/derailment.h | 38 +++++++++++++ blackbox_doc.md | 18 ++++-- docs/behaviour-changes.md | 11 ++++ simulation/blackboxrecorder.cpp | 57 +++++++++++++++++++ simulation/blackboxrecorder.h | 9 +++ simulation/simulation.cpp | 22 +++++++ simulation/simulation.h | 9 +++ simulation/simulationtest.cpp | 53 +++++++++++++++-- simulation/simulationtest.h | 9 +++ simulation/simulationtestrules.cpp | 20 +++++++ simulation/simulationtestrules.h | 13 +++++ tests/scenarios/README.md | 52 ++++++++++++++++- .../eu07_td_buckle_derails_ends_test.json | 38 +++++++++++++ .../eu07_td_off_track_end_scenery_told.json | 55 ++++++++++++++++++ tests/scenarios/run.py | 31 +++++++++- tests/unit/test_blackbox.cpp | 35 ++++++++++++ tests/unit/test_derailment.cpp | 41 +++++++++++++ tests/unit/test_test_mode.cpp | 53 ++++++++++++++++- utilities/Globals.cpp | 7 +++ utilities/Globals.h | 1 + vehicle/DynObj.cpp | 37 ++++++++++++ vehicle/DynObj.h | 9 +++ vehicle/blackbox.cpp | 2 + vehicle/blackbox.h | 3 + 27 files changed, 666 insertions(+), 13 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_buckle_derails_ends_test.json create mode 100644 tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index d5847cbc1..a5ff758a5 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2594,6 +2594,12 @@ class TMoverParameters // 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}; + // what derailed the vehicle, by any model, and its speed then [km/h], for what the scenery and the test mode are + // told (TDynamicObject::new_derailment()); none on the rails, and other when only the flag of the damage was set + derailment::reason DerailedBy{derailment::reason::none}; + double DerailVelocity{0.0}; + // the vehicle derails now, by the Reason, at the speed it has + void note_derailment(derailment::reason Reason); // physics.derailment new: how the vehicle left the rails, for the way it leaves the track (vehicle/derailmotion.h): // what derailed it, the lateral acceleration of its body out of the curve then [m/s2] (negative into the curve, where a // buckle bends the line the other way), and the side it was pulled off to by a coupling (1 the left of its front, -1 diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 7ee85203a..a48b05366 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1626,6 +1626,7 @@ void TMoverParameters::derail_in_collision(DerailReason const Reason, std::strin DerailAcceleration = 0.0; DerailSide = 0; CollisionDerail = Reason; + note_derailment(Reason == COLLISION_OVERRIDE ? derailment::reason::overriding : derailment::reason::pushed_off); EventFlag = true; MainSwitch(false, range_t::local); if (Vel < 5.0) @@ -2100,6 +2101,10 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve } Derailed = Verdict.result; DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; + // a buckle under it is what derailed it, whichever way it went + note_derailment(Track.buckle_curvature != 0.0 ? derailment::reason::buckle : + Verdict.result == derailment::outcome::overturned ? derailment::reason::overturned : + derailment::reason::flange_climb); // out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve DerailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration; DerailSide = 0; @@ -2119,6 +2124,8 @@ void TMoverParameters::rerail() { ClearFlag(DamageFlag, dtrain_out); Derailed = derailment::outcome::none; + DerailedBy = derailment::reason::none; + DerailVelocity = 0.0; // and back on the track; what derailed it before has no say in how it leaves the track the next time OffTrack.reset(); DerailCause = derail_motion::cause::off_rails; @@ -2161,6 +2168,13 @@ void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) { + note_derailment(Reason == END_OF_TRACK ? derailment::reason::end_of_track : + Reason == TOO_HIGH_SPEED ? derailment::reason::overspeed : + Reason == GAUGE_MISMATCH ? derailment::reason::track_gauge : + Reason == WRONG_TRACK_TYPE ? derailment::reason::track_type : + Reason == COLLISION ? derailment::reason::collision : + Reason == TRAILED_SWITCH ? derailment::reason::trailed_switch : + derailment::reason::other); EventFlag = true; MainSwitch(false, range_t::local); @@ -2208,6 +2222,12 @@ void TMoverParameters::Derail(DerailReason const Reason) } } +void TMoverParameters::note_derailment(derailment::reason const Reason) +{ + DerailedBy = Reason; + DerailVelocity = std::abs(V) * 3.6; +} + bool TMoverParameters::leaves_track() const { return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none && @@ -2225,6 +2245,7 @@ void TMoverParameters::pull_off(int const Side, double const Acceleration, std:: DerailCause = derail_motion::cause::pulled_off; DerailAcceleration = Acceleration; DerailSide = Side; + note_derailment(derailment::reason::pulled_off); EventFlag = true; MainSwitch(false, range_t::local); tear_brake_hoses(*this); diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index e9cfa452e..5f7e346a8 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -282,4 +282,33 @@ std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_s Vehicle.ends[0].compression / 1000.0, Vehicle.ends[1].compression / 1000.0, Track.damage, Track.uneven_cross); } +std::string_view reason_name(reason const Reason) { + switch (Reason) { + case reason::none: return "none"; + case reason::flange_climb: return "flange_climb"; + case reason::overturned: return "overturned"; + case reason::end_of_track: return "end_of_track"; + case reason::pulled_off: return "pulled_off"; + case reason::collision: return "collision"; + case reason::buckle: return "buckle"; + case reason::overriding: return "overriding"; + case reason::pushed_off: return "pushed_off"; + case reason::overspeed: return "overspeed"; + case reason::track_gauge: return "track_gauge"; + case reason::track_type: return "track_type"; + case reason::trailed_switch: return "trailed_switch"; + case reason::other: return "other"; + } + return "other"; +} + +std::string cell_text(notice const &Notice) { + return std::format("{} {} {}", Notice.vehicle, reason_name(Notice.why), Notice.track.empty() ? std::string_view{"none"} : std::string_view{Notice.track}); +} + +std::string describe(notice const &Notice) { + return std::format("{} derailed ({}) {} at {:.0f} km/h", Notice.vehicle, reason_name(Notice.why), + Notice.track.empty() ? std::string{"on a track without a name"} : "on track " + Notice.track, std::abs(Notice.velocity)); +} + } // namespace derailment diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 50a3d84cb..720b7ea88 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 #include @@ -226,4 +227,41 @@ std::optional climbing_speed(vehicle_state const &Vehicle, track_state c // 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); +// ---- what the scenery and the test mode are told + +// what put a vehicle off the rails, by any model of the derailment (physics.derailment new, monitor or old) and of the +// collisions. the codes are public: the memory cell __simulation.derailment holds them in its value 2, and the black +// box in its derailment records (blackbox_doc.md); 1 to 5 are the causes of the motion off the track +enum class reason : std::uint8_t { + none = 0, + flange_climb = 1, // the flange climbed the rail (new) + overturned = 2, // it overturned in a curve (new) + end_of_track = 3, // it ran off the end of the track + pulled_off = 4, // the coupling of a vehicle off the track pulled it off (new) + collision = 5, // the legacy derailment in a collision + buckle = 6, // it left the rails on a buckled track (new) + overriding = 7, // it climbed onto the vehicle it hit (physics.collisions new) + pushed_off = 8, // the force pressing its ends pushed it off the track (physics.collisions new) + overspeed = 9, // the legacy draw: too fast in a curve (old, monitor) + track_gauge = 10, // the gauge of the track doesn't fit the vehicle + track_type = 11, // a track of another kind than the vehicle + trailed_switch = 12, // it trailed through a switch with a movable nose set the other way + other = 13 // something else derailed it: a SetDamage command of a scenery +}; +// the name of the cause in the log and the memory cell, e.g. "end_of_track" +std::string_view reason_name(reason Reason); + +// a vehicle derailed: what the scenery (the memory cell and the events of __simulation.derailment) and the test mode +// are told, once each time it leaves the rails +struct notice { + std::string vehicle; // name of the vehicle + reason why{reason::other}; + std::string track; // name of the track it derailed on, empty for a track without one + double velocity{0.0}; // [km/h] as it derailed +}; +// the text of the memory cell __simulation.derailment: " ", "none" for a track without a name +std::string cell_text(notice const &Notice); +// for the log and the verdict of a test: " derailed () on track at km/h" +std::string describe(notice const &Notice); + } // namespace derailment diff --git a/blackbox_doc.md b/blackbox_doc.md index ce2108484..c89823ee0 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -552,15 +552,18 @@ undone in shunting (between the cars of a unit). ### 0x38 derailment -A vehicle off the track, with `physics.derailment new` in `eu07.ini`: it doesn't follow the track any more -and moves on the ground by itself until it stops. Written when it leaves the track, and when it comes to -rest off it, looked at every second. A vehicle put back on the rails and derailed again is written again. +A vehicle derails, with any `physics.derailment` in `eu07.ini`: written as it happens (phase 2), with what +derailed it and the track (one that derailed before the recording started, in the first frame, at the first look). With `physics.derailment new` the vehicle then leaves the track, doesn't follow it +any more and moves on the ground by itself until it stops: written when it leaves the track (phase 0), and +when it comes to rest off it (phase 1), looked at every second. A vehicle put back on the rails and derailed +again is written again. In phase 2 the fields of the motion on the ground are those of the vehicle on the +track: no offset, no roll, nothing travelled. | type | field | |---------|--------------------------------------------------------------------------------| | `f64` | t | | `u32` | number of the vehicle | -| `u8` | 0 it left the track, 1 it came to rest off it | +| `u8` | 0 it left the track, 1 it came to rest off it, 2 it derailed | | `u8` | what derailed it: 1 the flange climbed the rail, 2 it overturned in a curve, 3 the end of the track, 4 a coupling of a vehicle off the track pulled it off, 5 a collision | | `dvec3` | position of the vehicle | | `f32` | heading [rad] of its front, from +z towards +x | @@ -569,6 +572,13 @@ rest off it, looked at every second. A vehicle put back on the rails and deraile | `f32` | roll [rad] of its body, to the left positive: about 1.57 on its side | | `f32` | distance [m] it went on the ground since it left the rails | | `u8` | 1 lying on its side, 0 upright | +| `u8` | what derailed it, finer: the code of the cause of the memory cell `__simulation.derailment` (tests/scenarios/README.md): 1 the flange climbed, 2 overturned, 3 the end of the track, 4 pulled off, 5 a collision (the legacy model), 6 a buckle, 7 overriding, 8 pushed off, 9 too fast in a curve (the legacy draw), 10 the gauge, 11 a track of another kind, 12 a trailed switch, 13 something else. In phases 0 and 1 too | +| `str` | name of the track it derailed on, empty for a track without a name | + +The last two came later: a reader of an older file finds the record shorter. The finer cause is 0 when the +simulator didn't know it yet. The cause before them stays one of 1-5, the closest one: a buckle 1 or 2, the +way the vehicle went; overriding and pushing off 5; a trailed switch, the legacy draw in a curve, the gauge, +the kind of track and something else 1. ### 0x3F end diff --git a/docs/behaviour-changes.md b/docs/behaviour-changes.md index 069bb6e90..9877fb50e 100644 --- a/docs/behaviour-changes.md +++ b/docs/behaviour-changes.md @@ -42,6 +42,13 @@ existing data. - **Test mode** (#266, `--test`; see `tests/scenarios/README.md`): takes no input from outside, does not read the player's own eu07.ini, writes only its verdict to the standard output, and has exit codes of its own (kept clear of 1 and 3). +- **A derailment is logged in one line of its own** (derailment event PR): `derailment: derailed () on + track at km/h`, once each time a vehicle leaves the rails, with any `physics.derailment`, next to the + `Bad driving` lines that were there before. The black box writes it too, as a derailment record (0x38) with phase 2, + and every derailment record gets the finer cause and the track name at its end (see `blackbox_doc.md`). Notices: log + checks that count lines with "derailed"; readers of the black box that took every 0x38 record for one off the track. + The settings dump at the start of log.txt has `test.fail_on_derailment` (default `no`); with `yes` a derailment of + a tested train ends a test run with the new exit code 15. Needs: nothing. ## AI @@ -114,6 +121,10 @@ existing data. - **New putvalues commands** for sceneries: `Crew: ` puts an AI driver in a vehicle or takes it off (#422); `SignalAreaEnd` (#305, above); the parameter `H` after the coupling of a vehicle prepares it for hauling dead in a train, the "pullee mode" (#419). +- **A scenery can react to a derailment** (derailment event PR, optional): when it declares the memory cell + `__simulation.derailment`, the simulator writes the vehicle, the cause, the track, the speed and the code of the + cause into it on each derailment, then runs the event `__simulation.derailment` and the event `:derailed` + when the scenery has them. Nothing is made or run for a scenery without them. See `tests/scenarios/README.md`. ## Data keys that need new data diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index e4161ce61..307b9001a 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "input/command.h" +#include "McZapkie/derailment.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "vehicle/Train.h" @@ -575,14 +576,66 @@ std::uint8_t cause_of(derail_motion::cause const Cause) { } } +// the cause of the motion off the track closest to what derailed the vehicle: a buckle as the vehicle went +std::uint8_t cause_of(derailment::reason const Reason, derailment::outcome const Outcome) { + switch (Reason) { + case derailment::reason::overturned: + return blackbox::derailment_causes::overturned; + case derailment::reason::buckle: + return Outcome == derailment::outcome::overturned ? blackbox::derailment_causes::overturned : blackbox::derailment_causes::flange_climbed; + case derailment::reason::end_of_track: + return blackbox::derailment_causes::end_of_track; + case derailment::reason::pulled_off: + return blackbox::derailment_causes::pulled_off; + case derailment::reason::collision: + case derailment::reason::overriding: + case derailment::reason::pushed_off: + return blackbox::derailment_causes::collision; + default: + return blackbox::derailment_causes::flange_climbed; + } +} + } // namespace +void blackbox_recorder::derailed(TDynamicObject const *Vehicle, derailment::notice const &Notice) { + std::scoped_lock lock{m_mutex}; + // before the recording starts (a vehicle derailing in the first frame) the first look writes it + if (m_writer == nullptr || Vehicle == nullptr) + return; + write_derailed(Vehicle, Notice); +} + +void blackbox_recorder::write_derailed(TDynamicObject const *Vehicle, derailment::notice const &Notice) { + auto &entry{m_vehicles[Vehicle]}; + if (entry.derailed) + return; + entry.derailed = true; + blackbox::derailment_state state; + state.time = m_time; + state.vehicle = vehicle_id(Vehicle); + state.phase = blackbox::derailment_phases::derailed; + state.cause = cause_of(Notice.why, Vehicle->MoverParameters->Derailed); + state.position = Vehicle->GetPosition(); + state.heading = static_cast(std::atan2(Vehicle->VectorFront().x, Vehicle->VectorFront().z)); + // as it derailed, along its front as it moves now + state.speed_kmh = static_cast(std::copysign(Notice.velocity, Vehicle->MoverParameters->V)); + state.reason = static_cast(Notice.why); + state.track = text_of(Notice.track); + m_writer->derailment(state); +} + void blackbox_recorder::look_at_derailments() { for (auto *vehicle : simulation::Vehicles.sequence()) { if (false == vehicle->bEnabled) continue; auto const &motion{vehicle->MoverParameters->OffTrack}; auto const id{vehicle_id(vehicle)}; + // the derailment itself first, if it came before the recording did; forgotten once back on the rails + if (auto const *notice{vehicle->derailment_notice()}) + write_derailed(vehicle, *notice); + else + m_vehicles[vehicle].derailed = false; auto &entry{m_vehicles[vehicle]}; if (false == motion.active()) { entry.derailment = 0; @@ -602,6 +655,10 @@ void blackbox_recorder::look_at_derailments() { state.roll = static_cast(motion.roll()); state.travelled = static_cast(motion.travelled()); state.lying = motion.lying(); + if (auto const *notice{vehicle->derailment_notice()}) { + state.reason = static_cast(notice->why); + state.track = text_of(notice->track); + } // seen first at rest, it left the track before for (auto written = entry.derailment + 1; written <= phase; ++written) { state.phase = (written == 1 ? blackbox::derailment_phases::left_track : blackbox::derailment_phases::at_rest); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index cdc61da61..568f1671d 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -24,6 +24,9 @@ http://mozilla.org/MPL/2.0/. #include class TDynamicObject; +namespace derailment { +struct notice; +} class TTrack; class TMemCell; class basic_event; @@ -49,6 +52,8 @@ public: // Event: the one telling the aspect of the signal void signal_passed(TDynamicObject const *Vehicle, basic_event const &Event, double Speed1, double Speed2, double Trainspeed, double Overrun, std::uint8_t Flags); void vehicle_removed(TDynamicObject const *Vehicle); + // the vehicle derailed, by any model: the derailment record as it happens + void derailed(TDynamicObject const *Vehicle, derailment::notice const &Notice); // a train at a station of its timetable; the time and the vehicle are filled in here void station(TDynamicObject const *Vehicle, blackbox::station_event Station); // a train told to sound the horn (W6), at Position @@ -71,6 +76,8 @@ private: bool couplers_known{false}; // off the track: 0 not, 1 written as leaving it, 2 written as at rest int derailment{0}; + // its derailment written (phase 2), while it's off the rails + bool derailed{false}; }; struct switch_entry { TTrack *track{nullptr}; @@ -103,6 +110,8 @@ private: void look_at_couplers(); // the vehicles leaving the track and coming to rest off it (physics.derailment new) void look_at_derailments(); + // the derailment record of the vehicle as it derailed (phase 2), once + void write_derailed(TDynamicObject const *Vehicle, derailment::notice const &Notice); void write_camera(); // the timetable of the train the user is in, written again when it is another one; none isn't written void look_at_timetable(TDynamicObject const &Vehicle, std::uint32_t Id); diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 2eb0a3c89..770a3553a 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -127,6 +127,28 @@ state_manager::init_scripting_interface() { simulation::test().init_result_cell(); } +void +state_manager::report_derailment( TDynamicObject const &Vehicle, derailment::notice const &Notice ) { + + WriteLog( "derailment: " + derailment::describe( Notice ) ); + auto const name { std::string( derailment_name ) }; + if( auto *cell { Memory.find( name ) } ) { + cell->UpdateValues( + derailment::cell_text( Notice ), + Notice.velocity, + static_cast( static_cast( Notice.why ) ), + basic_event::flags::text | basic_event::flags::value1 | basic_event::flags::value2 ); + } + if( auto *event { Events.FindEvent( name ) } ) { + Events.AddToQuery( event, &Vehicle ); + } + if( auto *event { Events.FindEvent( Vehicle.name() + ":derailed" ) } ) { + Events.AddToQuery( event, &Vehicle ); + } + Blackbox.derailed( &Vehicle, Notice ); + test().vehicle_derailed( Vehicle, Notice ); +} + // legacy method, calculates changes in simulation state over specified time void state_manager::update( double const Deltatime, int Iterationcount ) { diff --git a/simulation/simulation.h b/simulation/simulation.h index 02bef0ffd..9bf9cd057 100644 --- a/simulation/simulation.h +++ b/simulation/simulation.h @@ -72,6 +72,15 @@ public: // stores class data in specified file, in legacy (text) format void export_as_text( std::string const &Scenariofile ) const; + // the vehicle derailed: the log, the black box, the test mode, and the scenery which asked for it. the scenery's + // memory cell __simulation.derailment gets the notice (derailment::cell_text(), value 1 the speed [km/h], value 2 + // the code of the cause), then its events __simulation.derailment and :derailed run, the vehicle their + // activator. a scenery declares those it wants: nothing is made at the start, where a node made would take a + // draw of the random numbers and change every run + void + report_derailment( TDynamicObject const &Vehicle, derailment::notice const &Notice ); + // name of the memory cell and of the event of a derailment of any vehicle + static constexpr std::string_view derailment_name { "__simulation.derailment" }; private: // members diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index f6e2a4a39..276596bbc 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtest.h" #include "application/application.h" +#include "McZapkie/derailment.h" #include "scene/scene.h" #include "simulation/simulation.h" #include "utilities/Globals.h" @@ -49,6 +50,16 @@ double elapsed_wall_time() namespace simulation { +namespace { + +// the limits of the settings, as they are now: the scenery may change them +test_limits current_limits() +{ + return test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass, Global.test.fail_on_derailment }; +} + +} // namespace + test_manager &test() { static test_manager instance; @@ -141,11 +152,12 @@ void test_manager::start() tested += " " + name; } auto const walllimit { m_walllimit.load() }; - WriteLog(std::format("test: started, testing {}, timeout {:.0f} s, real time limit {}, standstill {:.0f} s{}{}{}", tested, Global.test.timeout, + WriteLog(std::format("test: started, testing {}, timeout {:.0f} s, real time limit {}, standstill {:.0f} s{}{}{}{}", tested, Global.test.timeout, walllimit > 0.0 ? std::format("{:.0f} s", walllimit) : std::string("none"), Global.test.standstill, Global.test.pass_on_standstill ? ", standstill passes" : "", Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed", - Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop")); + Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop", + Global.test.fail_on_derailment ? ", a derailment fails" : "")); } void test_manager::update(double const Deltatime) @@ -160,7 +172,7 @@ void test_manager::update(double const Deltatime) frame.reason = cell->Text(); } - auto const limits { test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass } }; + auto const limits { current_limits() }; std::optional verdict; auto passrequested { false }; { @@ -192,6 +204,38 @@ bool test_manager::tested_trains_at_rest() const }); } +bool test_manager::tested(TDynamicObject const &Vehicle) const +{ + if (Global.test.vehicles.empty()) + return true; + return std::ranges::any_of(Global.test.vehicles, [&Vehicle](std::string const &Name) { + auto *vehicle { simulation::Vehicles.find(Name) }; + return vehicle != nullptr && vehicle->find_vehicle(coupling::coupler, [&Vehicle](TDynamicObject const *Other) { return Other == &Vehicle; }) != nullptr; + }); +} + +void test_manager::vehicle_derailed(TDynamicObject const &Vehicle, derailment::notice const &Notice) +{ + if (false == Global.test.enabled || false == m_started || m_finished) + return; + auto const istested { tested(Vehicle) }; + auto const description { derailment::describe(Notice) }; + std::optional verdict; + double time { 0.0 }; + { + std::scoped_lock lock { m_lock }; + verdict = evaluate_derailment(m_progress, istested, description, current_limits()); + time = m_progress.time; + } + if (verdict.has_value()) + { + finish(verdict->result, verdict->reason); + return; + } + if (istested) + WriteLog(std::format("test: {} at {:.1f} s, allowed by test.fail_on_derailment", description, time)); +} + void test_manager::signal_passed_at_danger(std::string_view const Vehicle, std::string_view const Signal) { auto const reason { std::format("{} passed signal {} at danger", Vehicle, Signal) }; @@ -222,7 +266,8 @@ bool test_manager::conclude(test_result const Result, std::string_view const Rea m_result = Result; m_finished = true; - auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_progress.time, Reason) }; + auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast(Result), m_progress.time, + verdict_reason(test_verdict { Result, std::string(Reason) }, m_progress)) }; if (Result == test_result::pass) WriteLog(line); else diff --git a/simulation/simulationtest.h b/simulation/simulationtest.h index 784cd39e8..cf03d1287 100644 --- a/simulation/simulationtest.h +++ b/simulation/simulationtest.h @@ -11,6 +11,11 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtestrules.h" +class TDynamicObject; +namespace derailment { +struct notice; +} + #include #include #include @@ -36,6 +41,8 @@ public: void update(double Deltatime); // reported by a driver whose train went past a signal showing stop void signal_passed_at_danger(std::string_view Vehicle, std::string_view Signal); + // the vehicle derailed: a vehicle of the tested trains ends the test with test.fail_on_derailment + void vehicle_derailed(TDynamicObject const &Vehicle, derailment::notice const &Notice); // ends the test with given result and closes the application; the first call wins void finish(test_result Result, std::string_view Reason); // ends the test with given result, without closing the application: for the ways out that close it anyway @@ -54,6 +61,8 @@ private: void check_wall_clock(double Elapsed); // every vehicle of the tested trains stands: the consists of test.vehicle, or every vehicle without it bool tested_trains_at_rest() const; + // the vehicle is one of the tested trains: in a consist of test.vehicle as it is now, any vehicle without it + bool tested(TDynamicObject const &Vehicle) const; // the watchdog may end the test from its own thread mutable std::mutex m_lock; diff --git a/simulation/simulationtestrules.cpp b/simulation/simulationtestrules.cpp index fcedaed7d..6635d0808 100644 --- a/simulation/simulationtestrules.cpp +++ b/simulation/simulationtestrules.cpp @@ -58,6 +58,7 @@ std::string_view to_string(test_result const Result) case timeout: return "timeout"; case standstill: return "standstill"; case error: return "error"; + case derailment: return "derailment"; } return "unknown"; } @@ -159,4 +160,23 @@ std::optional evaluate_frame(test_progress &Progress, test_frame c return std::nullopt; } +std::optional evaluate_derailment(test_progress &Progress, bool const Tested, std::string_view const Description, test_limits const &Limits) +{ + if (false == Tested) + return std::nullopt; + if (Limits.fail_on_derailment) + return test_verdict{test_result::derailment, std::string(Description)}; + if (Progress.derailments++ == 0) + Progress.firstderailment = Description; + return std::nullopt; +} + +std::string verdict_reason(test_verdict const &Verdict, test_progress const &Progress) +{ + if (Verdict.result == test_result::derailment || Progress.derailments <= 0) + return Verdict.reason; + return std::format("{} [derailed: {}{}]", Verdict.reason, Progress.firstderailment, + Progress.derailments > 1 ? std::format(", and {} more", Progress.derailments - 1) : std::string()); +} + } // namespace simulation diff --git a/simulation/simulationtestrules.h b/simulation/simulationtestrules.h index 684b90cde..469eae29e 100644 --- a/simulation/simulationtestrules.h +++ b/simulation/simulationtestrules.h @@ -29,6 +29,7 @@ enum class test_result : int { timeout = 12, // test.timeout seconds of simulation time, or test.wall_timeout seconds of real time went by standstill = 13, // the tested trains stood still for test.standstill seconds without a result error = 14, // the run could not start (a bad command line, the scenery failed to load) or the simulator threw + derailment = 15, // a vehicle of the tested trains derailed, with test.fail_on_derailment }; std::string_view to_string(test_result Result); @@ -72,6 +73,7 @@ struct test_limits { double standstill{300.0}; // [s] of the tested trains standing without a result; 0 = never bool pass_on_standstill{false}; bool no_movement_before_pass{true}; + bool fail_on_derailment{false}; }; // what a frame of the simulation brought @@ -87,6 +89,8 @@ struct test_progress { double time{0.0}; // simulation time since the start [s] double resttime{0.0}; // how long the tested trains have been standing [s] bool passrequested{false}; // __test.result was set to 1, the pass waits for the tested trains to stop + int derailments{0}; // of the vehicles of the tested trains, the test going on + std::string firstderailment; // the first of them, as derailment::describe() tells it }; // how long the tested trains have to stand before a requested pass is granted [s] @@ -95,4 +99,13 @@ inline constexpr double pass_settle_time{1.0}; // checks the end conditions after a frame and moves the progress on. returns the verdict once the test is over std::optional evaluate_frame(test_progress &Progress, test_frame const &Frame, test_limits const &Limits); +// a vehicle derailed, as Description tells it (" derailed () on track at km/h"). one of +// the tested trains (Tested) ends the test with test.fail_on_derailment; without it the test goes on, and the +// derailment is kept for the verdict. another train doesn't count +std::optional evaluate_derailment(test_progress &Progress, bool Tested, std::string_view Description, test_limits const &Limits); + +// the reason the verdict line gives: that of the verdict, and when the test went on after a tested train derailed +// " [derailed: ]" (", and N more" inside the brackets for more of them) at its end +std::string verdict_reason(test_verdict const &Verdict, test_progress const &Progress); + } // namespace simulation diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 529fefea6..757757659 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -77,6 +77,7 @@ The test ends with the first of these: | 12 | timeout | `test.timeout` seconds of simulation time went by (default 3600), or `test.wall_timeout` seconds of real time since the start (see below) | | 13 | standstill | the tested trains stood still for `test.standstill` seconds (default 300) and nothing reported a result. Trains waiting at a station or for a signal count as standing, so the limit has to be longer than such waits | | 14 | error | the run could not start: no `-s`, the scenery failed to load or has no vehicles, or the simulator threw | +| 15 | derailment | a vehicle of the tested trains derailed, with `test.fail_on_derailment yes` (default `no`); ends at once. The reason tells the vehicle, the cause, the track and the speed: `autotest_x derailed (buckle) on track tdo_n222 at 46 km/h` | A crash ends with the system's code instead (on Windows e.g. `0xC0000005`, -1073741819). The codes of the test mode keep clear of the ones a process gets when it goes wrong on its own: 1 @@ -93,6 +94,7 @@ test.standstill 120 test.pass_on_standstill no test.fail_if_stop_overran yes test.no_movement_before_pass yes +test.fail_on_derailment no test.vehicle ep07-424 endconfig ``` @@ -105,6 +107,7 @@ endconfig | `test.pass_on_standstill` | no | the standstill end passes the test instead | | `test.fail_if_stop_overran` | yes | a signal passed at danger ends the test; with `no` it's only logged | | `test.no_movement_before_pass` | yes | a pass waits until the tested trains stand still; with `no` it ends the test at once | +| `test.fail_on_derailment` | no | a derailment of a vehicle of the tested trains ends the test with `derailment` (15). With `no` it's only logged (`test: ... derailed ..., allowed by test.fail_on_derailment`), and the verdict of the run, whatever it is, ends with ` [derailed: ]` (and how many more). Off by default: the cases that derail on purpose check what the derailed vehicles did afterwards | | `test.vehicle` | none | a vehicle of a train under test, by its name in the scenery (once for each train under test). The tested trains are the consists of these vehicles as they are at the moment (a train the tested one couples to joins it), and only they count for the pass and the standstill: other trains, AI traffic, may run on. A name the scenery doesn't have ends the test with `error`. Not given, every vehicle of the scenery counts. A signal passed at danger counts for every train either way | `--test-timeout` and `--test-wall-timeout` on the command line win over `test.timeout` and @@ -118,6 +121,47 @@ fast as real time is never cut short by it. With `test.timeout 0` there is no wa `test.wall_timeout` is given; `test.wall_timeout 0` turns it off. A test that has ended but whose simulator doesn't close is ended by the watchdog too, with its own result. +### A derailment, for the scenery + +Every derailment, whatever the model (`physics.derailment new`: overturning, the flange climbing the rail, a buckle, +a coupling pulling a vehicle off, the end of the track, a collision; `old` and `monitor`: the legacy draw in a curve, +the end of the track, the gauge, a collision, a trailed switch with a movable nose), goes to the log as +`derailment: derailed () on track at km/h`, once for each time a vehicle leaves the +rails, and to the black box (record 0x38, phase 2, see `blackbox_doc.md`). A scenery that wants to react declares what +it needs, nothing is made for it otherwise: + +``` +node -1 0 __simulation.derailment memcell 0 0 0 none 0 0 none endmemcell +event __simulation.derailment multiple 0 none stop_the_line endevent +event ep07-424:derailed UpdateValues 0 __test.result derailed 0 * endevent +``` + +- the memory cell `__simulation.derailment` gets, before the events run: the text ` ` + (`none` for a track without a name), value 1 the speed [km/h] as it derailed (in a collision: after the hit), value 2 the code of the cause. + A `memcompare` can test the vehicle by the start of the text (`ep07-424*`) and the cause by value 2; +- the event `__simulation.derailment` runs for a derailment of any vehicle, `:derailed` for that vehicle + (like `:busy`); the vehicle is their activator (`whois`). Two vehicles derailing in the same frame run + the first one once, the cell holds the second. + +| code | cause | | +| --- | --- | --- | +| 1 | `flange_climb` | the flange climbed the rail (`new`) | +| 2 | `overturned` | it overturned in a curve (`new`) | +| 3 | `end_of_track` | it ran off the end of the track | +| 4 | `pulled_off` | the coupling of a vehicle off the track pulled it off (`new`) | +| 5 | `collision` | the legacy derailment in a collision | +| 6 | `buckle` | it left the rails on a buckled track (`new`) | +| 7 | `overriding` | it climbed onto the vehicle it hit (`physics.collisions new`) | +| 8 | `pushed_off` | the force pressing its ends pushed it off the track (`physics.collisions new`) | +| 9 | `overspeed` | the legacy draw: too fast in a curve (`old`, `monitor`) | +| 10 | `track_gauge` | the gauge of the track doesn't fit | +| 11 | `track_type` | a track of another kind (a road vehicle on rails, say) | +| 12 | `trailed_switch` | it trailed through a switch with a movable nose set the other way | +| 13 | `other` | something else set the derailment (a `SetDamage` command) | + +The memory cell isn't made by the simulator because a node made at the start would take the random numbers of the +scene and change every run of a scenery. `eu07_td_off_track_end_scenery_told` is an example. + A signal is passed at danger when the head of a train goes past a signal which its driver has in its speed table, showing stop. So it's the driver's view that counts: a train without a driver isn't watched, and neither is a signal the driver never scanned (a train placed at @@ -240,7 +284,7 @@ to `logs/`. | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | | `timetable` | a timetable file in `cases/` for a trainset of the fragment, for a train whose timetable no scenery of the game has: copied to the game's `scenery/` dir as `autotest_.txt` for the run and removed after it; the fragment names it `{{timetable}}` | | `vehicle_variants` | vehicles of the case's own, made from those of the game, e.g. with a `.fiz` key the game's data doesn't have yet: a list of `{ "name": ..., "from": "/", "replace": [[old, new], ...] }`. For the run the vehicle's `.fiz`, with the literal replacements (an `old` it doesn't have is an error), and its `.mmd` are copied beside it in the game's `dynamic/` dir as `autotest__` and removed after it; the fragment names the type `{{variant_}}`, e.g. `dynamic pkp/et42_v2 112e-014-a {{variant_a}} ...`. The copy of the `.mmd` has the name of the vehicle it is made from in place of `(p2)`, the type name the simulator hands it, which some pass on to the include that names the model. An optional `"fiz_from": "/"` copies that file instead of the vehicle's own `.fiz`, named in full, e.g. `pkp/e6act_v2/e6acta.fiz.inc` for a vehicle whose `.fiz` only includes it (`e6actad.fiz`); the `.mmd` still comes from `from`. Keys for a section of the included file can't go after the include on a line of their own: a second `Power:` line loads the power source anew | -| `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` | +| `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill`, `error` or `derailment`, 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`) | | `timeout` | wall-clock seconds before giving up, loading included: the simulator's `--test-wall-timeout` (default 600) | | `fail_on_errors` | fail when `errors.txt` is not empty (default `false`) | @@ -395,6 +439,12 @@ on level ground, on an embankment 4 m high and in a cutting, made of triangle st centre (-600, 400), the cross section swept along it every 0.03 rad; the banks of the cutting rise 4 m at 1:1.5, then on at 1:5). +`eu07_td_off_track_end_scenery_told` is `eu07_td_off_track_end` with the memory cell and the events of a derailment +declared in `vars.track_nodes` (see *A derailment, for the scenery*): the event `:derailed` of the locomotive +checks the cell and marks a cell of the case, which the log shows. `eu07_td_buckle_derails_ends_test` is `eu07_td_buckle_derails` with +`test.fail_on_derailment yes`: the derailment of the EU07 under test ends the run with `derailment`. The runner's +summary tells the derailment of the train under test after the case, from the verdict line. + `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 diff --git a/tests/scenarios/cases/eu07_td_buckle_derails_ends_test.json b/tests/scenarios/cases/eu07_td_buckle_derails_ends_test.json new file mode 100644 index 000000000..f0eb5fd46 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_derails_ends_test.json @@ -0,0 +1,38 @@ +{ + "description": "eu07_td_buckle_derails with test.fail_on_derailment yes: the EU07 under test leaves the rails on the buckled curve tdo_n222 at the 46 km/h it has there, and the derailment ends the test at once with its own result (exit code 15) instead of the timeout, the verdict telling the vehicle, the cause (buckle), the track and the speed.", + "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", + "physics.derailment new" + ], + "test_config": [ + "test.fail_on_derailment yes" + ], + "expect": "derailment", + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "Bad driving: autotest_\\S+ derailed on buckled track" + }, + { + "type": "log_contains", + "pattern": "test: derailment \\(exit code 15\\) after [0-9.]+ s of simulation time: autotest_\\S+ derailed \\(buckle\\) on track tdo_n222 at [0-9]+ km/h" + }, + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "distance", + "max": 1100 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json b/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json new file mode 100644 index 000000000..58e804567 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json @@ -0,0 +1,55 @@ +{ + "description": "The scenery is told of a derailment: eu07_td_off_track_end (an EU07 with three coaches and no driver runs off the end of autotest_stub at 60 km/h) with the memory cell __simulation.derailment, the event of the same name (logvalues of the cell) and the event :derailed of the locomotive declared in the fragment. The cell holds the vehicle, the cause, the track and the speed and the code of the cause when the events run; the event of the locomotive checks the cell (its name, end of track: code 3) and marks a cell of the case. test.fail_on_derailment yes doesn't end the test: the derailed train isn't the one under test (the EU07 standing on track 1), so the run ends on the timeout as eu07_td_off_track_end does.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "autotest_stub", + "offset": "100", + "velocity": "60", + "track_nodes": "node -1 0 autotest_stub track normal 150.0 1.435 0.15 25.0 20 0 flat vis\n rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1\n-150.0 0.2 600.0 0.0 //point 1\n0.0 0.0 0.0 //control vector 1\n0.0 0.0 0.0 //control vector 2\n-150.0 0.2 750.0 0.0 //point 2\n0\nendtrack\nnode -1 0 __simulation.derailment memcell 0 0 0 none 0 0 none endmemcell\nnode -1 0 autotest_seen memcell 0 0 0 none 0 0 none endmemcell\nevent __simulation.derailment logvalues 0 __simulation.derailment endevent\nevent {{vehicle}}_off:derailed multiple 0 __simulation.derailment autotest_derail_seen autotest_derail_log condition memcompare {{vehicle}}_off* * 3 endevent\nevent autotest_derail_seen UpdateValues 0 autotest_seen end_of_track_seen 1 * endevent\nevent autotest_derail_log logvalues 0 autotest_seen endevent", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "test_config": [ + "test.fail_on_derailment yes" + ], + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off derailed \\(end_of_track\\) on track autotest_stub at [0-9]+ km/h" + }, + { + "type": "log_contains", + "pattern": "Memcell __simulation\\.derailment: \\[autotest_\\S+_off end_of_track autotest_stub\\] \\[(59|60)\\.[0-9]+\\] \\[3\\.00\\]" + }, + { + "type": "log_contains", + "pattern": "Memcell autotest_seen: \\[end_of_track_seen\\] \\[1\\.00\\]" + }, + { + "type": "log_lacks", + "pattern": "test: derailment" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "end of track", + "max_offset": 0.5, + "min_distance": 5, + "max_distance": 60, + "lying": false + } + ] +} diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index ad7ac5bcb..ecbafff5e 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -12,7 +12,8 @@ mode should end with, and checks on the vehicle's physics log. The runner: that turns on physicslog, 3. waits until the simulator quits by itself and reads the test result from its exit code: pass, fail, signal passed at danger, timeout (after `duration` seconds of - simulation, if the case gives one), standstill or error, + simulation, if the case gives one), standstill, error or derailment (with + test.fail_on_derailment), 4. compares the result with the one the case expects, evaluates the checks on the physicslog and prints PASS/FAIL per check. @@ -65,6 +66,7 @@ EXIT_RESULTS = { 12: "timeout", 13: "standstill", 14: "error", + 15: "derailment", } # the timeout of the simulator's real time watchdog (test.wall_timeout) has the timeout code too; told # apart by its verdict, so a run that hung doesn't pass a case that expects the simulation time to run out @@ -311,7 +313,7 @@ BLACKBOX_TRACK = 0x10 # the map: a rail track, or one way of a switch, as point BLACKBOX_VEHICLE = 0x12 # a vehicle: its number and its name BLACKBOX_VEHICLES = 0x21 # once a second: the vehicles which moved, changed speed or got another driver BLACKBOX_COUPLING = 0x37 # a coupler of a vehicle coupled, uncoupled, or its hoses and cables changed -BLACKBOX_DERAILMENT = 0x38 # a vehicle left the track, or came to rest off it (physics.derailment new) +BLACKBOX_DERAILMENT = 0x38 # a vehicle derailed (phase 2), left the track or came to rest off it (physics.derailment new) DERAILMENT_CAUSES = {1: "flange climbed", 2: "overturned", 3: "end of track", 4: "pulled off", 5: "collision"} COUPLING_COUPLER = 0x01 # of the bits telling what is coupled: the coupler itself BLACKBOX_DRIVERS = {"none": 0, "user": 1, "ai": 2} # the driver byte of a vehicle state @@ -1282,6 +1284,26 @@ def count_lines(path: Path) -> int: return 0 +# the simulator's verdict line: "test: (exit code N) after T s of simulation time: ", the reason +# of a derailment " derailed () on track at km/h"; a run that ended otherwise after a +# train under test derailed has " [derailed: ]" at its end (simulation/simulationtestrules.h) +VERDICT_REASON = re.compile(r"^test: .*? \(exit code \d+\) after [\d.]+ s of simulation time: (.*)$") +VERDICT_DERAILED = re.compile(r" \[derailed: (.*)\]$") + + +def derailment_note(verdict: str, exit_code: int | None) -> str: + """What the summary says of a derailment of a train under test, from the verdict line; empty for none.""" + if EXIT_RESULTS.get(exit_code) == "derailment": + reason = VERDICT_REASON.match(verdict) + return "derailment: " + (reason.group(1) if reason else verdict) + derailed = VERDICT_DERAILED.search(verdict) + return "derailed: " + derailed.group(1) if derailed else "" + + +# notes for the summary of the cases run, by name: a derailment of the train under test +NOTES: dict[str, str] = {} + + def describe_exit(code: int | None) -> str: if code is None: return "none, still running" @@ -1395,6 +1417,9 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float else: if result.verdict: say(f" {result.verdict}") + note = derailment_note(result.verdict, result.exit_code) + if note: + NOTES[name] = note got = EXIT_RESULTS.get(result.exit_code) if result.exit_code is not None else None if got == "timeout" and "of real time" in result.verdict: got = WALL_TIMEOUT @@ -1521,7 +1546,7 @@ def main() -> int: print(f"\n=== summary ({time.monotonic() - started:.0f}s)") for n in names: - print(f" {results[n]:5} {n}") + print(f" {results[n]:5} {n}" + (f" ({NOTES[n]})" if n in NOTES else "")) # 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 diff --git a/tests/unit/test_blackbox.cpp b/tests/unit/test_blackbox.cpp index 77e3e55f4..f952278bf 100644 --- a/tests/unit/test_blackbox.cpp +++ b/tests/unit/test_blackbox.cpp @@ -473,6 +473,41 @@ TEST_CASE("blackbox: a vehicle off the track is written field by field") { CHECK(derailment.get() == -1.5f); CHECK(derailment.get() == 87.5f); CHECK(derailment.get() == 1); + // added later, at the end: the finer cause and the track + CHECK(derailment.get() == 0); + CHECK(derailment.text() == ""); + CHECK(derailment.done()); +} + +TEST_CASE("blackbox: a derailment as it happens has the finer cause and the track at the end") { + std::ostringstream file; + blackbox::writer out{file}; + out.header(); + blackbox::derailment_state state; + state.time = 3.0; + state.vehicle = 2; + state.phase = blackbox::derailment_phases::derailed; + state.cause = blackbox::derailment_causes::flange_climbed; + state.speed_kmh = 46.0f; + state.reason = 6; // a buckle + state.track = "tdo_n222"; + out.derailment(state); + auto const all{records(file.str())}; + REQUIRE(all.size() == 1); + reader derailment{all[0].payload}; + CHECK(derailment.get() == 3.0); + CHECK(derailment.get() == 2); + CHECK(derailment.get() == 2); + CHECK(derailment.get() == 1); + for (int i = 0; i < 3; ++i) + derailment.get(); + derailment.get(); + CHECK(derailment.get() == 46.0f); + for (int i = 0; i < 3; ++i) // offset, roll, travelled + derailment.get(); + CHECK(derailment.get() == 0); // upright + CHECK(derailment.get() == 6); + CHECK(derailment.text() == "tdo_n222"); CHECK(derailment.done()); } diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 3afca6a26..13fac6ea4 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -343,3 +343,44 @@ TEST_CASE("derailment: the report of the log") { 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),")); } + +TEST_CASE("derailment: what the scenery and the test mode are told") { + SUBCASE("the codes of the causes are public, 1 to 5 those of the motion off the track") { + CHECK(static_cast(dr::reason::flange_climb) == 1); + CHECK(static_cast(dr::reason::overturned) == 2); + CHECK(static_cast(dr::reason::end_of_track) == 3); + CHECK(static_cast(dr::reason::pulled_off) == 4); + CHECK(static_cast(dr::reason::collision) == 5); + CHECK(static_cast(dr::reason::buckle) == 6); + CHECK(static_cast(dr::reason::overriding) == 7); + CHECK(static_cast(dr::reason::pushed_off) == 8); + CHECK(static_cast(dr::reason::overspeed) == 9); + CHECK(static_cast(dr::reason::track_gauge) == 10); + CHECK(static_cast(dr::reason::track_type) == 11); + CHECK(static_cast(dr::reason::trailed_switch) == 12); + CHECK(static_cast(dr::reason::other) == 13); + } + SUBCASE("each cause has a name of one word") { + for (int code = 0; code <= 13; ++code) { + auto const name{dr::reason_name(static_cast(code))}; + CAPTURE(code); + CHECK_FALSE(name.empty()); + CHECK(name.find(' ') == std::string_view::npos); + } + CHECK(dr::reason_name(dr::reason::end_of_track) == "end_of_track"); + CHECK(dr::reason_name(dr::reason::flange_climb) == "flange_climb"); + } + SUBCASE("the memory cell: the vehicle, the cause and the track, none for a track without a name") { + dr::notice notice{"ep07-424", dr::reason::overturned, "tdo_n222", 113.4}; + CHECK(dr::cell_text(notice) == "ep07-424 overturned tdo_n222"); + notice.track.clear(); + CHECK(dr::cell_text(notice) == "ep07-424 overturned none"); + } + SUBCASE("the log and the verdict of a test") { + dr::notice notice{"autotest_x", dr::reason::buckle, "tdo_n222", 46.4}; + CHECK(dr::describe(notice) == "autotest_x derailed (buckle) on track tdo_n222 at 46 km/h"); + notice.track.clear(); + notice.velocity = -12.6; + CHECK(dr::describe(notice) == "autotest_x derailed (buckle) on a track without a name at 13 km/h"); + } +} diff --git a/tests/unit/test_test_mode.cpp b/tests/unit/test_test_mode.cpp index eba641096..b96bd9137 100644 --- a/tests/unit/test_test_mode.cpp +++ b/tests/unit/test_test_mode.cpp @@ -43,7 +43,8 @@ std::optional run(simulation::test_progress &Progress, TEST_CASE("test mode: the exit codes keep clear of the ones of a killed or aborted process") { - std::array const results{test_result::pass, test_result::fail, test_result::signal_passed_at_danger, test_result::timeout, test_result::standstill, test_result::error}; + std::array const results{test_result::pass, test_result::fail, test_result::signal_passed_at_danger, test_result::timeout, test_result::standstill, test_result::error, + test_result::derailment}; for (auto const result : results) { auto const code{static_cast(result)}; @@ -60,6 +61,8 @@ TEST_CASE("test mode: the exit codes keep clear of the ones of a killed or abort CHECK(static_cast(test_result::timeout) == 12); CHECK(static_cast(test_result::standstill) == 13); CHECK(static_cast(test_result::error) == 14); + CHECK(static_cast(test_result::derailment) == 15); + CHECK(simulation::to_string(test_result::derailment) == "derailment"); } TEST_CASE("test mode: seconds on the command line are a number, not negative") @@ -266,3 +269,51 @@ TEST_CASE("test mode: what ended a run the simulator didn't end") CHECK(simulation::describe_exception(nullptr) == "the simulator was terminated"); } } + +TEST_CASE("test mode: a derailment") +{ + simulation::test_limits limits; + simulation::test_progress progress; + auto const first{"autotest_x derailed (buckle) on track tdo_n222 at 46 km/h"}; + auto const second{"autotest_x_w1 derailed (pulled_off) on track tdo_n222 at 31 km/h"}; + + SUBCASE("off by default: a tested train derailing doesn't end the test, the verdict tells it") + { + CHECK_FALSE(limits.fail_on_derailment); + CHECK_FALSE(simulation::evaluate_derailment(progress, true, first, limits).has_value()); + CHECK(progress.derailments == 1); + auto const verdict{run(progress, limits, 4000.0, frame(false))}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::timeout); + CHECK(simulation::verdict_reason(*verdict, progress) == "no result after 3600 s [derailed: autotest_x derailed (buckle) on track tdo_n222 at 46 km/h]"); + } + SUBCASE("the verdict counts the ones after the first") + { + simulation::evaluate_derailment(progress, true, first, limits); + simulation::evaluate_derailment(progress, true, second, limits); + simulation::evaluate_derailment(progress, true, second, limits); + CHECK(simulation::verdict_reason({test_result::pass, "__test.result set to 1 and the tested trains stopped"}, progress) == + "__test.result set to 1 and the tested trains stopped [derailed: autotest_x derailed (buckle) on track tdo_n222 at 46 km/h, and 2 more]"); + } + SUBCASE("test.fail_on_derailment ends the test at once, with the derailment as the reason") + { + limits.fail_on_derailment = true; + auto const verdict{simulation::evaluate_derailment(progress, true, first, limits)}; + REQUIRE(verdict.has_value()); + CHECK(verdict->result == test_result::derailment); + CHECK(verdict->reason == first); + CHECK(simulation::verdict_reason(*verdict, progress) == first); + } + SUBCASE("another train doesn't count, either way") + { + CHECK_FALSE(simulation::evaluate_derailment(progress, false, first, limits).has_value()); + limits.fail_on_derailment = true; + CHECK_FALSE(simulation::evaluate_derailment(progress, false, first, limits).has_value()); + CHECK(progress.derailments == 0); + CHECK(simulation::verdict_reason({test_result::timeout, "no result after 60 s"}, progress) == "no result after 60 s"); + } + SUBCASE("a verdict without a derailment keeps its reason") + { + CHECK(simulation::verdict_reason({test_result::fail, "__test.result set to 0"}, progress) == "__test.result set to 0"); + } +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a4d5f6669..3a9bbfca8 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -623,6 +623,12 @@ bool global_settings::ConfigParseTest(cParser& Parser, std::string_view const To return true; } + if (Token == "test.fail_on_derailment") + { + ParseOne(Parser, test.fail_on_derailment); + return true; + } + return false; } @@ -2733,6 +2739,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "test.pass_on_standstill", test.pass_on_standstill ); export_as_text( Output, "test.fail_if_stop_overran", test.fail_if_stop_overran ); export_as_text( Output, "test.no_movement_before_pass", test.no_movement_before_pass ); + export_as_text( Output, "test.fail_on_derailment", test.fail_on_derailment ); for( auto const &vehicle : test.vehicles ) { export_as_text( Output, "test.vehicle", vehicle ); } diff --git a/utilities/Globals.h b/utilities/Globals.h index 3364c49a0..b076d5ec4 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -106,6 +106,7 @@ struct global_settings { bool pass_on_standstill{ false }; // the standstill end passes the test instead of failing it bool fail_if_stop_overran{ true }; // a train passing a signal at stop ends the test as failed; with false it's only logged bool no_movement_before_pass{ true }; // a pass waits until the tested trains stand still; with false it ends the test at once + bool fail_on_derailment{ false }; // a derailment of a vehicle of the tested trains ends the test; with false it's only logged std::vector vehicles; // test.vehicle: the trains under test are the consists of these; none = every vehicle bool timeout_from_command_line{ false }; // --test-timeout given, the scenery doesn't override it std::optional wall_timeout; // [s] of real time since the start; none = test.timeout + time for the loading, 0 = no limit diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index fb28557a0..97585ec54 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3105,6 +3105,30 @@ double TDynamicObject::off_track_gap( int const End ) const { return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].vehicle_end ) ).gap; } +derailment::notice const *TDynamicObject::new_derailment() { + + if( false == TestFlag( MoverParameters->DamageFlag, dtrain_out ) ) { + m_derailment.reset(); + return nullptr; + } + if( m_derailment ) { + return nullptr; + } + // what derailed it, at the speed it had then; the flag of the damage set by something else (SetDamage) is other + auto const known { MoverParameters->DerailedBy != derailment::reason::none }; + auto const *track { RaTrackGet() }; + // run off the end of a track it's on the piece made past the end (TTrack::NullCreate(), auto_null): the track it ran off + if( ( track != nullptr ) && ( ( track->iCategoryFlag & 0x80 ) != 0 ) && ( track->CurrentPrev() != nullptr ) ) { + track = track->CurrentPrev(); + } + m_derailment = derailment::notice { + asName, + known ? MoverParameters->DerailedBy : derailment::reason::other, + track != nullptr ? track->name() : std::string(), + known ? MoverParameters->DerailVelocity : std::abs( MoverParameters->V ) * 3.6 }; + return &*m_derailment; +} + double TDynamicObject::off_track_offset() const { if( false == MoverParameters->OffTrack.active() ) { @@ -9918,6 +9942,8 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { update_brake_pipes( Deltatime ); Timer::subsystem.vehicles_update.stop(); + report_derailments(); + // jeśli jest coś do usunięcia z listy, to trzeba na końcu erase_disabled(); @@ -9993,6 +10019,17 @@ std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const } // namespace +void +vehicle_table::report_derailments() { + + for( auto *vehicle : m_items ) { + if( false == vehicle->bEnabled ) { continue; } + if( auto const *notice { vehicle->new_derailment() } ) { + simulation::State.report_derailment( *vehicle, *notice ); + } + } +} + void vehicle_table::update_off_track_contacts( double const Deltatime ) { diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index ca82a0950..f2d4b630f 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -756,6 +756,11 @@ private: // physics.derailment new, the vehicle off the track (vehicle/derailmotion.h): the offset of its body from the axis of // the track at the place nearest to it, to the left of its front positive [m]; 0 while it's on the track double off_track_offset() const; + // the vehicle derailed since the last look, by any model: what the scenery and the test mode are told, once each + // time it leaves the rails; nothing otherwise. put back on the rails it's forgotten + derailment::notice const *new_derailment(); + // its derailment while it's off the rails, nothing on them + derailment::notice const *derailment_notice() const { return m_derailment ? &*m_derailment : nullptr; } // the gap between the ends of the vehicle and the one at its End, as they meet off the track [m]: negative the // buffers pressed in double off_track_gap( int End ) const; @@ -805,6 +810,7 @@ private: bool m_offtrackplaced { false }; // placed off the track: placed on it again once it's back on the rails std::array m_pulledoff; // the distance the coupling of an end pulled the vehicle coupled there over the climbing limit derailment::stretch m_struck; // on the rails: the distance a body off the track pushed it sideways over the climbing limit + std::optional m_derailment; // of new_derailment(), while the vehicle is off the rails // the model, the axes and the coupling points placed by the motion off the track void place_off_track(); public: @@ -1044,6 +1050,9 @@ private: // 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 ); + // the vehicles which derailed in the update, after all of them moved: told to the scenery and the test mode + void + report_derailments(); // physics.derailment new: the bodies of the vehicles off the track and those near them run into each other instead // of into one another: the impulses of the hits, the bodies moved apart, a vehicle on the rails pushed off them; // what the bodies overlap by goes to the log every second diff --git a/vehicle/blackbox.cpp b/vehicle/blackbox.cpp index 0138b6acd..df6bb7416 100644 --- a/vehicle/blackbox.cpp +++ b/vehicle/blackbox.cpp @@ -394,6 +394,8 @@ void writer::derailment(derailment_state const &State) { out.f32(State.roll); out.f32(State.travelled); out.u8(State.lying ? 1 : 0); + out.u8(State.reason); + out.text(State.track); emit(record::derailment); } diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 26fe5c6a1..20b98bfa2 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -337,6 +337,7 @@ inline constexpr std::uint8_t collision{5}; namespace derailment_phases { inline constexpr std::uint8_t left_track{0}; // it left the track inline constexpr std::uint8_t at_rest{1}; // it came to rest off the track +inline constexpr std::uint8_t derailed{2}; // it derailed, by any model: written as it happens } // namespace derailment_phases // a vehicle off the track (physics.derailment new): as it leaves it, and where it comes to rest @@ -352,6 +353,8 @@ struct derailment_state { float roll{0.0f}; // [rad] of its body against the level, to the left positive; 90 degrees on its side float travelled{0.0f}; // [m] on the ground since it left the rails bool lying{false}; // on its side + std::uint8_t reason{0}; // what derailed it, finer: the code of derailment::reason (McZapkie/derailment.h), 0 not known + std::string track; // name of the track it derailed on, empty for a track without one }; struct vehicle_state { From efde2157eba2d14be487ae4d19f91a59ebea5c3c Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 29 Nov 2026 15:57:26 +0100 Subject: [PATCH 03/20] fix: the derailment notice builds on the layout of #531: physics/derailment.h, TDynamicObject::physics --- simulation/blackboxrecorder.cpp | 6 +++--- simulation/simulationtest.cpp | 4 ++-- vehicle/blackbox.h | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index e6328d6ea..d81521caa 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "input/command.h" -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "vehicle/Train.h" @@ -616,11 +616,11 @@ void blackbox_recorder::write_derailed(TDynamicObject const *Vehicle, derailment state.time = m_time; state.vehicle = vehicle_id(Vehicle); state.phase = blackbox::derailment_phases::derailed; - state.cause = cause_of(Notice.why, Vehicle->MoverParameters->Derailed); + state.cause = cause_of(Notice.why, Vehicle->physics->Derailed); state.position = Vehicle->GetPosition(); state.heading = static_cast(std::atan2(Vehicle->VectorFront().x, Vehicle->VectorFront().z)); // as it derailed, along its front as it moves now - state.speed_kmh = static_cast(std::copysign(Notice.velocity, Vehicle->MoverParameters->V)); + state.speed_kmh = static_cast(std::copysign(Notice.velocity, Vehicle->physics->V)); state.reason = static_cast(Notice.why); state.track = text_of(Notice.track); m_writer->derailment(state); diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 4a29cfd6e..234223168 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtest.h" #include "application/application.h" -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include "scene/scene.h" #include "simulation/simulation.h" #include "utilities/Globals.h" @@ -210,7 +210,7 @@ bool test_manager::tested(TDynamicObject const &Vehicle) const return true; return std::ranges::any_of(Global.test.vehicles, [&Vehicle](std::string const &Name) { auto *vehicle { simulation::Vehicles.find(Name) }; - return vehicle != nullptr && vehicle->find_vehicle(coupling::coupler, [&Vehicle](TDynamicObject const *Other) { return Other == &Vehicle; }) != nullptr; + return vehicle != nullptr && vehicle->find_vehicle(Coupling::coupler, [&Vehicle](TDynamicObject const *Other) { return Other == &Vehicle; }) != nullptr; }); } diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 20b98bfa2..be8c7879c 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -353,7 +353,7 @@ struct derailment_state { float roll{0.0f}; // [rad] of its body against the level, to the left positive; 90 degrees on its side float travelled{0.0f}; // [m] on the ground since it left the rails bool lying{false}; // on its side - std::uint8_t reason{0}; // what derailed it, finer: the code of derailment::reason (McZapkie/derailment.h), 0 not known + std::uint8_t reason{0}; // what derailed it, finer: the code of derailment::reason (physics/derailment.h), 0 not known std::string track; // name of the track it derailed on, empty for a track without one }; From b0f7500004bd1623fcecf5e0d16dcda09da04c8d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 00:12:58 +0100 Subject: [PATCH 04/20] comment: the wiper mask is read into an int, not the uint8_t --- physics/components/fizparser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index 4aabe9a75..ece8c004c 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -447,7 +447,7 @@ bool physics::Vehicle::readWiperList(std::string const &line) WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); return false; } - // the mask of the wipers is a number: read into the uint8_t directly, the parser would take only its first character + // the mask of the wipers is a number: read into an int and clamped, as the parser would take only its first character for a uint8_t int bytesum{0}; parser >> bytesum >> WiperList[idx].WiperSpeed >> WiperList[idx].interval >> WiperList[idx].outBackDelay; WiperList[idx].byteSum = static_cast(std::clamp(bytesum, 0, 255)); From a81d1495412c1b4467a64433cf8a519bc5650ad3 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 00:15:50 +0100 Subject: [PATCH 05/20] feat: a memory cell of its own for the derailment of a vehicle report_derailment() writes the memory cell at once and only queues the events, which run later in Events.update(). A collision derails both vehicles in one frame, so when :derailed ran, __simulation.derailment already held B. The scenery can now declare the memory cell :derailed, written the same way and with the same three fields as __simulation.derailment, for the events of that one vehicle to read. Documented that __simulation.derailment keeps only the last derailment of a frame; eu07_td_off_track_end_scenery_told checks the cell of the locomotive now. --- physics/derailment.cpp | 4 +++ physics/derailment.h | 5 ++- simulation/simulation.cpp | 31 ++++++++++--------- simulation/simulation.h | 9 +++--- tests/scenarios/README.md | 14 ++++++--- .../eu07_td_off_track_end_scenery_told.json | 8 +++-- tests/unit/test_derailment.cpp | 4 +++ 7 files changed, 50 insertions(+), 25 deletions(-) diff --git a/physics/derailment.cpp b/physics/derailment.cpp index fc784b362..89ad5a0a3 100644 --- a/physics/derailment.cpp +++ b/physics/derailment.cpp @@ -306,6 +306,10 @@ std::string cell_text(notice const &Notice) { return std::format("{} {} {}", Notice.vehicle, reason_name(Notice.why), Notice.track.empty() ? std::string_view{"none"} : std::string_view{Notice.track}); } +std::string derailed_name(std::string_view const Vehicle) { + return std::string{Vehicle} + ":derailed"; +} + std::string describe(notice const &Notice) { return std::format("{} derailed ({}) {} at {:.0f} km/h", Notice.vehicle, reason_name(Notice.why), Notice.track.empty() ? std::string{"on a track without a name"} : "on track " + Notice.track, std::abs(Notice.velocity)); diff --git a/physics/derailment.h b/physics/derailment.h index 1e2851e0e..d8937754e 100644 --- a/physics/derailment.h +++ b/physics/derailment.h @@ -259,8 +259,11 @@ struct notice { std::string track; // name of the track it derailed on, empty for a track without one double velocity{0.0}; // [km/h] as it derailed }; -// the text of the memory cell __simulation.derailment: " ", "none" for a track without a name +// the text of the memory cell __simulation.derailment, and of :derailed: " ", "none" +// for a track without a name std::string cell_text(notice const &Notice); +// the name of the memory cell and of the event of the derailment of that one vehicle: ":derailed" +std::string derailed_name(std::string_view Vehicle); // for the log and the verdict of a test: " derailed () on track at km/h" std::string describe(notice const &Notice); diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 52e1eb5d9..25aa8d9b5 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -132,20 +132,23 @@ void state_manager::report_derailment( TDynamicObject const &Vehicle, derailment::notice const &Notice ) { WriteLog( "derailment: " + derailment::describe( Notice ) ); - auto const name { std::string( derailment_name ) }; - if( auto *cell { Memory.find( name ) } ) { - cell->UpdateValues( - derailment::cell_text( Notice ), - Notice.velocity, - static_cast( static_cast( Notice.why ) ), - basic_event::flags::text | basic_event::flags::value1 | basic_event::flags::value2 ); - } - if( auto *event { Events.FindEvent( name ) } ) { - Events.AddToQuery( event, &Vehicle ); - } - if( auto *event { Events.FindEvent( Vehicle.name() + ":derailed" ) } ) { - Events.AddToQuery( event, &Vehicle ); - } + auto const text { derailment::cell_text( Notice ) }; + // the cell of the name gets the notice at once, its event runs later (Events.update()): each with a cell of its own + // for the events of one vehicle, which the derailment of another one in the same frame doesn't overwrite + auto const tell { [ & ]( std::string const &Name ) { + if( auto *cell { Memory.find( Name ) } ) { + cell->UpdateValues( + text, + Notice.velocity, + static_cast( static_cast( Notice.why ) ), + basic_event::flags::text | basic_event::flags::value1 | basic_event::flags::value2 ); + } + if( auto *launched { Events.FindEvent( Name ) } ) { + Events.AddToQuery( launched, &Vehicle ); + } + } }; + tell( std::string( derailment_name ) ); + tell( derailment::derailed_name( Vehicle.name() ) ); Blackbox.derailed( &Vehicle, Notice ); test().vehicle_derailed( Vehicle, Notice ); } diff --git a/simulation/simulation.h b/simulation/simulation.h index 9bf9cd057..6fd044f67 100644 --- a/simulation/simulation.h +++ b/simulation/simulation.h @@ -73,10 +73,11 @@ public: void export_as_text( std::string const &Scenariofile ) const; // the vehicle derailed: the log, the black box, the test mode, and the scenery which asked for it. the scenery's - // memory cell __simulation.derailment gets the notice (derailment::cell_text(), value 1 the speed [km/h], value 2 - // the code of the cause), then its events __simulation.derailment and :derailed run, the vehicle their - // activator. a scenery declares those it wants: nothing is made at the start, where a node made would take a - // draw of the random numbers and change every run + // memory cells __simulation.derailment and :derailed get the notice (derailment::cell_text(), value 1 the + // speed [km/h], value 2 the code of the cause) at once, then its events of those names run, the vehicle their + // activator. __simulation.derailment holds the last derailment of a frame, its event runs once, for the first: + // an event of one vehicle reads the cell of that vehicle. a scenery declares those it wants: nothing is made at the + // start, where a node made would take a draw of the random numbers and change every run void report_derailment( TDynamicObject const &Vehicle, derailment::notice const &Notice ); // name of the memory cell and of the event of a derailment of any vehicle diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 7d9ec9e52..a62ca84c8 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -132,16 +132,22 @@ it needs, nothing is made for it otherwise: ``` node -1 0 __simulation.derailment memcell 0 0 0 none 0 0 none endmemcell +node -1 0 ep07-424:derailed memcell 0 0 0 none 0 0 none endmemcell event __simulation.derailment multiple 0 none stop_the_line endevent -event ep07-424:derailed UpdateValues 0 __test.result derailed 0 * endevent +event ep07-424:derailed multiple 0 ep07-424:derailed send_the_crane condition memcompare * * 2 endevent ``` - the memory cell `__simulation.derailment` gets, before the events run: the text ` ` (`none` for a track without a name), value 1 the speed [km/h] as it derailed (in a collision: after the hit), value 2 the code of the cause. A `memcompare` can test the vehicle by the start of the text (`ep07-424*`) and the cause by value 2; +- the memory cell `:derailed`, if the scenery declares it, gets the same of that one vehicle, the same way (above, `send_the_crane` runs if the EP07 overturned: code 2); - the event `__simulation.derailment` runs for a derailment of any vehicle, `:derailed` for that vehicle - (like `:busy`); the vehicle is their activator (`whois`). Two vehicles derailing in the same frame run - the first one once, the cell holds the second. + (like `:busy`); the vehicle is their activator (`whois`). + +The cells are written at once and the events run later, in the update of the events. Two vehicles derailing in the +same frame (a collision derails both at once) run the event `__simulation.derailment` once, for the first one, and the +cell `__simulation.derailment` holds the last one: it keeps only the last derailment of a frame. An event of one +vehicle reads the cell of that vehicle, `:derailed`, not `__simulation.derailment`. | code | cause | | | --- | --- | --- | @@ -441,7 +447,7 @@ on at 1:5). `eu07_td_off_track_end_scenery_told` is `eu07_td_off_track_end` with the memory cell and the events of a derailment declared in `vars.track_nodes` (see *A derailment, for the scenery*): the event `:derailed` of the locomotive -checks the cell and marks a cell of the case, which the log shows. `eu07_td_buckle_derails_ends_test` is `eu07_td_buckle_derails` with +checks the cell `:derailed` of the locomotive and marks a cell of the case, which the log shows with both cells. `eu07_td_buckle_derails_ends_test` is `eu07_td_buckle_derails` with `test.fail_on_derailment yes`: the derailment of the EU07 under test ends the run with `derailment`. The runner's summary tells the derailment of the train under test after the case, from the verdict line. diff --git a/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json b/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json index 58e804567..ded101583 100644 --- a/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json +++ b/tests/scenarios/cases/eu07_td_off_track_end_scenery_told.json @@ -1,5 +1,5 @@ { - "description": "The scenery is told of a derailment: eu07_td_off_track_end (an EU07 with three coaches and no driver runs off the end of autotest_stub at 60 km/h) with the memory cell __simulation.derailment, the event of the same name (logvalues of the cell) and the event :derailed of the locomotive declared in the fragment. The cell holds the vehicle, the cause, the track and the speed and the code of the cause when the events run; the event of the locomotive checks the cell (its name, end of track: code 3) and marks a cell of the case. test.fail_on_derailment yes doesn't end the test: the derailed train isn't the one under test (the EU07 standing on track 1), so the run ends on the timeout as eu07_td_off_track_end does.", + "description": "The scenery is told of a derailment: eu07_td_off_track_end (an EU07 with three coaches and no driver runs off the end of autotest_stub at 60 km/h) with the memory cell __simulation.derailment, the event of the same name (logvalues of the cell) and the memory cell and the event :derailed of the locomotive declared in the fragment. The cells hold the vehicle, the cause, the track and the speed and the code of the cause when the events run; the event of the locomotive checks its own cell (its name, end of track: code 3), logs it and marks a cell of the case. test.fail_on_derailment yes doesn't end the test: the derailed train isn't the one under test (the EU07 standing on track 1), so the run ends on the timeout as eu07_td_off_track_end does.", "base_scenery": "td.scn", "time": "10:34", "fragment": "td_off_track.scn", @@ -7,7 +7,7 @@ "track": "autotest_stub", "offset": "100", "velocity": "60", - "track_nodes": "node -1 0 autotest_stub track normal 150.0 1.435 0.15 25.0 20 0 flat vis\n rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1\n-150.0 0.2 600.0 0.0 //point 1\n0.0 0.0 0.0 //control vector 1\n0.0 0.0 0.0 //control vector 2\n-150.0 0.2 750.0 0.0 //point 2\n0\nendtrack\nnode -1 0 __simulation.derailment memcell 0 0 0 none 0 0 none endmemcell\nnode -1 0 autotest_seen memcell 0 0 0 none 0 0 none endmemcell\nevent __simulation.derailment logvalues 0 __simulation.derailment endevent\nevent {{vehicle}}_off:derailed multiple 0 __simulation.derailment autotest_derail_seen autotest_derail_log condition memcompare {{vehicle}}_off* * 3 endevent\nevent autotest_derail_seen UpdateValues 0 autotest_seen end_of_track_seen 1 * endevent\nevent autotest_derail_log logvalues 0 autotest_seen endevent", + "track_nodes": "node -1 0 autotest_stub track normal 150.0 1.435 0.15 25.0 20 0 flat vis\n rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1\n-150.0 0.2 600.0 0.0 //point 1\n0.0 0.0 0.0 //control vector 1\n0.0 0.0 0.0 //control vector 2\n-150.0 0.2 750.0 0.0 //point 2\n0\nendtrack\nnode -1 0 __simulation.derailment memcell 0 0 0 none 0 0 none endmemcell\nnode -1 0 {{vehicle}}_off:derailed memcell 0 0 0 none 0 0 none endmemcell\nnode -1 0 autotest_seen memcell 0 0 0 none 0 0 none endmemcell\nevent __simulation.derailment logvalues 0 __simulation.derailment endevent\nevent {{vehicle}}_off:derailed multiple 0 {{vehicle}}_off:derailed autotest_derail_seen autotest_derail_log autotest_derail_own_log condition memcompare {{vehicle}}_off* * 3 endevent\nevent autotest_derail_seen UpdateValues 0 autotest_seen end_of_track_seen 1 * endevent\nevent autotest_derail_log logvalues 0 autotest_seen endevent\nevent autotest_derail_own_log logvalues 0 {{vehicle}}_off:derailed endevent", "consist": [ "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", @@ -34,6 +34,10 @@ "type": "log_contains", "pattern": "Memcell __simulation\\.derailment: \\[autotest_\\S+_off end_of_track autotest_stub\\] \\[(59|60)\\.[0-9]+\\] \\[3\\.00\\]" }, + { + "type": "log_contains", + "pattern": "Memcell autotest_\\S+_off:derailed: \\[autotest_\\S+_off end_of_track autotest_stub\\] \\[(59|60)\\.[0-9]+\\] \\[3\\.00\\]" + }, { "type": "log_contains", "pattern": "Memcell autotest_seen: \\[end_of_track_seen\\] \\[1\\.00\\]" diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index c44aacaf4..9d68ffabd 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -376,6 +376,10 @@ TEST_CASE("derailment: what the scenery and the test mode are told") { notice.track.clear(); CHECK(dr::cell_text(notice) == "ep07-424 overturned none"); } + SUBCASE("the memory cell and the event of one vehicle: :derailed") { + CHECK(dr::derailed_name("ep07-424") == "ep07-424:derailed"); + CHECK(dr::derailed_name("autotest_x_w1") == "autotest_x_w1:derailed"); + } SUBCASE("the log and the verdict of a test") { dr::notice notice{"autotest_x", dr::reason::buckle, "tdo_n222", 46.4}; CHECK(dr::describe(notice) == "autotest_x derailed (buckle) on track tdo_n222 at 46 km/h"); From 6c3179029acf6ba903cbabfb594bad2d238d57c3 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 00:16:38 +0100 Subject: [PATCH 06/20] refactor: the cause of a derailment in reason_of(), the log in log_derailment() The nested conditional operators mapping DerailReason and the verdict of the criteria to derailment::reason in Derail(), derail() and derail_in_collision() go into the switch of reason_of() (S3358), and the log of Derail() into log_derailment(); Derail() returns early instead of nesting its body (S3776). The behaviour stays the same for every caller. --- physics/components/collisions.cpp | 138 ++++++++++++++++++------------ 1 file changed, 81 insertions(+), 57 deletions(-) diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index aec6b0684..5ce2a5a89 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -63,6 +63,50 @@ void tear_brake_hoses(physics::Vehicle &Vehicle) } } +// what the scenery and the test mode are told of a derailment the legacy way or in a collision +derailment::reason reason_of(DerailReason const Reason) +{ + switch (Reason) + { + case END_OF_TRACK: return derailment::reason::end_of_track; + case TOO_HIGH_SPEED: return derailment::reason::overspeed; + case GAUGE_MISMATCH: return derailment::reason::track_gauge; + case WRONG_TRACK_TYPE: return derailment::reason::track_type; + case COLLISION: return derailment::reason::collision; + case TRAILED_SWITCH: return derailment::reason::trailed_switch; + case COLLISION_OVERRIDE: return derailment::reason::overriding; + case COLLISION_PUSHED_OFF: return derailment::reason::pushed_off; + default: return derailment::reason::other; + } +} + +// what they are told of a derailment by the criteria (physics.derailment new) +derailment::reason reason_of(derailment::verdict const &Verdict, derailment::track_state const &Track) +{ + // a buckle under it is what derailed it, whichever way it went + if (Track.buckle_curvature != 0.0) + { + return derailment::reason::buckle; + } + return Verdict.result == derailment::outcome::overturned ? derailment::reason::overturned : derailment::reason::flange_climb; +} + +// the log of a derailment the legacy way +void log_derailment(std::string const &Name, DerailReason const Reason) +{ + switch (Reason) + { + case END_OF_TRACK: ErrorLog("Bad driving: " + Name + " derailed due to end of track"); break; + case TOO_HIGH_SPEED: ErrorLog("Bad driving: " + Name + " derailed due to too high speed"); break; + case GAUGE_MISMATCH: ErrorLog("Bad dynamic: " + Name + " derailed due to track width"); break; // błąd w scenerii + case WRONG_TRACK_TYPE: ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); break; // błąd w scenerii + // this reason also generates its own message in `physics::Vehicle::CollisionDetect()` + case COLLISION: WriteLog("Bad driving: " + Name + " derailed"); break; + case TRAILED_SWITCH: ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); break; + default: break; + } +} + } // namespace // ************************************************************************************************* @@ -264,7 +308,7 @@ void physics::Vehicle::derail_in_collision(DerailReason const Reason, std::strin derailAcceleration = 0.0; derailSide = 0; collisionDerail = Reason; - noteDerailment(Reason == COLLISION_OVERRIDE ? derailment::reason::overriding : derailment::reason::pushed_off); + noteDerailment(reason_of(Reason)); eventFlag = true; MainSwitch(false, range_t::local); if (Vel < 5.0) @@ -745,10 +789,7 @@ void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::ve } derailOutcome = Verdict.result; derailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; - // a buckle under it is what derailed it, whichever way it went - noteDerailment(Track.buckle_curvature != 0.0 ? derailment::reason::buckle : - Verdict.result == derailment::outcome::overturned ? derailment::reason::overturned : - derailment::reason::flange_climb); + noteDerailment(reason_of(Verdict, Track)); // out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve derailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration; derailSide = 0; @@ -810,60 +851,43 @@ void physics::Vehicle::repair_damage() void physics::Vehicle::Derail(DerailReason const Reason) { - if (DamageFlag.Set(VehicleDamage::derailed)) + if (false == DamageFlag.Set(VehicleDamage::derailed)) { - noteDerailment(Reason == END_OF_TRACK ? derailment::reason::end_of_track : - Reason == TOO_HIGH_SPEED ? derailment::reason::overspeed : - Reason == GAUGE_MISMATCH ? derailment::reason::track_gauge : - Reason == WRONG_TRACK_TYPE ? derailment::reason::track_type : - Reason == COLLISION ? derailment::reason::collision : - Reason == TRAILED_SWITCH ? derailment::reason::trailed_switch : - derailment::reason::other); - eventFlag = true; - MainSwitch(false, range_t::local); - - auto const velocity{travelSpeed}; - accS *= 0.65; - travelSpeed *= 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(travelSpeed - velocity); - } - RunningShape.R = 0; - if (Vel < 5.0) - { - // HACK: prevent permanent axle spin in static vehicle after a collision - nrotValue = 0.0; - slippingWheels = false; - } - // physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the - // ground as the vehicles the criteria derail do, and its brake hoses tear - if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1)) - { - derailOutcome = derailment::outcome::off_rails; - derailCause = derail_motion::cause::end_of_track; - derailAcceleration = 0.0; - derailSide = 0; - tear_brake_hoses(*this); - } - - // Print a message in the log. - if (Reason == END_OF_TRACK) - ErrorLog("Bad driving: " + Name + " derailed due to end of track"); - else if (Reason == TOO_HIGH_SPEED) - ErrorLog("Bad driving: " + Name + " derailed due to too high speed"); - else if (Reason == GAUGE_MISMATCH) - ErrorLog("Bad dynamic: " + Name + " derailed due to track width"); // błąd w scenerii - else if (Reason == WRONG_TRACK_TYPE) - ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii - else if (Reason == COLLISION) - WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `physics::Vehicle::CollisionDetect()` - else if (Reason == TRAILED_SWITCH) - ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); + return; } + noteDerailment(reason_of(Reason)); + eventFlag = true; + MainSwitch(false, range_t::local); + + auto const velocity{travelSpeed}; + accS *= 0.65; + travelSpeed *= 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(travelSpeed - velocity); + } + RunningShape.R = 0; + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrotValue = 0.0; + slippingWheels = false; + } + // physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the + // ground as the vehicles the criteria derail do, and its brake hoses tear + if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1)) + { + derailOutcome = derailment::outcome::off_rails; + derailCause = derail_motion::cause::end_of_track; + derailAcceleration = 0.0; + derailSide = 0; + tear_brake_hoses(*this); + } + + log_derailment(Name, Reason); } void physics::Vehicle::noteDerailment(derailment::reason const Reason) From d1e08078f1bd984f3b0c4e4a592c27e934a2a30b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 01:03:54 +0100 Subject: [PATCH 07/20] fix(derailment): no fall through the ground off the track, and more friction on it (GH#556) physics.derailment new: a vehicle off the track takes the ground from the terrain of the scenery and from the bed of the track. Where the terrain had no ground under a support (a hole in it, past the edge of what was gathered), the slope of the bed was taken, and it went down for ever: 100 m off the track some 65 m. The vehicle fell into it, and once under the terrain it never found the terrain again, as that was over it (a ceiling of 1 m over the vehicle). The slope now ends at its toe, 3 m under the top of the ballast, and away from it, where the terrain says nothing, there's no ground: the vehicle keeps its height. The friction of a vehicle sliding off the track goes from 0.3 to 0.45 on its wheels and from 0.5 to 0.7 on its side: a train off the track at 130-150 km/h slid some 250 m. --- physics/derailment.h | 8 +++++--- tests/unit/test_derail_motion.cpp | 30 +++++++++++++++++++++++++++--- vehicle/derailmotion.cpp | 11 ++++++++++- vehicle/derailmotion.h | 8 +++++++- 4 files changed, 49 insertions(+), 8 deletions(-) diff --git a/physics/derailment.h b/physics/derailment.h index d29fbc852..20d9a161e 100644 --- a/physics/derailment.h +++ b/physics/derailment.h @@ -211,9 +211,11 @@ private: 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}; +// the friction of a derailed vehicle sliding along [-]: on its wheels ploughing the sleepers and the ballast, or on its +// side digging into the ground (GH#556: with 0.3 and 0.5 a train off the track at 130-150 km/h slid some 250 m, more than +// a derailment on soil gives) +inline constexpr double off_rails_friction{0.45}; +inline constexpr double overturned_friction{0.7}; 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 diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index 2d3a7f1af..842ce2617 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -146,11 +146,11 @@ TEST_CASE("derail motion: the distance it slides goes with the square of the spe auto const slow{dm::stopping_distance(40.0 * kmh, dr::off_rails_friction)}; REQUIRE(fast.has_value()); REQUIRE(slow.has_value()); - CHECK(*fast == doctest::Approx(232.0).epsilon(0.01)); - CHECK(*slow == doctest::Approx(21.0).epsilon(0.01)); + CHECK(*fast == doctest::Approx(154.6).epsilon(0.01)); + CHECK(*slow == doctest::Approx(14.0).epsilon(0.01)); CHECK(*fast / *slow == doctest::Approx(133.0 * 133.0 / (40.0 * 40.0)).epsilon(1e-9)); // on its side - CHECK(*dm::stopping_distance(133.0 * kmh, dr::overturned_friction) == doctest::Approx(*fast * 0.3 / 0.5).epsilon(1e-9)); + CHECK(*dm::stopping_distance(133.0 * kmh, dr::overturned_friction) == doctest::Approx(*fast * dr::off_rails_friction / dr::overturned_friction).epsilon(1e-9)); // uphill sooner, downhill further, down a slope steeper than the friction it doesn't stop CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, 0.05) < *slow); CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, -0.05) > *slow); @@ -392,6 +392,30 @@ TEST_CASE("derail motion: the ground of the scenery") { CHECK(*embankment.height(20.0, 0.0, 12.0) == doctest::Approx(7.0)); dm::site const bare{nullptr, bed}; CHECK(*bare.height(20.0, 0.0, 12.0) == doctest::Approx(9.8)); + // the slope of the bed goes down to its toe, 3 m under the top of the ballast, not for ever + CHECK(bed.height(100.0, 0.0) == doctest::Approx(9.8 - 3.0)); + CHECK(bed.reaches(2.0 + 3.0 * 1.5, 0.0)); + CHECK_FALSE(bed.reaches(2.0 + 3.0 * 1.5 + 0.1, 0.0)); + } + SUBCASE("GH#556: where the terrain has no ground, the vehicle away from the bed finds none, rather than the slope of the bed going down for ever") { + dm::formation bed; + bed.point = glm::dvec3{0.0, 10.0, 0.0}; + bed.direction = glm::dvec3{0.0, 0.0, 1.0}; + bed.half_width = 2.0; + // a field 1 m under the top of the ballast, gathered for 20 m around: past it and in its holes there's no terrain + std::vector field{ + {glm::dvec3{-20.0, 8.8, -20.0}, glm::dvec3{20.0, 8.8, -20.0}, glm::dvec3{20.0, 8.8, 20.0}}, + {glm::dvec3{-20.0, 8.8, -20.0}, glm::dvec3{20.0, 8.8, 20.0}, glm::dvec3{-20.0, 8.8, 20.0}}}; + dm::mesh_ground const terrain{field, glm::dvec2{-20.0, -20.0}, glm::dvec2{20.0, 20.0}}; + dm::site const ground{&terrain, bed}; + // on the field: the field, or the bed where it's higher + CHECK(*ground.height(10.0, 0.0, 12.0) == doctest::Approx(8.8)); + CHECK(*ground.height(3.0, 0.0, 12.0) == doctest::Approx(9.8 - 1.0 / 1.5)); + // past the field, on the slope of the bed: the slope, down to its toe + CHECK(*ground.height(4.0, 30.0, 12.0) == doctest::Approx(9.8 - 2.0 / 1.5)); + // past the field and away from the bed: none (was the slope: 100 m off the track some 65 m down) + CHECK_FALSE(ground.height(100.0, 0.0, 12.0).has_value()); + CHECK_FALSE(ground.height(30.0, 30.0, 12.0).has_value()); } } diff --git a/vehicle/derailmotion.cpp b/vehicle/derailmotion.cpp index 252ba7f4d..0c0e02929 100644 --- a/vehicle/derailmotion.cpp +++ b/vehicle/derailmotion.cpp @@ -449,7 +449,12 @@ double formation::height(double const X, double const Z) const { if (across <= half_width) { return top; } - return top - (across - half_width) / std::max(slope, 0.1); + return top - std::min((across - half_width) / std::max(slope, 0.1), std::max(toe, 0.0)); +} + +bool formation::reaches(double const X, double const Z) const { + auto const across{std::abs(glm::dot(glm::dvec3{X, 0.0, Z} - glm::dvec3{point.x, 0.0, point.z}, left_of(level(direction))))}; + return across <= half_width + std::max(toe, 0.0) * std::max(slope, 0.1); } std::optional site::height(double const X, double const Z, double const Ceiling) const { @@ -461,6 +466,10 @@ std::optional site::height(double const X, double const Z, double const } else { result = m_terrain->height(X, Z, Ceiling); + if (false == result.has_value() && false == m_bed.reaches(X, Z)) { + // terrain, but none here, and away from the bed: nothing says where the ground is + return std::nullopt; + } } if (bed <= Ceiling && (false == result.has_value() || bed > *result)) { result = bed; diff --git a/vehicle/derailmotion.h b/vehicle/derailmotion.h index 20c89747f..ade4bf2b4 100644 --- a/vehicle/derailmotion.h +++ b/vehicle/derailmotion.h @@ -270,11 +270,17 @@ struct formation { double depth{0.2}; // of the top of the ballast under the rails [m] double half_width{2.0}; // from the axis to the edge of the top [m] double slope{1.5}; // run of the slope per metre of fall: 1:1.5, of an embankment + double toe{3.0}; // how far the slope goes down below the top of the ballast [m], where the terrain doesn't say more double height(double X, double Z) const; + // whether the point lies on the top or on the slope of the bed, down to its toe + bool reaches(double X, double Z) const; }; // the ground as the vehicle finds it: the terrain of the scenery where it has any, level with the top of the ballast -// where it has none (a scenery without terrain), and the bed of the track over it +// where it has none (a scenery without terrain), and the bed of the track over it. where the scenery has terrain but +// none under the point (a hole in it, past the edge of what was gathered), the bed only as far as its slope reaches +// and nothing further: none, the vehicle keeps its height there (GH#556: the slope went down for ever, the vehicle +// fell through it under the terrain, and once under it the terrain was over it and never found again) class site final : public ground { public: explicit site(ground const *Terrain = nullptr, formation const &Bed = {}) : m_terrain{Terrain}, m_bed{Bed} {} From 551172f9db5029cb852c648ca04733218bfa350f Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 02:08:01 +0100 Subject: [PATCH 08/20] test(derailment): the expectations of the friction on the ground follow its new values --- tests/unit/test_derail_motion.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index 842ce2617..611ea323a 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -152,9 +152,9 @@ TEST_CASE("derail motion: the distance it slides goes with the square of the spe // on its side CHECK(*dm::stopping_distance(133.0 * kmh, dr::overturned_friction) == doctest::Approx(*fast * dr::off_rails_friction / dr::overturned_friction).epsilon(1e-9)); // uphill sooner, downhill further, down a slope steeper than the friction it doesn't stop - CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, 0.05) < *slow); - CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, -0.05) > *slow); - CHECK_FALSE(dm::stopping_distance(40.0 * kmh, 0.3, -0.4).has_value()); + CHECK(*dm::stopping_distance(40.0 * kmh, dr::off_rails_friction, 0.05) < *slow); + CHECK(*dm::stopping_distance(40.0 * kmh, dr::off_rails_friction, -0.05) > *slow); + CHECK_FALSE(dm::stopping_distance(40.0 * kmh, dr::off_rails_friction, -(dr::off_rails_friction + 0.1)).has_value()); SUBCASE("the vehicle off the end of the track slides as far, straight on, upright") { for (auto const speed : {133.0, 40.0}) { @@ -254,9 +254,10 @@ TEST_CASE("derail motion: tipping over goes as far as the overturning went over TEST_CASE("derail motion: the ground under it") { SUBCASE("off the edge of an embankment it slides down the slope and falls on its side towards the bottom") { - // 1:1.5 down 4 m to the left, the vehicle leaving the track 4 degrees to the left at 60 km/h + // 1:1.5 down 4 m to the left, the vehicle leaving the track 4 degrees to the left at 90 km/h (fast enough to go over + // the edge with the friction of the ballast) profile const embankment{-1.0 / 1.5, 4.0}; - auto start{leaving(60.0 * kmh, dm::cause::off_rails)}; + auto start{leaving(90.0 * kmh, dm::cause::off_rails)}; start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; auto const result{slide(start, embankment)}; MESSAGE(std::format("down the embankment: {:.1f} m across, {:.1f} m down, tipped {:.0f} degrees, after {:.1f} m", result.across, -0.2 - result.height, result.tipping / degree, result.travelled)); From f0d3cfbd98598baa995f45c15f47dacf4b029fcc Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 02:33:37 +0100 Subject: [PATCH 09/20] test(derailment): the deceleration on its side and the zigzag of a folded train with the new friction --- tests/unit/test_derail_motion.cpp | 4 +++- tests/unit/test_derailment_vehicle.cpp | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index 611ea323a..9761f2831 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -796,7 +796,9 @@ TEST_CASE("derail motion: a train off the track pushed from behind folds into a MESSAGE(std::format("{} of 8 trains folded, {} of {} neighbouring folds turn opposite ways", foldedtrains, zigzags, pairs)); CHECK(foldedtrains >= 4); CHECK(pairs >= 2); - CHECK(zigzags * 4 >= pairs * 3); + // at least half of them (with the friction of 0.45/0.7 on the ground the trains fold less: 2 pairs over the eight seeds, + // one of them opposite ways) + CHECK(zigzags * 2 >= pairs); SUBCASE("without the bite and the scatter it stays in line") { auto const straight{run_train(overturning_train(1, false), coach())}; MESSAGE((std::string{"unscattered at rest:"} + described(straight))); diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 9a3e857f1..c6a2d3c80 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -60,14 +60,15 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); CHECK_FALSE(eu07vehicle->lineBreaker.IsClosed()); - // not stopped dead as the legacy model has it: it slows down at half of g on the 80 of its 96 t + // not stopped dead as the legacy model has it: it slows down at the friction of a vehicle on its side, 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)); + CHECK(deceleration == doctest::Approx(dr::overturned_friction * dr::gravity * 80.0 / 96.0).epsilon(0.05)); for (int step = 0; step < 2000; ++step) { eu07vehicle.step(curve); } From 597d72fdf9bc255a7a9e107d82eb94f08c3574ab Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 03:02:47 +0100 Subject: [PATCH 10/20] test, docs: the derailment cases and the behaviour changes with the new friction on the ground (GH#556) --- docs/behaviour-changes.md | 6 ++++++ tests/scenarios/cases/eu07_td_off_track_buckle_fast.json | 4 ++-- tests/scenarios/cases/eu07_td_off_track_end.json | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/behaviour-changes.md b/docs/behaviour-changes.md index 069bb6e90..d95baaa4c 100644 --- a/docs/behaviour-changes.md +++ b/docs/behaviour-changes.md @@ -105,6 +105,12 @@ existing data. `couplerphysics` (slack, hysteresis and breaking of the coupler; commits c85aab4f to 226155d4, no PR number) are off by default. - **Welded track buckles in the heat** (#378) when the scenery or an event sets it; no effect otherwise. +- **A vehicle off the track (`physics.derailment new`) slides less far and no longer falls through the ground** + (GH#556, #NNN). The friction on the ground goes from 0.3 to 0.45 on its wheels and from 0.5 to 0.7 on its side: an + EU07 overturning at 130 km/h stops some 140 m on instead of 170 m. Where the terrain of the scenery has no ground + under it (a hole, past what was gathered around it), the slope of the track bed ends 3 m under the ballast and the + vehicle keeps its height beyond it, rather than sinking under the terrain. Needs: nothing; `old` and `monitor` are + not affected. - **The cab shake is taken at the frame's moment** (#403, #414) and no longer moves in steps. - **Station names keep their Polish letters** in the interface and timetables, a W4 finds its station by one key (#418). A station of departure written in capitals is still a stop (#343). diff --git a/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json b/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json index 6b7154396..4435c3b59 100644 --- a/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json +++ b/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json @@ -1,5 +1,5 @@ { - "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 133 km/h into the curve tdo_n222 of td.scn (R 600 m, cant 65 mm), buckled hard 600 mm over a main lobe of 8 m from the start (the buckle keyword of the track). The locomotive overturns on the buckle: it leaves the track, falls on its side within a second and slides on the ground to a stop some 170 m on, 30 m off the track; the coaches behind it go off and over as well, and the train comes to rest folded, the vehicles turned against each other by 10 to 20 degrees.", + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 133 km/h into the curve tdo_n222 of td.scn (R 600 m, cant 65 mm), buckled hard 600 mm over a main lobe of 8 m from the start (the buckle keyword of the track). The locomotive overturns on the buckle: it leaves the track, falls on its side within a second and slides on the ground to a stop some 140 m on, 25 m off the track; the coaches behind it go off and over as well, and the train comes to rest folded, the vehicles turned against each other by 3 to 10 degrees (with the friction of 0.7 on its side, GH#556, it stops sooner and the coaches fold less than with 0.5, which gave 170 m and 3 to 13 degrees).", "base_scenery": "td.scn", "time": "10:34", "fragment": "td_off_track.scn", @@ -41,7 +41,7 @@ "type": "consist_folds", "vehicles": "{{vehicle}}_off,{{vehicle}}_off_w1,{{vehicle}}_off_w2,{{vehicle}}_off_w3", "min_bend": 8, - "min_folds": 2 + "min_folds": 1 }, { "type": "no_overlap", diff --git a/tests/scenarios/cases/eu07_td_off_track_end.json b/tests/scenarios/cases/eu07_td_off_track_end.json index 5a37cb2d0..71204aa6a 100644 --- a/tests/scenarios/cases/eu07_td_off_track_end.json +++ b/tests/scenarios/cases/eu07_td_off_track_end.json @@ -1,5 +1,5 @@ { - "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 60 km/h off the end of a track of 150 m laid on its own in the fields of td.scn (autotest_stub): it runs straight on, upright, on the ground, and stops some 30 m on (the friction of 0.3 against the 39 km/h left of its 60 km/h as it drops off the end of the rails, the coaches pushing it); the first coach follows it off the end.", + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 60 km/h off the end of a track of 150 m laid on its own in the fields of td.scn (autotest_stub): it runs straight on, upright, on the ground, and stops some 28 m on (the friction of 0.45 against the 36 km/h left of its 60 km/h as it drops off the end of the rails, the coaches pushing it); the first coach follows it off the end.", "base_scenery": "td.scn", "time": "10:34", "fragment": "td_off_track.scn", From 23f30109db38f06f31c2986c13067bf53232bb82 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 03:03:27 +0100 Subject: [PATCH 11/20] docs: the number of the pull request in the behaviour changes --- docs/behaviour-changes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/behaviour-changes.md b/docs/behaviour-changes.md index d95baaa4c..a5e9078be 100644 --- a/docs/behaviour-changes.md +++ b/docs/behaviour-changes.md @@ -106,7 +106,7 @@ existing data. off by default. - **Welded track buckles in the heat** (#378) when the scenery or an event sets it; no effect otherwise. - **A vehicle off the track (`physics.derailment new`) slides less far and no longer falls through the ground** - (GH#556, #NNN). The friction on the ground goes from 0.3 to 0.45 on its wheels and from 0.5 to 0.7 on its side: an + (GH#556, #560). The friction on the ground goes from 0.3 to 0.45 on its wheels and from 0.5 to 0.7 on its side: an EU07 overturning at 130 km/h stops some 140 m on instead of 170 m. Where the terrain of the scenery has no ground under it (a hole, past what was gathered around it), the slope of the track bed ends 3 m under the ballast and the vehicle keeps its height beyond it, rather than sinking under the terrain. Needs: nothing; `old` and `monitor` are From 3b6c60964e72b8fd506b446fbc53353398b8353b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 08:15:52 +0100 Subject: [PATCH 12/20] fix(derailment): the slope of the bed goes on down to the terrain; the toe only bounds it where there's none The toe limited the slope of the bed everywhere, so beside an embankment higher than 3 m the bed was a floor in mid-air 3 m under the ballast, over the field (review of #560). formation::height() is the slope again, unbounded; reaches() alone bounds the bed where the terrain has no ground under the point. The zigzag test runs 32 seeds instead of 8 (23 trains fold, 14 pairs of folds, 8 of them opposite ways), so that one seed folding otherwise doesn't decide it. --- tests/unit/test_derail_motion.cpp | 27 +++++++++++++++++---------- vehicle/derailmotion.cpp | 5 +++-- vehicle/derailmotion.h | 2 +- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index 9761f2831..734860dba 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -393,8 +393,13 @@ TEST_CASE("derail motion: the ground of the scenery") { CHECK(*embankment.height(20.0, 0.0, 12.0) == doctest::Approx(7.0)); dm::site const bare{nullptr, bed}; CHECK(*bare.height(20.0, 0.0, 12.0) == doctest::Approx(9.8)); - // the slope of the bed goes down to its toe, 3 m under the top of the ballast, not for ever - CHECK(bed.height(100.0, 0.0) == doctest::Approx(9.8 - 3.0)); + // an embankment higher than the toe of the bed (5 m over the field): the slope goes on down to the field, no + // floor 3 m under the ballast + dm::flat_ground const deep{4.8}; + dm::site const high{&deep, bed}; + CHECK(*high.height(8.0, 0.0, 12.0) == doctest::Approx(9.8 - 6.0 / 1.5)); + CHECK(*high.height(20.0, 0.0, 12.0) == doctest::Approx(4.8)); + // where the terrain has no ground, the bed counts down to its toe, 3 m under the top of the ballast CHECK(bed.reaches(2.0 + 3.0 * 1.5, 0.0)); CHECK_FALSE(bed.reaches(2.0 + 3.0 * 1.5 + 0.1, 0.0)); } @@ -768,12 +773,14 @@ TEST_CASE("derail motion: the yaw of the body") { } TEST_CASE("derail motion: a train off the track pushed from behind folds into a zigzag") { - // the leading one held back harder, the ones behind push into it: a chaotic matter, so over eight seeds most of the - // trains fold, and the folds next to each other turn opposite ways + // the leading one held back harder, the ones behind push into it: a chaotic matter, so over many seeds most of the + // trains fold, and the folds next to each other turn opposite ways. 32 seeds, so that one seed folding otherwise + // after a change of the scatter or the friction doesn't decide the outcome (with 8 there were 2 pairs of folds) + constexpr std::uint32_t seeds{32}; auto foldedtrains{0}; auto pairs{0}; auto zigzags{0}; - for (std::uint32_t seed = 1; seed <= 8; ++seed) { + for (std::uint32_t seed = 1; seed <= seeds; ++seed) { CAPTURE(seed); auto const train{run_train(overturning_train(seed), coach())}; auto const bent{bends(train)}; @@ -793,11 +800,11 @@ TEST_CASE("derail motion: a train off the track pushed from behind folds into a } foldedtrains += (folds > 0 ? 1 : 0); } - MESSAGE(std::format("{} of 8 trains folded, {} of {} neighbouring folds turn opposite ways", foldedtrains, zigzags, pairs)); - CHECK(foldedtrains >= 4); - CHECK(pairs >= 2); - // at least half of them (with the friction of 0.45/0.7 on the ground the trains fold less: 2 pairs over the eight seeds, - // one of them opposite ways) + MESSAGE(std::format("{} of {} trains folded, {} of {} neighbouring folds turn opposite ways", foldedtrains, seeds, zigzags, pairs)); + // with the friction of 0.45/0.7 on the ground: 23 of the 32 trains fold, 14 pairs of neighbouring folds, 8 of them + // opposite ways. at least half of the trains, 8 pairs, and half of the pairs opposite + CHECK(foldedtrains * 2 >= static_cast(seeds)); + CHECK(pairs >= 8); CHECK(zigzags * 2 >= pairs); SUBCASE("without the bite and the scatter it stays in line") { auto const straight{run_train(overturning_train(1, false), coach())}; diff --git a/vehicle/derailmotion.cpp b/vehicle/derailmotion.cpp index 0c0e02929..7285b8211 100644 --- a/vehicle/derailmotion.cpp +++ b/vehicle/derailmotion.cpp @@ -449,7 +449,7 @@ double formation::height(double const X, double const Z) const { if (across <= half_width) { return top; } - return top - std::min((across - half_width) / std::max(slope, 0.1), std::max(toe, 0.0)); + return top - (across - half_width) / std::max(slope, 0.1); } bool formation::reaches(double const X, double const Z) const { @@ -467,7 +467,8 @@ std::optional site::height(double const X, double const Z, double const else { result = m_terrain->height(X, Z, Ceiling); if (false == result.has_value() && false == m_bed.reaches(X, Z)) { - // terrain, but none here, and away from the bed: nothing says where the ground is + // terrain, but none here, and past the toe of the bed: nothing says where the ground is. (where the terrain + // has ground, the slope goes on under it, so a field deeper than the toe is found, not a floor at the toe) return std::nullopt; } } diff --git a/vehicle/derailmotion.h b/vehicle/derailmotion.h index ade4bf2b4..7af657802 100644 --- a/vehicle/derailmotion.h +++ b/vehicle/derailmotion.h @@ -270,7 +270,7 @@ struct formation { double depth{0.2}; // of the top of the ballast under the rails [m] double half_width{2.0}; // from the axis to the edge of the top [m] double slope{1.5}; // run of the slope per metre of fall: 1:1.5, of an embankment - double toe{3.0}; // how far the slope goes down below the top of the ballast [m], where the terrain doesn't say more + double toe{3.0}; // how far down below the top of the ballast [m] the slope is taken for ground where the terrain has none double height(double X, double Z) const; // whether the point lies on the top or on the slope of the bed, down to its toe bool reaches(double X, double Z) const; From 7d3ccd6dc4fc124dd23408ed00c59c0d61751daf Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Mon, 30 Nov 2026 15:08:45 +0100 Subject: [PATCH 13/20] Textures: read KTX2 files (BC1-BC7, RGBA8, zstd) in both renderers The game now reads .ktx2 texture files, for the OpenGL 4.6 and the Vulkan renderer alike (texture_source::load_KTX2(), parser in model/ktx2.*): - formats: BC1 (RGB and RGBA), BC2, BC3, BC4, BC5 (unsigned and signed), BC6H (unsigned and signed float), BC7, and plain R8G8B8A8 / B8G8R8A8; - the levels stored as they are or packed with zstd (the bundled zstd); with gfx.textures.streaming the worker threads read and unpack them; - the KTXorientation key is honoured: "rd" files are flipped to the bottom row first, BC1-BC5 block by block, plain texels row by row. BC6H and BC7 can't be flipped without decoding: an "rd" file of these is loaded as stored, with a warning in the log, as the BC7 dds files are. A file without the key is taken the way the dds files are (ddsupperorigin); - srgb or linear colour is chosen by the material, as for the dds files; - the alpha of BC7 is checked on a small level, as for the dds files. Not supported, refused with the reason in the log: Basis Universal (ETC1S / UASTC, BasisLZ), zlib supercompression, arrays, cube maps and 3d images. BC1 without alpha, BC4, BC5 and BC6H are new formats for the renderers: opengl_texture::mapping and the Vulkan texture_format_of() map them (no srgb variants for BC4/BC5/BC6H; their alpha reads 1). .ktx2 is looked for right after .dds (textures, materials, the editor's texture browsers). Existing data holds no .ktx2 files, so nothing changes for existing sceneries and vehicles, and no asset change in the SVN is needed. Unit tests: tests/unit/test_ktx2.cpp (header, levels, zstd, orientation, refused files, flipping of BC1-BC5 and plain texels). --- CMakeLists.txt | 1 + application/editormodetextures.cpp | 2 +- application/editormodetrackprops.cpp | 2 +- model/Texture.cpp | 253 +++++++++++- model/Texture.h | 13 +- model/ktx2.cpp | 511 +++++++++++++++++++++++++ model/ktx2.h | 105 +++++ model/materialdata.cpp | 2 +- rendering/vulkan14/vulkan14texture.cpp | 51 ++- tests/unit/CMakeLists.txt | 3 + tests/unit/test_ktx2.cpp | 419 ++++++++++++++++++++ 11 files changed, 1351 insertions(+), 11 deletions(-) create mode 100644 model/ktx2.cpp create mode 100644 model/ktx2.h create mode 100644 tests/unit/test_ktx2.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 561bbc127..ba583b93b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -130,6 +130,7 @@ list(APPEND CMAKE_MODULE_PATH "${VCPKG_INSTALLED_PATH}/share") set(SOURCES "model/Texture.cpp" +"model/ktx2.cpp" "utilities/Timer.cpp" "utilities/asciiname.cpp" "utilities/workerpool.cpp" diff --git a/application/editormodetextures.cpp b/application/editormodetextures.cpp index e3423de5e..476de2ab5 100644 --- a/application/editormodetextures.cpp +++ b/application/editormodetextures.cpp @@ -30,7 +30,7 @@ char const *const material_payload{"EU07_MATERIAL"}; // files the browser shows: textures, and the materials, which are kept with them bool texture_file(std::string const &Extension) { - return Extension == ".dds" || Extension == ".tga" || Extension == ".png" || Extension == ".bmp" || Extension == ".jpg" || Extension == ".ktx" || Extension == ".tex"; + return Extension == ".dds" || Extension == ".ktx2" || Extension == ".tga" || Extension == ".png" || Extension == ".bmp" || Extension == ".jpg" || Extension == ".ktx" || Extension == ".tex"; } std::string lowercase(std::string Text) diff --git a/application/editormodetrackprops.cpp b/application/editormodetrackprops.cpp index fd6c16052..d290648d7 100644 --- a/application/editormodetrackprops.cpp +++ b/application/editormodetrackprops.cpp @@ -139,7 +139,7 @@ std::string lowered(std::string Text) bool texture_extension(std::string const &Extension) { - return Extension == ".dds" || Extension == ".tga" || Extension == ".png" || Extension == ".bmp" || Extension == ".jpg" || Extension == ".ktx" || Extension == ".tex"; + return Extension == ".dds" || Extension == ".ktx2" || Extension == ".tga" || Extension == ".png" || Extension == ".bmp" || Extension == ".jpg" || Extension == ".ktx" || Extension == ".tex"; } // a name in two lines under a tile: as much as fits, then the rest; the end, where the names differ, is kept when the rest is too long diff --git a/model/Texture.cpp b/model/Texture.cpp index d058ca9b2..cf497e9ae 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" #include "scene/sn_utils.h" +#include "model/ktx2.h" #include "rendering/flip-s3tc.h" #include "rendering/common/texturealpha.h" #include "stb/stb_image.h" @@ -30,6 +31,8 @@ http://mozilla.org/MPL/2.0/. #include "winheaders.h" #include +#include +#include #include #define EU07_DEFERRED_TEXTURE_UPLOAD @@ -51,6 +54,10 @@ struct texture_request { int height { 0 }; int mapcount { 0 }; int blocksize { 0 }; + // of a ktx2 file: its image, of which the worker reads mapcount levels from firstlevel on (and unpacks them), flipped if flip + // is set; width and height are those of the first level read + std::optional ktx2image; + std::size_t firstlevel { 0 }; // handed to the workers (texture_source::prefetch()), and when: the main thread only bool submitted { false }; std::chrono::steady_clock::time_point submittime; @@ -61,11 +68,74 @@ struct texture_request { // every texel passes the alpha test of the shadow maps: checked by the worker threads, not by a thread waiting for the data std::optional alphakept; bool failed { false }; + std::string error; // why the data couldn't be read, when the reader knows bool done { false }; // guarded by the mutex of the loader }; namespace { +// what the texture takes of a format of the ktx2 files: the format of its data, and the components it has +struct ktx2_layout { + GLint format; + GLint components; +}; + +ktx2_layout ktx2_layout_of( ktx2::Format const Format ) { + using enum ktx2::Format; + switch( Format ) { + case bc1Rgb: { return { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_RGB }; } + // the 1 bit alpha is cut out by the alpha test, the texture isn't a translucent one: as with the dxt1 dds files + case bc1Rgba: { return { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGB }; } + case bc2: { return { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA }; } + case bc3: { return { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA }; } + case bc4: { return { GL_COMPRESSED_RED_RGTC1, GL_RED }; } + case bc4Signed: { return { GL_COMPRESSED_SIGNED_RED_RGTC1, GL_RED }; } + case bc5: { return { GL_COMPRESSED_RG_RGTC2, GL_RG }; } + case bc5Signed: { return { GL_COMPRESSED_SIGNED_RG_RGTC2, GL_RG }; } + case bc6h: { return { GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, GL_RGB }; } + case bc6hSigned: { return { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, GL_RGB }; } + // whether the texels use the alpha is checked on the data (bc7_components()) + case bc7: { return { GL_COMPRESSED_RGBA_BPTC_UNORM, GL_RGBA }; } + case bgra8: { return { GL_BGRA, GL_RGBA }; } + default: { return { GL_RGBA, GL_RGBA }; } + } } + +// the alpha test of the shadow maps checked on the data of a ktx2 file. the formats without alpha are known to pass it by their +// format alone +std::optional ktx2_alpha_kept( ktx2::Format const Format, std::span const Data ) { + using enum ktx2::Format; + switch( Format ) { + case bc1Rgba: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc1, Data ); } + case bc2: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc2, Data ); } + case bc3: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc3, Data ); } + case bc7: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc7, Data ); } + case rgba8: + case bgra8: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::rgba8, Data ); } + default: { return std::nullopt; } + } } + +// reads the levels of a ktx2 file a request asks for, unpacks and flips them. Check: the alpha of the texels checked too +void read_ktx2( texture_request &Request, bool const Check ) { + auto const &image { *Request.ktx2image }; + Request.data.clear(); + std::ifstream file( Request.file, std::ios::binary ); + if( false == file.is_open() ) { + Request.failed = true; + return; + } + if( false == ktx2::ReadLevels( file, image, Request.firstlevel, static_cast( Request.mapcount ), Request.data, Request.error ) ) { + Request.data = std::vector(); + Request.failed = true; + return; + } + if( Request.flip ) { + ktx2::FlipLevels( image.format, Request.data, static_cast( Request.width ), static_cast( Request.height ), static_cast( Request.mapcount ) ); + } + Request.alphakept.reset(); + if( Check ) { + Request.alphakept = ktx2_alpha_kept( image.format, Request.data ); + } } + // the alpha test of the shadow maps checked on the data of a dds file, block by block of its format std::optional dds_alpha_kept( texture_request const &Request ) { switch( Request.fourcc ) { @@ -163,6 +233,10 @@ private: // same as the reading part of texture_source::load_DDS(). Check: the alpha of the texels checked too (on a worker thread) static void read( texture_request &Request, bool const Check ) { + if( Request.ktx2image.has_value() ) { + read_ktx2( Request, Check ); + return; + } std::ifstream file( Request.file, std::ios::binary ); if( false == file.is_open() ) { Request.failed = true; @@ -316,6 +390,46 @@ GLint bc7_components( std::istream &File, std::streamoff const Start, std::size_ } return GL_RGB; } +// the components of BC7 data held in memory (a level of a ktx2 file), checked as bc7_components() checks a dds file +GLint bc7_components( std::span const Data ) { + for( std::size_t block = 0; block + 16 <= Data.size(); block += 16 ) { + if( bc7_block_has_alpha( &Data[ block ] ) ) { + return GL_RGBA; + } + } + return GL_RGB; } + +// the components of a bc7 ktx2 image: a level of up to 256x256 texels (or the smallest one) checked for translucent texels, as for +// the dds files. the level is read from the file whether the data is streamed or not, so the result doesn't depend on it +GLint ktx2_bc7_components( std::istream &File, ktx2::Description const &Image, std::size_t Level ) { + while( ( Level + 1 < Image.levels.size() ) + && ( std::max( ktx2::LevelExtent( Image.width, Level ), ktx2::LevelExtent( Image.height, Level ) ) > 256 ) ) { + ++Level; + } + std::vector probe; + std::string error; + if( false == ktx2::ReadLevels( File, Image, Level, 1, probe, error ) ) { + // a broken file, erring on the side of translucency like DXT5 does + return GL_RGBA; + } + return bc7_components( probe ); } + +// the first level of a ktx2 image within maxtexturesize, or the count of the levels when none is +std::size_t ktx2_first_level( ktx2::Description const &Image ) { + auto const limit { static_cast( std::max( Global.CurrentMaxTextureSize, 1 ) ) }; + std::size_t level { 0 }; + while( ( level < Image.levels.size() ) + && ( std::max( ktx2::LevelExtent( Image.width, level ), ktx2::LevelExtent( Image.height, level ) ) > limit ) ) { + ++level; + } + return level; } + +// the formats of the bptc extension, BC6H and BC7 +bool is_bptc( GLint const Format ) { + return ( Format == GL_COMPRESSED_RGBA_BPTC_UNORM ) + || ( Format == GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT ) + || ( Format == GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT ); } + // BC7 is core since GL 4.2, older contexts need the extension. requires current gl context bool bptc_supported() { static bool const supported = []() { @@ -346,6 +460,7 @@ GLint readback_format( GLint const Internalformat ) { switch( Internalformat ) { case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: { return GL_COMPRESSED_RGBA8_ETC2_EAC; } case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; } + case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT: { return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; } case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; } case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; } case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM: { return GL_COMPRESSED_RGBA_BPTC_UNORM; } @@ -371,6 +486,15 @@ std::unordered_map texture_source::precompressed_formats = { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 16 }, { GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM, 16 }, { GL_COMPRESSED_RGBA_BPTC_UNORM, 16 }, + // of the ktx2 files only + { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, 8 }, + { GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, 8 }, + { GL_COMPRESSED_RED_RGTC1, 8 }, + { GL_COMPRESSED_SIGNED_RED_RGTC1, 8 }, + { GL_COMPRESSED_RG_RGTC2, 16 }, + { GL_COMPRESSED_SIGNED_RG_RGTC2, 16 }, + { GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, 16 }, + { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, 16 }, }; std::unordered_map opengl_texture::drivercompressed_formats = @@ -416,7 +540,50 @@ std::unordered_map> opengl_texture::mapp { GL_RGB, GL_COMPRESSED_RGBA_BPTC_UNORM }, { GL_RG, GL_COMPRESSED_RGBA_BPTC_UNORM }, { GL_RED, GL_COMPRESSED_RGBA_BPTC_UNORM } } }, - { GL_RGBA, { { GL_SRGB_ALPHA, GL_SRGB8_ALPHA8 }, + // of the ktx2 files only. bc4, bc5 and bc6h have no srgb variants: their values are taken as they are, whatever the material wants + { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, { { GL_SRGB_ALPHA, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT }, + { GL_SRGB, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT }, + { GL_RGBA, GL_COMPRESSED_RGB_S3TC_DXT1_EXT }, + { GL_RGB, GL_COMPRESSED_RGB_S3TC_DXT1_EXT }, + { GL_RG, GL_COMPRESSED_RGB_S3TC_DXT1_EXT }, + { GL_RED, GL_COMPRESSED_RGB_S3TC_DXT1_EXT } } }, + { GL_COMPRESSED_RED_RGTC1, { { GL_SRGB_ALPHA, GL_COMPRESSED_RED_RGTC1 }, + { GL_SRGB, GL_COMPRESSED_RED_RGTC1 }, + { GL_RGBA, GL_COMPRESSED_RED_RGTC1 }, + { GL_RGB, GL_COMPRESSED_RED_RGTC1 }, + { GL_RG, GL_COMPRESSED_RED_RGTC1 }, + { GL_RED, GL_COMPRESSED_RED_RGTC1 } } }, + { GL_COMPRESSED_SIGNED_RED_RGTC1, { { GL_SRGB_ALPHA, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_SRGB, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_RGBA, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_RGB, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_RG, GL_COMPRESSED_SIGNED_RED_RGTC1 }, + { GL_RED, GL_COMPRESSED_SIGNED_RED_RGTC1 } } }, + { GL_COMPRESSED_RG_RGTC2, { { GL_SRGB_ALPHA, GL_COMPRESSED_RG_RGTC2 }, + { GL_SRGB, GL_COMPRESSED_RG_RGTC2 }, + { GL_RGBA, GL_COMPRESSED_RG_RGTC2 }, + { GL_RGB, GL_COMPRESSED_RG_RGTC2 }, + { GL_RG, GL_COMPRESSED_RG_RGTC2 }, + { GL_RED, GL_COMPRESSED_RG_RGTC2 } } }, + { GL_COMPRESSED_SIGNED_RG_RGTC2, { { GL_SRGB_ALPHA, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_SRGB, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_RGBA, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_RGB, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_RG, GL_COMPRESSED_SIGNED_RG_RGTC2 }, + { GL_RED, GL_COMPRESSED_SIGNED_RG_RGTC2 } } }, + { GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, { { GL_SRGB_ALPHA, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_SRGB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_RGBA, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_RGB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_RG, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT }, + { GL_RED, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT } } }, + { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, { { GL_SRGB_ALPHA, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_SRGB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_RGBA, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_RGB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_RG, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT }, + { GL_RED, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT } } }, + { GL_RGBA, { { GL_SRGB_ALPHA, GL_SRGB8_ALPHA8 }, { GL_SRGB, GL_SRGB8 }, { GL_RGBA, GL_RGBA8 }, { GL_RGB, GL_RGB8 }, @@ -483,6 +650,7 @@ texture_source::load() { else if( type == ".tga" ) { load_TGA(); } else if( type == ".png" ) { load_STBI(); } else if( type == ".ktx" ) { load_KTX(); } + else if( type == ".ktx2" ) { load_KTX2(); } else if( type == ".bmp" ) { load_STBI(); } else if( type == ".jpg" ) { load_STBI(); } else if( type == ".tex" ) { load_TEX(); } @@ -1080,6 +1248,78 @@ texture_source::load_KTX() { data_state = resource_state::good; } +// a khronos texture 2.0 file: the levels within maxtexturesize, unpacked (zstd) and with the bottom row first. the material +// decides between srgb and linear colour, as it does for the dds files +void +texture_source::load_KTX2() { + + auto const path { FileOnDisk( name + type ) }; + std::ifstream file( path, std::ios::binary ); + std::string error; + auto image { ktx2::Parse( file, error ) }; + if( false == image.has_value() ) { + ErrorLog( std::format( "Bad texture: \"{}{}\" can't be read: {}", name, type, error ), logtype::texture ); + data_state = resource_state::failed; + return; + } + + auto const first { ktx2_first_level( *image ) }; + if( first == image->levels.size() ) { + WriteLog( std::format( "Texture \"{}\" has no mipmaps which can fit currently set texture pixelcount limits.", name ) ); + data_state = resource_state::failed; + return; + } + if( first > 0 ) { + WriteLog( std::format( "Texture pixelcount exceeds specified limits, skipping {} mipmap level(s) of \"{}\"", first, name ), logtype::texture ); + } + + auto const layout { ktx2_layout_of( image->format ) }; + data_format = layout.format; + data_width = ktx2::LevelExtent( image->width, first ); + data_height = ktx2::LevelExtent( image->height, first ); + // of plain texels only the largest level is taken, the gpu makes the rest as it does for the other image files + auto const count { ktx2::IsCompressed( image->format ) ? image->levels.size() - first : std::size_t { 1 } }; + data_mapcount = static_cast( count ); + data_components = ( + image->format == ktx2::Format::bc7 ? + ktx2_bc7_components( file, *image, first ) : + layout.components ); + + // the data is kept with the bottom row first. the file states where its first row is, and one which doesn't is taken the way + // the dds files are (ddsupperorigin) + auto const topfirst { ( image->origin == ktx2::Origin::top ) || ( ( image->origin == ktx2::Origin::unstated ) && Global.dds_upper_origin ) }; + auto const flip { topfirst && ktx2::CanFlip( image->format ) }; + if( topfirst && ( false == flip ) ) { + WriteLog( std::format( "Warning: BC6H/BC7 texture \"{}\" has its first row at the top and can't be flipped, it's loaded as stored", name ), logtype::texture ); + } + + if( true == Global.gfx_texture_streaming ) { + // the levels are read and unpacked by a worker thread, everything else about the texture is known already + request = std::make_shared(); + request->file = path; + request->flip = flip; + request->width = static_cast( data_width ); + request->height = static_cast( data_height ); + request->mapcount = static_cast( count ); + request->firstlevel = first; + request->ktx2image = std::move( image ); + data_state = resource_state::loading; + return; + } + + data.clear(); + if( false == ktx2::ReadLevels( file, *image, first, count, data, error ) ) { + data = std::vector(); + ErrorLog( std::format( "Bad texture: \"{}{}\": {}", name, type, error ), logtype::texture ); + data_state = resource_state::failed; + return; + } + if( flip ) { + ktx2::FlipLevels( image->format, data, data_width, data_height, count ); + } + data_state = resource_state::good; +} + void texture_source::load_TEX() { @@ -1322,9 +1562,9 @@ opengl_texture::create( bool const Static ) { return false; } - if( ( data_format == GL_COMPRESSED_RGBA_BPTC_UNORM ) + if( is_bptc( data_format ) && ( false == bptc_supported() ) ) { - ErrorLog( "Bad texture: \"" + name + "\" uses BC7 compression, which the graphics driver doesn't support", logtype::texture ); + ErrorLog( std::format( "Bad texture: \"{}\" uses {} compression, which the graphics driver doesn't support", name, ( data_format == GL_COMPRESSED_RGBA_BPTC_UNORM ? "BC7" : "BC6H" ) ), logtype::texture ); data = std::vector(); data_state = resource_state::failed; // NOTE: temporary workaround for texture assignment errors, same as in load() @@ -1476,6 +1716,9 @@ texture_source::complete_data() { if( true == completed->failed ) { data_state = resource_state::failed; + if( false == completed->error.empty() ) { + ErrorLog( std::format( "Bad texture: \"{}{}\": {}", name, type, completed->error ), logtype::texture ); + } ErrorLog( "Bad texture: failed to load texture \"" + name + "\"" ); // NOTE: temporary workaround for texture assignment errors, same as in load() on_failed(); @@ -1517,7 +1760,7 @@ bool texture_source::streamed() const { return ( ( true == Global.gfx_texture_streaming ) - && ( type == ".dds" ) + && ( ( type == ".dds" ) || ( type == ".ktx2" ) ) && ( false == is_rendertarget ) ); } @@ -2184,7 +2427,7 @@ texture_bank::find_on_disk( std::string const &Texturename ) { // if the first attempt fails, try entire extension list // NOTE: slightly wasteful as it means preferred extension is tested twice, but, eh - return FileExists(filenames, {".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex"}); + return FileExists(filenames, {".dds", ".ktx2", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex"}); } //--------------------------------------------------------------------------- diff --git a/model/Texture.h b/model/Texture.h index 0e47d4676..302d0fb25 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -31,11 +31,19 @@ http://mozilla.org/MPL/2.0/. #ifndef GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM #define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D #endif +// BC6H, of the same extension: data_format of BC6H ktx2 files +#ifndef GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E +#endif +#ifndef GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F +#endif struct texture_request; // texture data read by a worker thread, with gfx.textures.streaming -// a texture as its file gives it, whichever api draws it: read and decoded (dds, tga, png, bmp, jpg, ktx, tex), with the mipmaps -// the file has, kept within maxtexturesize; with gfx.textures.streaming the data of a dds file is read by worker threads. the +// a texture as its file gives it, whichever api draws it: read and decoded (dds, ktx2, tga, png, bmp, jpg, ktx, tex), with the +// mipmaps the file has, kept within maxtexturesize; with gfx.textures.streaming the data of a dds or ktx2 file is read (and the +// levels of a ktx2 file packed with zstd unpacked) by worker threads. the // data is laid out as opengl takes it (the bottom row first) and its formats are the values of opengl (GL_RGBA, // GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ...), which the renderers take as they are. a renderer makes its own object of the texture // from the data (create()) @@ -120,6 +128,7 @@ public: void load_PNG(); void load_DDS(); void load_KTX(); + void load_KTX2(); void load_TEX(); void load_STBI(); void load_TGA(); diff --git a/model/ktx2.cpp b/model/ktx2.cpp new file mode 100644 index 000000000..430067ea0 --- /dev/null +++ b/model/ktx2.cpp @@ -0,0 +1,511 @@ +/* +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 "model/ktx2.h" + +#include +#include +#include +#include + +#include "zstd.h" + +namespace ktx2 +{ + +namespace +{ + +// «KTX 20»\r\n\x1A\n +constexpr std::array identifier{0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; +// the identifier, the 9 words of the image and the index of the data format descriptor, the key/value data and the global data +constexpr std::size_t headerBytes{80}; +constexpr std::size_t levelEntryBytes{24}; +constexpr std::uint32_t schemeNone{0}; +constexpr std::uint32_t schemeBasisLz{1}; +constexpr std::uint32_t schemeZstd{2}; +// more levels than an image of 2^31 texels has: a broken file +constexpr std::uint32_t maxLevels{32}; +// the key/value data holds a few short entries; more than this is a broken file +constexpr std::uint32_t maxKeyValueBytes{1u << 20}; + +std::uint32_t readU32(std::span const Bytes, std::size_t const Offset) +{ + return static_cast(Bytes[Offset]) | (static_cast(Bytes[Offset + 1]) << 8) | + (static_cast(Bytes[Offset + 2]) << 16) | (static_cast(Bytes[Offset + 3]) << 24); +} + +std::uint64_t readU64(std::span const Bytes, std::size_t const Offset) +{ + return static_cast(readU32(Bytes, Offset)) | (static_cast(readU32(Bytes, Offset + 4)) << 32); +} + +// reads Out.size() bytes at Offset of the stream; false when the stream ends before +bool readBytes(std::istream &Stream, std::uint64_t const Offset, std::span const Out) +{ + Stream.clear(); + Stream.seekg(static_cast(Offset)); + Stream.read(reinterpret_cast(Out.data()), static_cast(Out.size())); + return Stream.gcount() == static_cast(Out.size()); +} + +std::uint64_t streamBytes(std::istream &Stream) +{ + Stream.clear(); + Stream.seekg(0, std::ios::end); + auto const end{static_cast(Stream.tellg())}; + return end < 0 ? 0 : static_cast(end); +} + +// whether Length bytes at Offset are within a file of FileBytes +bool fits(std::uint64_t const Offset, std::uint64_t const Length, std::uint64_t const FileBytes) +{ + return (Length <= FileBytes) && (Offset <= FileBytes - Length); +} + +struct FormatEntry +{ + std::uint32_t vkFormat; + Format format; + bool srgb; +}; + +// the values of VkFormat the game takes +constexpr std::array formats{ + FormatEntry{37, Format::rgba8, false}, // VK_FORMAT_R8G8B8A8_UNORM + FormatEntry{43, Format::rgba8, true}, // VK_FORMAT_R8G8B8A8_SRGB + FormatEntry{44, Format::bgra8, false}, // VK_FORMAT_B8G8R8A8_UNORM + FormatEntry{50, Format::bgra8, true}, // VK_FORMAT_B8G8R8A8_SRGB + FormatEntry{131, Format::bc1Rgb, false}, // VK_FORMAT_BC1_RGB_UNORM_BLOCK + FormatEntry{132, Format::bc1Rgb, true}, + FormatEntry{133, Format::bc1Rgba, false}, // VK_FORMAT_BC1_RGBA_UNORM_BLOCK + FormatEntry{134, Format::bc1Rgba, true}, + FormatEntry{135, Format::bc2, false}, // VK_FORMAT_BC2_UNORM_BLOCK + FormatEntry{136, Format::bc2, true}, + FormatEntry{137, Format::bc3, false}, // VK_FORMAT_BC3_UNORM_BLOCK + FormatEntry{138, Format::bc3, true}, + FormatEntry{139, Format::bc4, false}, // VK_FORMAT_BC4_UNORM_BLOCK + FormatEntry{140, Format::bc4Signed, false}, + FormatEntry{141, Format::bc5, false}, // VK_FORMAT_BC5_UNORM_BLOCK + FormatEntry{142, Format::bc5Signed, false}, + FormatEntry{143, Format::bc6h, false}, // VK_FORMAT_BC6H_UFLOAT_BLOCK + FormatEntry{144, Format::bc6hSigned, false}, + FormatEntry{145, Format::bc7, false}, // VK_FORMAT_BC7_UNORM_BLOCK + FormatEntry{146, Format::bc7, true}, +}; + +// the words of the header the description is made of +struct Header +{ + std::uint32_t vkFormat{0}; + std::uint32_t width{0}; + std::uint32_t height{0}; + std::uint32_t depth{0}; + std::uint32_t layers{0}; + std::uint32_t faces{0}; + std::uint32_t levels{0}; + std::uint32_t scheme{0}; + std::uint32_t keyValueOffset{0}; + std::uint32_t keyValueLength{0}; + + explicit Header(std::span const Bytes) + : vkFormat{readU32(Bytes, 12)}, width{readU32(Bytes, 20)}, height{readU32(Bytes, 24)}, depth{readU32(Bytes, 28)}, + layers{readU32(Bytes, 32)}, faces{readU32(Bytes, 36)}, levels{readU32(Bytes, 40)}, scheme{readU32(Bytes, 44)}, + keyValueOffset{readU32(Bytes, 56)}, keyValueLength{readU32(Bytes, 60)} + { + } + + // why the game can't take the image the header describes, empty when it can + std::string shapeError() const + { + if ((width == 0) || (height == 0)) + { + return "the image isn't a 2d one"; + } + if (depth != 0) + { + return "3d images aren't supported"; + } + if (layers > 1) + { + return "arrays of images aren't supported"; + } + if (faces != 1) + { + return "cube maps aren't supported"; + } + if (levels > maxLevels) + { + return std::format("it gives {} levels", levels); + } + return {}; + } +}; + +std::optional supercompressionOf(std::uint32_t const Scheme, std::string &Error) +{ + if (Scheme == schemeNone) + { + return Supercompression::none; + } + if (Scheme == schemeZstd) + { + return Supercompression::zstd; + } + Error = (Scheme == schemeBasisLz ? std::string{"basis universal (basislz) isn't supported"} : std::format("its supercompression scheme {} isn't supported", Scheme)); + return std::nullopt; +} + +// what the key/value data says of the first row of the levels +Origin originOf(std::span const KeyValues) +{ + std::string_view const orientationKey{"KTXorientation"}; + std::size_t offset{0}; + while (offset + 4 <= KeyValues.size()) + { + auto const length{static_cast(readU32(KeyValues, offset))}; + offset += 4; + if (length > KeyValues.size() - offset) + { + // a broken entry, nothing after it can be trusted + return Origin::unstated; + } + std::string_view const entry{reinterpret_cast(KeyValues.data() + offset), length}; + // each entry is padded to 4 bytes + offset += (length + 3) & ~std::size_t{3}; + auto const keyEnd{entry.find('\0')}; + if ((keyEnd == std::string_view::npos) || (entry.substr(0, keyEnd) != orientationKey)) + { + continue; + } + // "rd" for the first row at the top, "ru" for the first row at the bottom + auto const value{entry.substr(keyEnd + 1)}; + if (value.size() < 2) + { + return Origin::unstated; + } + if (value[1] == 'u') + { + return Origin::bottom; + } + return (value[1] == 'd' ? Origin::top : Origin::unstated); + } + return Origin::unstated; +} + +// the levels of the index, checked against the size of the file and of the image +bool readLevelIndex(std::istream &Stream, Header const &Head, std::uint64_t const FileBytes, Description &Image, std::string &Error) +{ + auto const count{std::max(Head.levels, 1)}; + std::vector index(static_cast(count) * levelEntryBytes); + if (false == readBytes(Stream, headerBytes, index)) + { + Error = "the file is shorter than its index of levels"; + return false; + } + for (std::size_t level = 0; level < count; ++level) + { + auto const entry{level * levelEntryBytes}; + Level const read{readU64(index, entry), readU64(index, entry + 8), readU64(index, entry + 16)}; + if (false == fits(read.offset, read.length, FileBytes)) + { + Error = std::format("level {} is past the end of the file", level); + return false; + } + auto const expected{LevelBytes(Image.format, LevelExtent(Image.width, level), LevelExtent(Image.height, level))}; + // the level packed with zstd is unpacked into a buffer of the size the file gives, which has to be the size of the level + auto const whole{Image.supercompression == Supercompression::none ? read.length >= expected : read.uncompressedLength == expected}; + if (false == whole) + { + Error = std::format("level {} doesn't hold the {} bytes of its texels", level, expected); + return false; + } + Image.levels.push_back(read); + } + return true; +} + +// the rows of the indices of a bc1 colour block (a byte each) swapped, the first Rows of them +void flipColourRows(std::span const Block, std::uint32_t const Rows) +{ + std::ranges::reverse(Block.subspan(4, Rows)); +} + +// the rows of the explicit alpha of a bc2 block (16 bits each) swapped +void flipExplicitAlphaRows(std::span const Block, std::uint32_t const Rows) +{ + for (std::uint32_t row = 0; row < Rows / 2; ++row) + { + std::ranges::swap_ranges(Block.subspan(row * 2, 2), Block.subspan((Rows - 1 - row) * 2, 2)); + } +} + +// the rows of the indices of a bc4 block (12 bits each, after the two end points) swapped. a bc3 alpha and each half of bc5 are such a block +void flipBc4Rows(std::span const Block, std::uint32_t const Rows) +{ + std::uint64_t bits{0}; + for (std::size_t idx = 0; idx < 6; ++idx) + { + bits |= static_cast(Block[2 + idx]) << (8 * idx); + } + std::array rows{}; + for (std::size_t row = 0; row < rows.size(); ++row) + { + rows[row] = (bits >> (12 * row)) & 0xfff; + } + std::ranges::reverse(std::span{rows}.first(Rows)); + std::uint64_t flipped{0}; + for (std::size_t row = 0; row < rows.size(); ++row) + { + flipped |= rows[row] << (12 * row); + } + for (std::size_t idx = 0; idx < 6; ++idx) + { + Block[2 + idx] = static_cast((flipped >> (8 * idx)) & 0xff); + } +} + +void flipBlock(Format const Value, std::span const Block, std::uint32_t const Rows) +{ + using enum Format; + switch (Value) + { + case bc1Rgb: + case bc1Rgba: + flipColourRows(Block, Rows); + break; + case bc2: + flipExplicitAlphaRows(Block.first(8), Rows); + flipColourRows(Block.subspan(8), Rows); + break; + case bc3: + flipBc4Rows(Block.first(8), Rows); + flipColourRows(Block.subspan(8), Rows); + break; + case bc4: + case bc4Signed: + flipBc4Rows(Block, Rows); + break; + case bc5: + case bc5Signed: + flipBc4Rows(Block.first(8), Rows); + flipBc4Rows(Block.subspan(8), Rows); + break; + default: + break; + } +} + +// the rows of Data, RowBytes each, in the reverse order +void swapRows(std::span const Data, std::size_t const RowBytes, std::uint32_t const Rows) +{ + for (std::uint32_t row = 0; row < Rows / 2; ++row) + { + std::ranges::swap_ranges(Data.subspan(row * RowBytes, RowBytes), Data.subspan((Rows - 1 - row) * RowBytes, RowBytes)); + } +} + +void flipLevel(Format const Value, std::span const Level, std::uint32_t const Width, std::uint32_t const Height) +{ + if (false == IsCompressed(Value)) + { + swapRows(Level, static_cast(Width) * BlockBytes(Value), Height); + return; + } + auto const blockBytes{BlockBytes(Value)}; + auto const blockRows{(Height + 3) / 4}; + // a level lower than a block holds only its first rows of texels. (a height above 4 which isn't a multiple of 4 would need the + // texels moved across the blocks: such a level is flipped block by block, as the dds files are) + auto const texelRows{std::min(Height, 4u)}; + for (std::size_t offset = 0; offset + blockBytes <= Level.size(); offset += blockBytes) + { + flipBlock(Value, Level.subspan(offset, blockBytes), texelRows); + } + swapRows(Level, static_cast((Width + 3) / 4) * blockBytes, blockRows); +} + +// reads the level Index of the image and appends it to Data. Packed: a buffer for the data of a level packed with zstd +bool readLevel(std::istream &Stream, Description const &Image, std::size_t const Index, std::vector &Packed, std::vector &Data, std::string &Error) +{ + auto const &level{Image.levels[Index]}; + auto const expected{static_cast(LevelBytes(Image.format, LevelExtent(Image.width, Index), LevelExtent(Image.height, Index)))}; + auto const start{Data.size()}; + Data.resize(start + expected); + auto const target{std::span{Data}.subspan(start)}; + if (Image.supercompression == Supercompression::none) + { + if (false == readBytes(Stream, level.offset, target)) + { + Data.resize(start); + Error = std::format("level {} couldn't be read", Index); + return false; + } + return true; + } + Packed.resize(static_cast(level.length)); + if (false == readBytes(Stream, level.offset, Packed)) + { + Data.resize(start); + Error = std::format("level {} couldn't be read", Index); + return false; + } + auto const unpacked{ZSTD_decompress(target.data(), target.size(), Packed.data(), Packed.size())}; + if ((ZSTD_isError(unpacked) != 0) || (unpacked != expected)) + { + Data.resize(start); + Error = std::format("level {} couldn't be unpacked", Index); + return false; + } + return true; +} + +} // namespace + +std::optional Parse(std::istream &Stream, std::string &Error) +{ + auto const fileBytes{streamBytes(Stream)}; + std::array bytes{}; + if (false == readBytes(Stream, 0, bytes)) + { + Error = "the file is shorter than the header"; + return std::nullopt; + } + if (false == std::ranges::equal(std::span{bytes}.first(identifier.size()), identifier)) + { + Error = "it isn't a ktx2 file"; + return std::nullopt; + } + Header const head{bytes}; + Error = head.shapeError(); + if (false == Error.empty()) + { + return std::nullopt; + } + auto const format{std::ranges::find(formats, head.vkFormat, &FormatEntry::vkFormat)}; + if (format == formats.end()) + { + Error = (head.vkFormat == 0 ? std::string{"basis universal (or no stated format) isn't supported"} : std::format("its format (vkFormat {}) isn't supported", head.vkFormat)); + return std::nullopt; + } + auto const supercompression{supercompressionOf(head.scheme, Error)}; + if (false == supercompression.has_value()) + { + return std::nullopt; + } + + Description image; + image.format = format->format; + image.srgb = format->srgb; + image.width = head.width; + image.height = head.height; + image.supercompression = *supercompression; + if (false == readLevelIndex(Stream, head, fileBytes, image, Error)) + { + return std::nullopt; + } + // the orientation is optional: data which can't be read is taken for none + if ((head.keyValueLength > 0) && (head.keyValueLength <= maxKeyValueBytes) && fits(head.keyValueOffset, head.keyValueLength, fileBytes)) + { + std::vector keyValues(head.keyValueLength); + if (readBytes(Stream, head.keyValueOffset, keyValues)) + { + image.origin = originOf(keyValues); + } + } + Error.clear(); + return image; +} + +bool IsCompressed(Format const Value) +{ + return (Value != Format::rgba8) && (Value != Format::bgra8); +} + +std::uint32_t BlockBytes(Format const Value) +{ + using enum Format; + switch (Value) + { + case bc1Rgb: + case bc1Rgba: + case bc4: + case bc4Signed: + return 8; + case rgba8: + case bgra8: + return 4; + default: + return 16; + } +} + +std::uint64_t LevelBytes(Format const Value, std::uint32_t const Width, std::uint32_t const Height) +{ + if (false == IsCompressed(Value)) + { + return static_cast(Width) * Height * BlockBytes(Value); + } + return static_cast((Width + 3) / 4) * ((Height + 3) / 4) * BlockBytes(Value); +} + +std::uint32_t LevelExtent(std::uint32_t const Extent, std::size_t const Level) +{ + if (Level >= 32) + { + return 1; + } + return std::max(Extent >> Level, 1u); +} + +bool ReadLevels(std::istream &Stream, Description const &Image, std::size_t const First, std::size_t const Count, std::vector &Data, std::string &Error) +{ + if ((First > Image.levels.size()) || (Count > Image.levels.size() - First)) + { + Error = std::format("the file has no level {}", First + Count - 1); + return false; + } + std::vector packed; + for (auto index = First; index < First + Count; ++index) + { + if (false == readLevel(Stream, Image, index, packed, Data, Error)) + { + return false; + } + } + return true; +} + +bool CanFlip(Format const Value) +{ + return (Value != Format::bc6h) && (Value != Format::bc6hSigned) && (Value != Format::bc7); +} + +void FlipLevels(Format const Value, std::span const Data, std::uint32_t const Width, std::uint32_t const Height, std::size_t const Count) +{ + if (false == CanFlip(Value)) + { + return; + } + std::size_t offset{0}; + for (std::size_t level = 0; level < Count; ++level) + { + auto const width{LevelExtent(Width, level)}; + auto const height{LevelExtent(Height, level)}; + auto const bytes{static_cast(LevelBytes(Value, width, height))}; + if (bytes > Data.size() - offset) + { + return; + } + flipLevel(Value, Data.subspan(offset, bytes), width, height); + offset += bytes; + } +} + +} // namespace ktx2 diff --git a/model/ktx2.h b/model/ktx2.h new file mode 100644 index 000000000..5a2ae2f57 --- /dev/null +++ b/model/ktx2.h @@ -0,0 +1,105 @@ +/* +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 + +// the khronos texture 2.0 files (.ktx2) the game takes: a 2d image with its mipmaps, of the bc formats (bc1 to bc7) or of plain +// rgba / bgra bytes, its levels stored as they are or packed with zstd. the files hold the levels the way vulkan takes them; what +// the renderers make of them is the matter of texture_source::load_KTX2() (model/Texture.cpp). the code here knows nothing of +// opengl or vulkan, so that it can be tested on its own +namespace ktx2 +{ + +// the formats of the texels the game takes from the files (vkFormat of the header) +enum class Format +{ + bc1Rgb, // no alpha + bc1Rgba, // 1 bit alpha + bc2, + bc3, + bc4, // one channel (red) + bc4Signed, + bc5, // two channels (red, green): normal maps + bc5Signed, + bc6h, // hdr colour, no alpha + bc6hSigned, + bc7, + rgba8, + bgra8 +}; + +// how the levels are stored in the file +enum class Supercompression +{ + none, + zstd +}; + +// where the file says the first row of a level is (the KTXorientation key) +enum class Origin +{ + unstated, + top, // "rd", what the format holds by default + bottom // "ru" +}; + +// a level of the image in the file: where its data is, how many bytes it takes there and how many unpacked +struct Level +{ + std::uint64_t offset{0}; + std::uint64_t length{0}; + std::uint64_t uncompressedLength{0}; +}; + +// what the header of a file tells of its image +struct Description +{ + Format format{Format::rgba8}; + bool srgb{false}; // the file states srgb colour (the material decides it in the game, as it does for the dds files) + std::uint32_t width{0}; + std::uint32_t height{0}; + Supercompression supercompression{Supercompression::none}; + Origin origin{Origin::unstated}; + std::vector levels; // the largest first +}; + +// the description of the image of a file, or nothing and the reason in Error when the game can't take it. reads the header, the +// index of the levels and the key/value data; the levels themselves aren't read +std::optional Parse(std::istream &Stream, std::string &Error); + +// whether the format is made of the 4x4 blocks +bool IsCompressed(Format Value); +// the bytes of a 4x4 block of a compressed format, of a texel of the others +std::uint32_t BlockBytes(Format Value); +// the bytes the data of a level of the given size takes +std::uint64_t LevelBytes(Format Value, std::uint32_t Width, std::uint32_t Height); +// the size of a level +std::uint32_t LevelExtent(std::uint32_t Extent, std::size_t Level); + +// appends the data of Count levels of the image, from the level First on, to Data: read from the file and unpacked. false and the +// reason in Error when the file doesn't hold them whole +bool ReadLevels(std::istream &Stream, Description const &Image, std::size_t First, std::size_t Count, std::vector &Data, std::string &Error); + +// whether the rows of the format can be turned upside down without decoding it: not those of bc6h and bc7, whose blocks are +// split into parts in many ways +bool CanFlip(Format Value); +// turns the rows of Count levels, one after another in Data and the first of the given size, upside down. of a compressed level the +// rows of its blocks swap places and the rows of texels inside each block too; a level lower than a block has only its rows of +// texels swapped, the rest of the block isn't drawn +void FlipLevels(Format Value, std::span Data, std::uint32_t Width, std::uint32_t Height, std::size_t Count); + +} // namespace ktx2 diff --git a/model/materialdata.cpp b/model/materialdata.cpp index 8d026d71a..7c4c13bb7 100644 --- a/model/materialdata.cpp +++ b/model/materialdata.cpp @@ -23,7 +23,7 @@ TextureTest( std::string const &Name ) { auto const lookup { FileExists( { Global.asCurrentTexturePath + Name, Name, paths::textures + Name }, - { ".mat", ".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex" } ) }; + { ".mat", ".dds", ".ktx2", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex" } ) }; return lookup.first + lookup.second; } diff --git a/rendering/vulkan14/vulkan14texture.cpp b/rendering/vulkan14/vulkan14texture.cpp index c0d469fe6..ff6951298 100644 --- a/rendering/vulkan14/vulkan14texture.cpp +++ b/rendering/vulkan14/vulkan14texture.cpp @@ -498,10 +498,50 @@ void image_table::clear() // formats +namespace +{ + +// the compressed formats only the ktx2 files give, which hold no alpha: it reads 1 as it does in opengl, so the alpha test of the +// shadow maps keeps every texel. bc4, bc5 and bc6h have no srgb variants, their values are taken as they are (as in the opengl +// renderer). nothing for the other formats +std::optional alphaless_format_of(GLint const Format, bool const Srgb) +{ + texture_format result; + result.compressed = true; + result.components.a = VK_COMPONENT_SWIZZLE_ONE; + switch (Format) + { + case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT: + case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: + result.format = ((Srgb || (Format == GL_COMPRESSED_SRGB_S3TC_DXT1_EXT)) ? VK_FORMAT_BC1_RGB_SRGB_BLOCK : VK_FORMAT_BC1_RGB_UNORM_BLOCK); + result.block_bytes = 8; + return result; + case GL_COMPRESSED_RED_RGTC1: + case GL_COMPRESSED_SIGNED_RED_RGTC1: + result.format = (Format == GL_COMPRESSED_RED_RGTC1 ? VK_FORMAT_BC4_UNORM_BLOCK : VK_FORMAT_BC4_SNORM_BLOCK); + result.block_bytes = 8; + return result; + case GL_COMPRESSED_RG_RGTC2: + case GL_COMPRESSED_SIGNED_RG_RGTC2: + result.format = (Format == GL_COMPRESSED_RG_RGTC2 ? VK_FORMAT_BC5_UNORM_BLOCK : VK_FORMAT_BC5_SNORM_BLOCK); + result.block_bytes = 16; + return result; + case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT: + case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT: + result.format = (Format == GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT ? VK_FORMAT_BC6H_UFLOAT_BLOCK : VK_FORMAT_BC6H_SFLOAT_BLOCK); + result.block_bytes = 16; + return result; + default: + return std::nullopt; + } +} + +} // namespace + texture_format texture_format_of(GLint Format, GLint Hint) { // (etc2 of the ktx files isn't mapped: the desktop gpus don't sample it, and the feature isn't enabled on the device; the - // opengl driver decodes it) + // opengl driver decodes it. the bc formats of the ktx2 files are: all of them are part of textureCompressionBC) // the material wants srgb colours (the default), or values: the compressed formats keep their alpha either way, as in the // opengl renderer (opengl_texture::mapping) auto const srgb{(Hint == 0) || (Hint == GL_SRGB_ALPHA) || (Hint == GL_SRGB)}; @@ -533,6 +573,15 @@ texture_format texture_format_of(GLint Format, GLint Hint) result.compressed = true; result.block_bytes = 16; return result; + default: + break; + } + if (auto const alphaless{alphaless_format_of(Format, srgb)}; alphaless.has_value()) + { + return *alphaless; + } + switch (Format) + { case GL_RGBA: case GL_BGRA: case GL_RGB: diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 44684b79b..65ce5d5c6 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -34,6 +34,9 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" # which textures the shadow maps draw without the alpha test "${CMAKE_SOURCE_DIR}/rendering/common/texturealpha.cpp" + # and the ktx2 texture files, with the zstd their levels are packed with + "${CMAKE_SOURCE_DIR}/model/ktx2.cpp" + "${DEPS_DIR}/zstd/zstd.c" # and the movement of the free camera the motion blur takes "${CMAKE_SOURCE_DIR}/rendering/common/freecameramotion.cpp" # and the http client the editor fetches its aids with diff --git a/tests/unit/test_ktx2.cpp b/tests/unit/test_ktx2.cpp new file mode 100644 index 000000000..1bf5bbc81 --- /dev/null +++ b/tests/unit/test_ktx2.cpp @@ -0,0 +1,419 @@ +#include "stdafx.h" +#include "doctest.h" +#include "model/ktx2.h" + +#include "zstd.h" + +#include +#include +#include +#include +#include +#include + +// the khronos texture 2.0 files the game reads: what the header tells, the levels read and unpacked from zstd, and the rows of the +// bc formats turned upside down without decoding them +namespace +{ + +using Bytes = std::vector; + +// a file made for a test: the levels are stored the smallest first, after the header, the index and the key/value data, as the +// tools write them +struct TestFile +{ + std::uint32_t vkFormat{145}; // VK_FORMAT_BC7_UNORM_BLOCK + std::uint32_t width{16}; + std::uint32_t height{16}; + std::uint32_t depth{0}; + std::uint32_t faces{1}; + std::uint32_t scheme{0}; + std::string orientation; // the value of KTXorientation, no key when empty + std::vector levels; // the data stored of each level, the largest first + std::vector unpacked; // the sizes of the levels packed with zstd, unpacked + std::uint64_t levelOffsetShift{0}; // moves the data of the levels in the index, for a broken file +}; + +void put32(std::string &Out, std::uint32_t const Value) +{ + for (int shift = 0; shift < 32; shift += 8) + { + Out.push_back(static_cast((Value >> shift) & 0xff)); + } +} + +void put64(std::string &Out, std::uint64_t const Value) +{ + put32(Out, static_cast(Value & 0xffffffffu)); + put32(Out, static_cast(Value >> 32)); +} + +std::string keyValues(std::string const &Orientation) +{ + std::string out; + if (Orientation.empty()) + { + return out; + } + std::string entry{"KTXorientation"}; + entry.push_back('\0'); + entry += Orientation; + entry.push_back('\0'); + put32(out, static_cast(entry.size())); + out += entry; + out.resize((out.size() + 3) & ~std::size_t{3}, '\0'); + return out; +} + +std::string write(TestFile const &File) +{ + auto const kvd{keyValues(File.orientation)}; + auto const count{File.levels.size()}; + auto const kvdOffset{80 + 24 * count}; + // the data of the levels, the smallest first + std::vector offsets(count); + auto position{kvdOffset + kvd.size()}; + for (auto level = count; level-- > 0;) + { + offsets[level] = position; + position += File.levels[level].size(); + } + + std::string out{"\xAB\x4B\x54\x58\x20\x32\x30\xBB\x0D\x0A\x1A\x0A", 12}; + put32(out, File.vkFormat); + put32(out, 1); // typeSize + put32(out, File.width); + put32(out, File.height); + put32(out, File.depth); + put32(out, 0); // layerCount + put32(out, File.faces); + put32(out, static_cast(count)); + put32(out, File.scheme); + put32(out, 0); // dfdByteOffset: the descriptor isn't read + put32(out, 0); + put32(out, kvd.empty() ? 0 : static_cast(kvdOffset)); + put32(out, static_cast(kvd.size())); + put64(out, 0); // sgdByteOffset + put64(out, 0); + for (std::size_t level = 0; level < count; ++level) + { + put64(out, offsets[level] + File.levelOffsetShift); + put64(out, File.levels[level].size()); + put64(out, File.unpacked.empty() ? File.levels[level].size() : File.unpacked[level]); + } + out += kvd; + for (auto level = count; level-- > 0;) + { + out.append(reinterpret_cast(File.levels[level].data()), File.levels[level].size()); + } + return out; +} + +// data of the given size made of a running count, different in each level +Bytes counting(std::size_t const Size, std::uint8_t const Start) +{ + Bytes out(Size); + std::iota(out.begin(), out.end(), Start); + return out; +} + +Bytes pack(Bytes const &Data) +{ + Bytes out(ZSTD_compressBound(Data.size())); + auto const size{ZSTD_compress(out.data(), out.size(), Data.data(), Data.size(), 3)}; + REQUIRE(ZSTD_isError(size) == 0); + out.resize(size); + return out; +} + +std::optional parse(std::string const &Content, std::string &Error) +{ + std::istringstream stream{Content}; + return ktx2::Parse(stream, Error); +} + +// the bc7 file of a 16x16 image with its three levels down to a block +TestFile bc7File() +{ + TestFile file; + file.levels = {counting(16 * 16, 0), counting(4 * 16, 1), counting(16, 2)}; + return file; +} + +} // namespace + +TEST_CASE("ktx2: the header of a bc7 file describes its image and levels") +{ + auto file{bc7File()}; + file.vkFormat = 146; // VK_FORMAT_BC7_SRGB_BLOCK + std::string error; + auto const image{parse(write(file), error)}; + REQUIRE_MESSAGE(image.has_value(), error); + CHECK(image->format == ktx2::Format::bc7); + CHECK(image->srgb); + CHECK(image->width == 16); + CHECK(image->height == 16); + CHECK(image->supercompression == ktx2::Supercompression::none); + CHECK(image->origin == ktx2::Origin::unstated); + REQUIRE(image->levels.size() == 3); + CHECK(image->levels[0].length == 256); + CHECK(image->levels[2].length == 16); +} + +TEST_CASE("ktx2: the levels are read the largest first, from where the index puts them") +{ + auto const file{bc7File()}; + auto const content{write(file)}; + std::string error; + auto const image{parse(content, error)}; + REQUIRE(image.has_value()); + + std::istringstream stream{content}; + Bytes data; + REQUIRE_MESSAGE(ktx2::ReadLevels(stream, *image, 0, 3, data, error), error); + Bytes expected; + for (auto const &level : file.levels) + { + expected.insert(expected.end(), level.begin(), level.end()); + } + CHECK(data == expected); + + // the levels past those too large for the game, appended to what's there + Bytes tail{9}; + REQUIRE(ktx2::ReadLevels(stream, *image, 1, 2, tail, error)); + CHECK(tail.size() == 1 + 64 + 16); + CHECK(tail[0] == 9); + CHECK(tail[1] == file.levels[1][0]); + CHECK_FALSE(ktx2::ReadLevels(stream, *image, 2, 2, tail, error)); +} + +TEST_CASE("ktx2: levels packed with zstd are unpacked") +{ + TestFile file; + file.vkFormat = 133; // VK_FORMAT_BC1_RGBA_UNORM_BLOCK + file.width = 8; + file.height = 8; + file.scheme = 2; + std::vector const plain{counting(4 * 8, 10), counting(8, 20), counting(8, 30), counting(8, 40)}; + for (auto const &level : plain) + { + file.levels.push_back(pack(level)); + file.unpacked.push_back(level.size()); + } + auto const content{write(file)}; + std::string error; + auto const image{parse(content, error)}; + REQUIRE_MESSAGE(image.has_value(), error); + CHECK(image->format == ktx2::Format::bc1Rgba); + CHECK_FALSE(image->srgb); + CHECK(image->supercompression == ktx2::Supercompression::zstd); + + std::istringstream stream{content}; + Bytes data; + REQUIRE_MESSAGE(ktx2::ReadLevels(stream, *image, 0, 4, data, error), error); + Bytes expected; + for (auto const &level : plain) + { + expected.insert(expected.end(), level.begin(), level.end()); + } + CHECK(data == expected); +} + +TEST_CASE("ktx2: a level which doesn't unpack fails to be read and leaves the data as it was") +{ + TestFile file; + file.vkFormat = 141; // VK_FORMAT_BC5_UNORM_BLOCK + file.width = 4; + file.height = 4; + file.scheme = 2; + file.levels = {Bytes(16, 0x55)}; // not zstd + file.unpacked = {16}; + auto const content{write(file)}; + std::string error; + auto const image{parse(content, error)}; + REQUIRE(image.has_value()); + std::istringstream stream{content}; + Bytes data{1, 2}; + CHECK_FALSE(ktx2::ReadLevels(stream, *image, 0, 1, data, error)); + CHECK(data == Bytes{1, 2}); + CHECK_FALSE(error.empty()); +} + +TEST_CASE("ktx2: the orientation key tells where the first row is") +{ + auto file{bc7File()}; + std::string error; + file.orientation = "rd"; + CHECK(parse(write(file), error)->origin == ktx2::Origin::top); + file.orientation = "ru"; + CHECK(parse(write(file), error)->origin == ktx2::Origin::bottom); + file.orientation = "r"; + CHECK(parse(write(file), error)->origin == ktx2::Origin::unstated); +} + +TEST_CASE("ktx2: the formats of the bc family and plain bytes are known") +{ + struct Case + { + std::uint32_t vkFormat; + ktx2::Format format; + bool srgb; + }; + std::array const cases{Case{37, ktx2::Format::rgba8, false}, Case{50, ktx2::Format::bgra8, true}, Case{132, ktx2::Format::bc1Rgb, true}, + Case{135, ktx2::Format::bc2, false}, Case{138, ktx2::Format::bc3, true}, Case{139, ktx2::Format::bc4, false}, + Case{140, ktx2::Format::bc4Signed, false}, Case{142, ktx2::Format::bc5Signed, false}, Case{143, ktx2::Format::bc6h, false}, + Case{144, ktx2::Format::bc6hSigned, false}}; + for (auto const &item : cases) + { + CAPTURE(item.vkFormat); + TestFile file; + file.vkFormat = item.vkFormat; + file.width = 4; + file.height = 4; + file.levels = {Bytes(ktx2::LevelBytes(item.format, 4, 4))}; + std::string error; + auto const image{parse(write(file), error)}; + REQUIRE_MESSAGE(image.has_value(), error); + CHECK(image->format == item.format); + CHECK(image->srgb == item.srgb); + } +} + +TEST_CASE("ktx2: files the game can't take are refused with the reason") +{ + std::string error; + SUBCASE("not a ktx2 file") + { + auto content{write(bc7File())}; + content[5] = '1'; // "KTX 10" + CHECK_FALSE(parse(content, error).has_value()); + } + SUBCASE("cut short in the header") + { + CHECK_FALSE(parse(write(bc7File()).substr(0, 40), error).has_value()); + } + SUBCASE("basis universal") + { + auto file{bc7File()}; + file.vkFormat = 0; + file.scheme = 1; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("basislz supercompression") + { + auto file{bc7File()}; + file.scheme = 1; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("an unknown format") + { + auto file{bc7File()}; + file.vkFormat = 147; // VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a cube map") + { + auto file{bc7File()}; + file.faces = 6; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a 3d image") + { + auto file{bc7File()}; + file.depth = 4; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a level past the end of the file") + { + auto file{bc7File()}; + file.levelOffsetShift = 1000; + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a level shorter than its texels") + { + auto file{bc7File()}; + file.levels[1].resize(32); + CHECK_FALSE(parse(write(file), error).has_value()); + } + SUBCASE("a packed level which unpacks to another size") + { + auto file{bc7File()}; + file.scheme = 2; + file.unpacked = {256, 64, 32}; + CHECK_FALSE(parse(write(file), error).has_value()); + } + CHECK_FALSE(error.empty()); +} + +TEST_CASE("ktx2: the sizes of the levels") +{ + CHECK(ktx2::LevelExtent(16, 0) == 16); + CHECK(ktx2::LevelExtent(16, 3) == 2); + CHECK(ktx2::LevelExtent(16, 7) == 1); + CHECK(ktx2::LevelExtent(16, 40) == 1); + CHECK(ktx2::LevelBytes(ktx2::Format::bc1Rgb, 8, 8) == 32); + CHECK(ktx2::LevelBytes(ktx2::Format::bc1Rgb, 2, 1) == 8); + CHECK(ktx2::LevelBytes(ktx2::Format::bc5, 8, 4) == 32); + CHECK(ktx2::LevelBytes(ktx2::Format::bc7, 1, 1) == 16); + CHECK(ktx2::LevelBytes(ktx2::Format::rgba8, 3, 2) == 24); +} + +TEST_CASE("ktx2: the rows of a bc1 image are turned upside down block by block") +{ + // a 4x8 image: two blocks one above the other, each with its colours and a row of indices per texel row + Bytes data{0x11, 0x11, 0x22, 0x22, 0x00, 0x01, 0x02, 0x03, 0x33, 0x33, 0x44, 0x44, 0x10, 0x11, 0x12, 0x13}; + ktx2::FlipLevels(ktx2::Format::bc1Rgb, data, 4, 8, 1); + CHECK(data == Bytes{0x33, 0x33, 0x44, 0x44, 0x13, 0x12, 0x11, 0x10, 0x11, 0x11, 0x22, 0x22, 0x03, 0x02, 0x01, 0x00}); + + // a level of 2 rows has only those swapped, the rest of the block isn't drawn + Bytes lowLevel{0x11, 0x11, 0x22, 0x22, 0x00, 0x01, 0x02, 0x03}; + ktx2::FlipLevels(ktx2::Format::bc1Rgba, lowLevel, 2, 2, 1); + CHECK(lowLevel == Bytes{0x11, 0x11, 0x22, 0x22, 0x01, 0x00, 0x02, 0x03}); +} + +TEST_CASE("ktx2: the rows of the alpha and of the channels of bc2 to bc5 are swapped") +{ + // a bc4 block of 4 rows of 12 bit indices: 0x001, 0x002, 0x003, 0x004 + Bytes const bc4{0xff, 0x00, 0x01, 0x20, 0x00, 0x03, 0x40, 0x00}; + auto flipped{bc4}; + ktx2::FlipLevels(ktx2::Format::bc4, flipped, 4, 4, 1); + CHECK(flipped == Bytes{0xff, 0x00, 0x04, 0x30, 0x00, 0x02, 0x10, 0x00}); + + // the alpha of bc3 is a bc4 block, its colour a bc1 one + Bytes bc3{bc4}; + bc3.insert(bc3.end(), {0x11, 0x11, 0x22, 0x22, 0x00, 0x01, 0x02, 0x03}); + ktx2::FlipLevels(ktx2::Format::bc3, bc3, 4, 4, 1); + CHECK(Bytes(bc3.begin(), bc3.begin() + 8) == flipped); + CHECK(Bytes(bc3.begin() + 12, bc3.end()) == Bytes{0x03, 0x02, 0x01, 0x00}); + + // the explicit alpha of bc2: 16 bits a row + Bytes bc2{0x01, 0x10, 0x02, 0x20, 0x03, 0x30, 0x04, 0x40, 0x11, 0x11, 0x22, 0x22, 0x00, 0x01, 0x02, 0x03}; + ktx2::FlipLevels(ktx2::Format::bc2, bc2, 4, 4, 1); + CHECK(Bytes(bc2.begin(), bc2.begin() + 8) == Bytes{0x04, 0x40, 0x03, 0x30, 0x02, 0x20, 0x01, 0x10}); + + // flipped twice, the levels of an image come back as they were + for (auto const format : {ktx2::Format::bc2, ktx2::Format::bc3, ktx2::Format::bc4Signed, ktx2::Format::bc5}) + { + auto const original{counting(static_cast(ktx2::LevelBytes(format, 16, 8) + ktx2::LevelBytes(format, 8, 4) + ktx2::LevelBytes(format, 4, 2)), 7)}; + auto data{original}; + ktx2::FlipLevels(format, data, 16, 8, 3); + CHECK(data != original); + ktx2::FlipLevels(format, data, 16, 8, 3); + CHECK(data == original); + } +} + +TEST_CASE("ktx2: plain texels have their rows swapped, bc6h and bc7 are left as they are") +{ + Bytes rgba{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6}; + ktx2::FlipLevels(ktx2::Format::rgba8, rgba, 2, 3, 1); + CHECK(rgba == Bytes{5, 5, 5, 5, 6, 6, 6, 6, 3, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2}); + + CHECK_FALSE(ktx2::CanFlip(ktx2::Format::bc7)); + CHECK_FALSE(ktx2::CanFlip(ktx2::Format::bc6h)); + CHECK(ktx2::CanFlip(ktx2::Format::bc5Signed)); + auto const original{counting(32, 0)}; + auto data{original}; + ktx2::FlipLevels(ktx2::Format::bc7, data, 4, 8, 1); + CHECK(data == original); +} From 0426a44f71b3a5fb7aafc623e94ef2c6a96b8926 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Mon, 30 Nov 2026 15:42:51 +0100 Subject: [PATCH 14/20] fix(e3d): the -e3d export no longer crashes on a submodel without a matrix A submodel whose definition breaks off before its transform (no "type:" in its header) is still attached to the tree, without a matrix, and TSubModel::serialize dereferenced that matrix. It is written as -1 now, which the binary loader reads back as no matrix, so the .e3d holds the same tree the .t3d gives. The -e3d mode also runs the log service now. Without it nothing logged during the conversion came out, neither the included files the conversion scripts read from the standard output nor the error that names the broken submodel. A model that loaded nothing ends with exit code 1 and a message instead of a crash. --- EU07.cpp | 4 ++-- export_e3d_standalone.cpp | 28 +++++++++++++++++++++++++--- model/Model3d.cpp | 7 ++++++- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/EU07.cpp b/EU07.cpp index 19703dbe1..6b7ed17b9 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -48,7 +48,7 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #endif #endif -void export_e3d_standalone(std::string in, std::string out, int flags, bool dynamic); +int export_e3d_standalone(std::string in, std::string out, int flags, bool dynamic); int export_btf_standalone(std::string in, std::string out); int generate_nodebank_previews(int Argc, char *Argv[]); @@ -144,7 +144,7 @@ int main(int argc, char *argv[]) std::string out(argv[3]); int flags = std::stoi(std::string(argv[4])); int dynamic = std::stoi(std::string(argv[5])); - export_e3d_standalone(in, out, flags, dynamic); + exitcode = export_e3d_standalone(in, out, flags, dynamic); } // standalone generation of preview images of the node bank models: -generate-nodebank-previews [options] else if (argc >= 2 && std::string(argv[1]) == "-generate-nodebank-previews") diff --git a/export_e3d_standalone.cpp b/export_e3d_standalone.cpp index ecdd4ab9c..6a1ae29fc 100644 --- a/export_e3d_standalone.cpp +++ b/export_e3d_standalone.cpp @@ -1,17 +1,39 @@ #include "stdafx.h" +#include + #include "model/Model3d.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "rendering/renderer.h" -void export_e3d_standalone(std::string in, std::string out, int flags, bool dynamic) +int export_e3d_standalone(std::string in, std::string out, int flags, bool dynamic) { Global.iConvertModels = flags; Global.iWriteLogEnabled = 2; Global.ParserLogIncludes = true; + // the log goes to the standard output only, where the conversion scripts read the included files from, so it is + // written from the start. without the log service nothing logged here would come out at all + OpenLogFiles(); + std::jthread logservice(LogService); + GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); TModel3d model; model.LoadFromTextFile(in, dynamic); model.Init(); - model.SaveToBinFile(out); -} \ No newline at end of file + auto result{0}; + if (model.GetSMRoot() == nullptr) + { + ErrorLog("Bad model: failed to load 3d model \"" + in + "\""); + result = 1; + } + else + { + model.SaveToBinFile(out); + } + + // the process ends without destructors, so the log service writes out what's left before it goes + StopLogService(); + logservice.join(); + return result; +} diff --git a/model/Model3d.cpp b/model/Model3d.cpp index f3ddbc4a5..7f60b0bc8 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1943,7 +1943,12 @@ void TSubModel::serialize(std::ostream &s, std::vector &models, std if (m_material > 0 && Global.iConvertModels & 16) flags &= ~0x30; // don't save phase information, will be guessed on binary load from material sn_utils::ls_uint32(s, flags); - sn_utils::ls_int32(s, (int32_t)get_container_pos(transforms, *fMatrix)); + // a submodel whose definition broke off before its transform (see Load()) has no matrix. -1 is what the binary + // loader reads back as no matrix + if (fMatrix != nullptr) + sn_utils::ls_int32(s, (int32_t)get_container_pos(transforms, *fMatrix)); + else + sn_utils::ls_int32(s, -1); sn_utils::ls_int32(s, m_geometry.vertex_count); sn_utils::ls_int32(s, m_geometry.vertex_offset); From 269591fc357bdec0806cd386949bc1e7c85b0511 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Mon, 30 Nov 2026 18:48:43 +0100 Subject: [PATCH 15/20] fix(render): the lamps of small scenery models are seen from afar --- docs/opengl46-renderer.md | 5 ++++ model/Model3d.cpp | 13 ++++++++++ model/Model3d.h | 4 +++ rendering/common/instancecull.h | 1 + rendering/common/scenewalk.cpp | 27 +++++++++++++++------ rendering/common/scenewalk.h | 3 +++ rendering/common/scenewalkindirect.cpp | 1 + rendering/opengl46/opengl46instancecull.cpp | 2 +- rendering/vulkan14/vulkan14cull.cpp | 2 +- scene/scene.h | 2 ++ shaders/ogl46/instance_cull.comp | 7 ++++-- shaders/vk14/instance_cull.comp | 7 ++++-- utilities/Globals.cpp | 2 ++ utilities/Globals.h | 3 +++ 14 files changed, 66 insertions(+), 13 deletions(-) diff --git a/docs/opengl46-renderer.md b/docs/opengl46-renderer.md index 2491ceec6..39045ca63 100644 --- a/docs/opengl46-renderer.md +++ b/docs/opengl46-renderer.md @@ -180,6 +180,11 @@ scales can also be changed in the **Light clusters** debug window. shines always). Their colour, power, cone and the optional `Radius:`/`SoftFalloff:`/`CastShadows:` are those of the light point (brightness `gfx.lights.freespot.intensity`, the self-illumination threshold doesn't matter), and they fade in the daylight as the cab lamp does. The dimming of the cab lamp applies only to the lamp under the top. +- **Lamps seen from afar** (`gfx.lights.freespot.far`, default `yes`): a scenery model with light points (not `LightOnly`) is + drawn however small it is in the view, so its lamps are seen as far as the ranges of their submodels (`MaxDistance` of the + light point and of every submodel above it) and the draw range reach. Before, a model smaller than 0.3% of the view was left + out whole, lamps too: a dwarf signal at a few hundred metres, a signal head at a kilometre or two. `no` brings that back. It + holds in the colour pass only; shadows and reflections leave small models out as before. - **`LightOnly: true`** (an optional entry of any `FreeSpotLight`, after `HotspotAngle:` with the others; in e3d the flag 0x8 after the radius) makes the light point only a light: it lights its surroundings, but its glowing point and its glare, seen from afar, aren't drawn. For lights hidden in fittings, the backlight of a desk and the like. diff --git a/model/Model3d.cpp b/model/Model3d.cpp index f3ddbc4a5..e7247b3b0 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1843,6 +1843,17 @@ void assign_lod_ranges(TSubModel *Root, std::string const &Filename) phase.submodel->fSquareMaxDist = farlimit * farlimit; } } + +// whether the submodel, the submodels under it or the ones after it hold a light point seen from afar +bool has_light_points(TSubModel const *Submodel) +{ + for (auto const *submodel = Submodel; submodel != nullptr; submodel = submodel->Next) + { + if (((submodel->eType == TP_FREESPOTLIGHT) && (false == submodel->bLightOnly)) || has_light_points(submodel->Child)) + return true; + } + return false; +} } // namespace bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) @@ -1890,6 +1901,8 @@ bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) assign_lod_ranges(Root, name); } + m_lightpoints = has_light_points(Root); + bool const result = Root ? iSubModelsCount > 0 : false; // brak pliku albo problem z wczytaniem if (false == result) { diff --git a/model/Model3d.h b/model/Model3d.h index f7a09dc03..67486802e 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -307,6 +307,7 @@ private: bool m_instancesubmodelslocated { false }; std::vector m_lodbounds; // filled on first use, see lod_bounds() bool m_lodboundsfound { false }; + bool m_lightpoints { false }; // see HasLightPoints() std::uint32_t m_stateversion { 0 }; // see state_version() public: @@ -322,6 +323,9 @@ public: // returns the distinct bounds of the visibility ranges of the submodels (fSquareMinDist and fSquareMaxDist, squared), sorted: // they split the distance into bands in which the same submodels are drawn. found once for the model, like instance_parts() std::vector const & lod_bounds(); + // whether the model holds light points seen from afar: freespot lights which aren't only lights (lightonly:). found as it loads + bool HasLightPoints() const { + return m_lightpoints; } // the submodels of the model are shared by everything drawn with it, which sets their state (lights, animations, visibility) // before it's drawn. the version changes when something which may set it differently than the last time did, or the submodels // changed, so the renderer can tell whether what it worked out from them still holds diff --git a/rendering/common/instancecull.h b/rendering/common/instancecull.h index 1661bf933..5328016fe 100644 --- a/rendering/common/instancecull.h +++ b/rendering/common/instancecull.h @@ -65,6 +65,7 @@ class instance_cull float distancerange{0.f}; // squared range of the scaled distance before the offset float drawrange{0.f}; // squared draw range float zoom{1.f}; + bool lightpoints{false}; // instances of models with light points are kept however small in the view (scene_walk::Keeps_Light_Points()) bool drawing{false}; // the instances are drawn from the result (Global.gfx_gpucull 1), not compared }; // a group of instances (model and skins) of the pass, for the renderer to make the draw commands of diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index ad0dafae0..7ea2c2bad 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -936,9 +936,10 @@ void scene_walk::Render(TAnimModel *Instance) if( distancesquared > sq(drawdistancethreshold) ) { return; } - // second stage visibility cull, reject modelstoo far away to be noticeable + // second stage visibility cull, reject modelstoo far away to be noticeable; a model with light points is kept for its lamps auto const radiussquared { Instance->radius() * Instance->radius() }; - if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) { + if( ( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) + && ( false == Keeps_Light_Points( ( Instance->pModel != nullptr ) && Instance->pModel->HasLightPoints() ) ) ) { return; } if( m_modelcomparekey != nullptr ) { @@ -1085,6 +1086,9 @@ void scene_walk::Update_Instance_Records( TModel3d const *Model, scene::basic_ce Bucket.records.clear(); Bucket.records.reserve( Bucket.instances.size() ); + // the light points of the model are seen from afar, however small its instances are in the view (Keeps_Light_Points()) + auto const lightpoints { ( Model != nullptr ) && Model->HasLightPoints() }; + Bucket.recordlightpoints = lightpoints; // the range of the bucket: past it none of its instances is drawn, by its own range or by the submodels of the model auto rangesquared { 0.f }; for( auto *instance : Bucket.instances ) { @@ -1097,7 +1101,8 @@ void scene_walk::Update_Instance_Records( TModel3d const *Model, scene::basic_ce rangesquared = std::max( rangesquared, record.rangesquaredmax ); record.flags = ( instance->visible() ? scene::basic_cell::instance_visible : 0u ) - | ( instance->m_instanceable ? scene::basic_cell::instance_instanceable : 0u ); + | ( instance->m_instanceable ? scene::basic_cell::instance_instanceable : 0u ) + | ( lightpoints ? scene::basic_cell::instance_lightpoints : 0u ); auto const &rotationscale { instance->rotation_scale() }; for( int column = 0; column < 3; ++column ) { record.rotationscale[ column ] = rotationscale[ column ]; @@ -1170,6 +1175,12 @@ scene::basic_cell::instance_sequence const &scene_walk::Single_Instances( scene: return Cell.m_instancessingle; } +bool scene_walk::Keeps_Light_Points( bool const Lightpoints ) const +{ + // only the colour pass shows the light points: in the shadows and the reflections a small model is left out as before + return Lightpoints && Global.gfx_lights_freespot_far && ( m_renderpass.draw_mode == rendermode::color ); +} + // whether none of the instances of a bucket can pass the tests of the culling of the pass (Render_Instanced(), on the gpu // instance_cull.comp): by the bounds of their records the visible ones lie wholly out of the frustum of the pass, beyond their // range or the draw range, or are too small on the screen. the tests are those of the culling with the nearest location and @@ -1202,7 +1213,7 @@ bool scene_walk::Bucket_Culled( scene::basic_cell::instance_bucket const &Bucket if( distancesquared > slack * sq( static_cast( m_renderpass.draw_range ) + 250.0 ) ) { return true; } // the largest instance at the nearest location takes the largest part of the view auto const radiusmax { static_cast( Bucket.recordradiusmax ) }; - if( radiusmax * radiusmax * zoom * slack < 0.003 * 0.003 * distancesquared ) { return true; } + if( ( radiusmax * radiusmax * zoom * slack < 0.003 * 0.003 * distancesquared ) && ( false == Keeps_Light_Points( Bucket.recordlightpoints ) ) ) { return true; } return false; } @@ -1313,7 +1324,8 @@ void scene_walk::Render_Instanced( TModel3d *Model, std::vector if( distancesquared > sq( drawdistancethreshold ) ) { continue; } auto const radiussquared { record.radius * record.radius }; - if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) { continue; } + if( ( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) + && ( false == Keeps_Light_Points( ( record.flags & scene::basic_cell::instance_lightpoints ) != 0 ) ) ) { continue; } if( batch_instance == nullptr ) { batch_instance = queued.bucket->instances[ queued.index ]; @@ -2884,9 +2896,10 @@ void scene_walk::Render_Alpha(TAnimModel *Instance) if( distancesquared > sq(drawdistancethreshold) ) { return; } - // second stage visibility cull, reject modelstoo far away to be noticeable + // second stage visibility cull, reject modelstoo far away to be noticeable; a model with light points is kept for its lamps auto const radiussquared { Instance->radius() * Instance->radius() }; - if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) { + if( ( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) + && ( false == Keeps_Light_Points( ( Instance->pModel != nullptr ) && Instance->pModel->HasLightPoints() ) ) ) { return; } diff --git a/rendering/common/scenewalk.h b/rendering/common/scenewalk.h index 0bdfa63e9..8b1f18550 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -158,6 +158,9 @@ class scene_walk scene::basic_cell::instance_sequence const &Single_Instances(scene::basic_cell const &Cell) const; // whether none of the instances of a bucket can pass the culling of the current pass, by the bounds of their records bool Bucket_Culled(scene::basic_cell::instance_bucket const &Bucket) const; + // whether the current pass draws an instance whose model has light points (Lightpoints) however small it is in the view, + // so that its lamps are seen from afar (Global.gfx_lights_freespot_far) + bool Keeps_Light_Points(bool const Lightpoints) const; // the sphere around the locations of the visible instances of a bucket, with a margin for the precision of the records static scene::bounding_area Bucket_Area(scene::basic_cell::instance_bucket const &Bucket); bool Render(TDynamicObject *Dynamic); diff --git a/rendering/common/scenewalkindirect.cpp b/rendering/common/scenewalkindirect.cpp index 661986bec..8b5bf96df 100644 --- a/rendering/common/scenewalkindirect.cpp +++ b/rendering/common/scenewalkindirect.cpp @@ -59,6 +59,7 @@ void scene_walk::Begin_Pass_Cull(gfx::instance_cull *Cull, bool const Mainview) setup.distancerange = (reflections ? static_cast(sq(Global.reflectiontune.range_instances)) : std::numeric_limits::max()); setup.drawrange = static_cast(sq(m_renderpass.draw_range + 250)); setup.zoom = Global.ZoomFactor; + setup.lightpoints = Keeps_Light_Points(true); setup.drawing = (Global.gfx_gpucull == 1); m_passcull->begin_pass(setup); } diff --git a/rendering/opengl46/opengl46instancecull.cpp b/rendering/opengl46/opengl46instancecull.cpp index a18b1fe23..4556d75b5 100644 --- a/rendering/opengl46/opengl46instancecull.cpp +++ b/rendering/opengl46/opengl46instancecull.cpp @@ -105,7 +105,7 @@ void opengl46_instance_cull::dispatch(glm::mat4 const &View, occlusion_setup con glProgramUniformMatrix4fv(*m_shared->cull_program, 0, 1, GL_FALSE, glm::value_ptr(View)); glProgramUniform4fv(*m_shared->cull_program, 1, 6, glm::value_ptr(planes[0])); glProgramUniform4f(*m_shared->cull_program, 7, m_setup.distancescale, m_setup.distanceoffset, m_setup.distancerange, m_setup.drawrange); - glProgramUniform4f(*m_shared->cull_program, 8, m_setup.zoom, 0.f, 0.f, 0.f); + glProgramUniform4f(*m_shared->cull_program, 8, m_setup.zoom, (m_setup.lightpoints ? 1.f : 0.f), 0.f, 0.f); glProgramUniform4ui(*m_shared->offsets_program, 0, m_entries, 0, 0, 0); // the occlusion test only when the instances are drawn from the result, the cpu doesn't make it m_occlusion = (m_setup.drawing && (Occlusion != nullptr) && (Occlusion->pyramid != 0)); diff --git a/rendering/vulkan14/vulkan14cull.cpp b/rendering/vulkan14/vulkan14cull.cpp index 0e33cd871..e90720553 100644 --- a/rendering/vulkan14/vulkan14cull.cpp +++ b/rendering/vulkan14/vulkan14cull.cpp @@ -282,7 +282,7 @@ void instance_cull::dispatch(command_stream *Commands, glm::mat4 const &View, cu block.view = View; frustum_planes(block.planes); block.distance_params = glm::vec4{m_setup.distancescale, m_setup.distanceoffset, m_setup.distancerange, m_setup.drawrange}; - block.size_params = glm::vec4{m_setup.zoom, 0.f, 0.f, 0.f}; + block.size_params = glm::vec4{m_setup.zoom, (m_setup.lightpoints ? 1.f : 0.f), 0.f, 0.f}; // the occlusion test only when the instances are drawn from the result, the cpu doesn't make it m_occlusion = (m_setup.drawing && (Occlusion != nullptr) && (Occlusion->pyramid != VK_NULL_HANDLE)); if (m_occlusion) diff --git a/scene/scene.h b/scene/scene.h index e92b11988..3c6f9f0e6 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -272,6 +272,7 @@ public: enum instance_record_flags : std::uint32_t { instance_visible = 1 << 0, instance_instanceable = 1 << 1, // false once an event gave the instance animations or a skin of its own + instance_lightpoints = 1 << 2, // the model has light points seen from afar (TModel3d::HasLightPoints()) }; struct instance_bucket { std::vector instances; @@ -287,6 +288,7 @@ public: mutable float recordlocationradius { 0.f }; mutable float recordradius { -1.f }; mutable float recordradiusmax { 0.f }; + mutable bool recordlightpoints { false }; // the model of the bucket has light points seen from afar mutable unsigned int recordsversion { 0 }; // place of the records in the record buffer of the gpu culling: first record, room, and the generation of // the buffer it is good for. gpustale: the records changed since they were sent diff --git a/shaders/ogl46/instance_cull.comp b/shaders/ogl46/instance_cull.comp index 5a6fd6ca4..7e7bb3015 100644 --- a/shaders/ogl46/instance_cull.comp +++ b/shaders/ogl46/instance_cull.comp @@ -82,7 +82,7 @@ layout(location = 1) uniform vec4 planes[6]; // x: scale of the squared distance, y: added to it past the range test, z: range of the scaled distance before the // addition (reflections), w: squared draw range layout(location = 7) uniform vec4 distance_params; -// x: zoom factor +// x: zoom factor, y: 1 when instances of models with light points are kept however small in the view layout(location = 8) uniform vec4 size_params; // x: jobs, y: records in all jobs, z: entries, w: stage layout(location = 9) uniform uvec4 counts; @@ -99,6 +99,7 @@ layout(binding = 0) uniform sampler2D hiz; const uint INSTANCE_VISIBLE = 1u; const uint INSTANCE_INSTANCEABLE = 2u; +const uint INSTANCE_LIGHTPOINTS = 4u; // smallest part of the view an instance has to take const float MIN_SCREEN_SIZE = 0.003; // header of the counters, see gl::INSTANCE_COUNTER_HEADER @@ -198,7 +199,9 @@ bool passes(instance_cull_job job, instance_record record, out vec3 location, ou return false; if (distancesquared > distance_params.w) return false; - if (record.radius * record.radius * size_params.x / distancesquared < MIN_SCREEN_SIZE * MIN_SCREEN_SIZE) + // a model with light points stays for its lamps to be seen from afar + bool lightpoints = ((record.flags & INSTANCE_LIGHTPOINTS) != 0u) && (size_params.y != 0.0); + if ((record.radius * record.radius * size_params.x / distancesquared < MIN_SCREEN_SIZE * MIN_SCREEN_SIZE) && (!lightpoints)) return false; } diff --git a/shaders/vk14/instance_cull.comp b/shaders/vk14/instance_cull.comp index c6b8e0983..b7ac25928 100644 --- a/shaders/vk14/instance_cull.comp +++ b/shaders/vk14/instance_cull.comp @@ -86,7 +86,7 @@ layout(std140, set = COMPUTE_SET, binding = 7) uniform kernel_block // x: scale of the squared distance, y: added to it past the range test, z: range of the scaled distance before the // addition (reflections), w: squared draw range vec4 distance_params; - // x: zoom factor + // x: zoom factor, y: 1 when instances of models with light points are kept however small in the view vec4 size_params; // occlusion test: projection of the pass, x: on, y: levels of the pyramid, zw: size of its first level mat4 hiz_projection; @@ -107,6 +107,7 @@ layout(set = COMPUTE_SET, binding = 6) uniform sampler2D hiz; const uint INSTANCE_VISIBLE = 1u; const uint INSTANCE_INSTANCEABLE = 2u; +const uint INSTANCE_LIGHTPOINTS = 4u; // smallest part of the view an instance has to take const float MIN_SCREEN_SIZE = 0.003; // header of the counters, see gl::INSTANCE_COUNTER_HEADER @@ -206,7 +207,9 @@ bool passes(instance_cull_job job, instance_record record, out vec3 location, ou return false; if (distancesquared > distance_params.w) return false; - if (record.radius * record.radius * size_params.x / distancesquared < MIN_SCREEN_SIZE * MIN_SCREEN_SIZE) + // a model with light points stays for its lamps to be seen from afar + bool lightpoints = ((record.flags & INSTANCE_LIGHTPOINTS) != 0u) && (size_params.y != 0.0); + if ((record.radius * record.radius * size_params.x / distancesquared < MIN_SCREEN_SIZE * MIN_SCREEN_SIZE) && (!lightpoints)) return false; } diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 4461e8278..ccd0672c8 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -2250,6 +2250,7 @@ global_settings::ConfigParse_gfx_sky( cParser &Parser, std::string_view const To else if( Token == "gfx.lights.headlights" ) { readswitch( gfx_lights_headlights ); } else if( Token == "gfx.lights.cab" ) { readswitch( gfx_lights_cab ); } else if( Token == "gfx.lights.freespot.intensity" ) { readvalue( gfx_lights_freespot_intensity, 0.f, 1000.f ); } + else if( Token == "gfx.lights.freespot.far" ) { readswitch( gfx_lights_freespot_far ); } else if( Token == "gfx.lights.compartment.intensity" ) { readvalue( gfx_lights_compartment_intensity, 0.f, 100.f ); } else if( Token == "gfx.lights.cab.intensity" ) { readvalue( gfx_lights_cab_intensity, 0.f, 100.f ); } else if( Token == "gfx.lights.cab.bounce" ) { readvalue( gfx_lights_cab_bounce, 0.f, 1.f ); } @@ -2854,6 +2855,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "gfx.lights.headlights", gfx_lights_headlights ); export_as_text( Output, "gfx.lights.cab", gfx_lights_cab ); export_as_text( Output, "gfx.lights.freespot.intensity", gfx_lights_freespot_intensity ); + export_as_text( Output, "gfx.lights.freespot.far", gfx_lights_freespot_far ); export_as_text( Output, "gfx.lights.compartment.intensity", gfx_lights_compartment_intensity ); export_as_text( Output, "gfx.lights.cab.intensity", gfx_lights_cab_intensity ); export_as_text( Output, "gfx.lights.cab.bounce", gfx_lights_cab_bounce ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 0a47cd13d..322bd54bb 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -597,6 +597,9 @@ struct global_settings { bool gfx_lights_headlights { true }; bool gfx_lights_cab { true }; // the lamp of the occupied cab is a point light instead of an addition to the ambient light float gfx_lights_freespot_intensity { 10.f }; // brightness of a light point of a model + // a scenery model with light points is drawn however small it is in the view, so its lamps are seen from afar as far as the ranges + // of their submodels reach. no: as before, a model smaller than 0.3% of the view is left out with its lamps + bool gfx_lights_freespot_far { true }; float gfx_lights_compartment_intensity { 1.f }; // brightness of the light of a lit vehicle compartment float gfx_lights_cab_intensity { 1.5f }; // brightness of the cab lamp float gfx_lights_cab_bounce { 0.3f }; // share of the former ambient light of the cab lamp kept, for the light which bounces around the cab From 48b7c679a005688082b262364890f47e1aba15b0 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Mon, 30 Nov 2026 19:39:29 +0100 Subject: [PATCH 16/20] Windscreen snow: no crash of the simulator when the driver's compiler faults A player's simulator (Vulkan, GeForce RTX 4060, NVIDIA 610.88, through Steam) crashed at every start as the cab loaded: an access violation (read of address 8) inside nvgpucomp64.dll while vkCreateComputePipelines compiled water_snowlayer.comp. The crash came on $baltyk_skm1.scn and $td.scn alike, at the same address in the driver. The snow shaders (shaders/vk14 and shaders/ogl46, the same in both) no longer use what the compute shader alone had: a vector component written at an index known only while running through an inout parameter (snRef), constant arrays of structs and of ints indexed at run time (sn_grids, sn_lump_tiles, the neighbours of snSpan) and a local vec4 indexed by the blade. They are worked out by small functions and explicit components instead (snRefPut, snRefWord, snGrid, snLumpTile, snNear), and the blade is read from the storage as water_snow.comp, which the same driver compiled, does. The results are the same. glslc compiles both variants and spirv-val passes; whether 610.88 compiles them now can't be checked without that driver. So that a driver crashing on a program the renderer can go without doesn't take the simulator down, the programs of the windscreen water are made under gfx::DriverCrashGuard (rendering/common/drivercrashguard.*): - with msvc the fault of the driver is caught (SEH) and the session goes on without the program: the glasses without the snow, or without the simulation of the water; - the program is written down in the cache of the renderer (driver_crash_attempt.txt) before the driver gets it and crossed out after. a program a session ended on is suspect (driver_crash_suspects.txt); when a second session ends on it, or when a fault was caught, it is recorded (driver_crashes.txt) and not made again with that driver. a new driver or a changed program is tried again; - Vulkan makes these pipelines without the VkPipelineCache, whose lock a faulting driver might leave taken (the drivers keep their own cache on the disk). Tested: unit tests (1211/1211, with a caught access violation), Vulkan and OpenGL 4.6 in the cab of 303E on $td.scn (RTX 4070, 621.14), and on Vulkan with a real access violation injected into the pipeline of water_snowlayer.comp: the session went on without the snow, the next one skipped it. No change of the game data. --- CMakeLists.txt | 1 + rendering/common/drivercrashguard.cpp | 232 +++++++++++++++++++++++++ rendering/common/drivercrashguard.h | 79 +++++++++ rendering/opengl46/opengl46water.cpp | 82 +++++++-- rendering/opengl46/opengl46water.h | 7 + rendering/vulkan14/vulkan14compute.cpp | 5 +- rendering/vulkan14/vulkan14compute.h | 5 +- rendering/vulkan14/vulkan14shaders.cpp | 63 ++++++- rendering/vulkan14/vulkan14shaders.h | 17 +- rendering/vulkan14/vulkan14water.cpp | 4 +- shaders/ogl46/snow_sprites.glsl | 111 +++++++++--- shaders/ogl46/water_snowlayer.comp | 8 +- shaders/vk14/snow_sprites.glsl | 111 +++++++++--- shaders/vk14/water_snowlayer.comp | 8 +- tests/unit/CMakeLists.txt | 2 + tests/unit/test_driver_crash_guard.cpp | 164 +++++++++++++++++ 16 files changed, 821 insertions(+), 78 deletions(-) create mode 100644 rendering/common/drivercrashguard.cpp create mode 100644 rendering/common/drivercrashguard.h create mode 100644 tests/unit/test_driver_crash_guard.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 561bbc127..84d0be14b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -448,6 +448,7 @@ set(SOURCES "rendering/common/exposure.cpp" "rendering/common/temporalaa.cpp" "rendering/common/freecameramotion.cpp" +"rendering/common/drivercrashguard.cpp" "rendering/common/screenreflections.cpp" "gl/buffer.cpp" "gl/fence.cpp" diff --git a/rendering/common/drivercrashguard.cpp b/rendering/common/drivercrashguard.cpp new file mode 100644 index 000000000..46c08c03f --- /dev/null +++ b/rendering/common/drivercrashguard.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 "rendering/common/drivercrashguard.h" + +#include "utilities/Logs.h" + +#include +#include +#include +#include +#include +#include + +#if defined(_MSC_VER) +#include +#endif + +namespace gfx +{ + +namespace +{ + +constexpr char separator{'\t'}; + +using Records = std::vector>; + +// the text as one field of a line of the records +std::string oneField(std::string_view const text) +{ + std::string result{text}; + std::ranges::replace_if(result, [](char const c) { return (c == '\t') || (c == '\n') || (c == '\r'); }, ' '); + return result; +} + +// the lines of the records, the driver and the program; nothing when there's no file +Records readRecords(std::string const &path) +{ + Records result; + std::ifstream file(path); + std::string line; + while (std::getline(file, line)) + { + if ((false == line.empty()) && (line.back() == '\r')) + line.pop_back(); + auto const tab{line.find(separator)}; + if ((tab == std::string::npos) || (tab + 1 == line.size())) + continue; + result.emplace_back(line.substr(0, tab), line.substr(tab + 1)); + } + return result; +} + +void appendRecord(std::string const &path, std::string_view const driver, std::string_view const key) +{ + if (path.empty()) + return; + std::ofstream file(path, std::ios::app); + file << driver << separator << key << '\n'; +} + +#if defined(_MSC_VER) +// the faults caught: the structured exceptions but those of c++ (thrown on) and the overflow of the stack (the guard page is gone +// after it, the thread can't go on) +int faultFilter(unsigned long const code) +{ + constexpr unsigned long cppException{0xE06D7363ul}; + constexpr unsigned long stackOverflow{0xC00000FDul}; + return ((code == cppException) || (code == stackOverflow)) ? EXCEPTION_CONTINUE_SEARCH : EXCEPTION_EXECUTE_HANDLER; +} +#endif + +} // namespace + +void DriverCrashGuard::Init(std::string_view const directory, std::string_view const driverName) +{ + std::scoped_lock lock(mutex); + std::string const folder{directory}; + std::error_code error; + std::filesystem::create_directories(std::filesystem::path(folder), error); + recordsPath = folder + "driver_crashes.txt"; + suspectsPath = folder + "driver_crash_suspects.txt"; + attemptPath = folder + "driver_crash_attempt.txt"; + driver = oneField(driverName); + crashedKeys.clear(); + suspectKeys.clear(); + for (auto const &[recordDriver, key] : readRecords(recordsPath)) + { + if (recordDriver == driver) + crashedKeys.insert(key); + } + for (auto const &[recordDriver, key] : readRecords(suspectsPath)) + { + if (recordDriver == driver) + suspectKeys.insert(key); + } + // the program the session before was making when it ended (one of another driver no longer matters) + for (auto const &[attemptDriver, key] : readRecords(attemptPath)) + { + if ((attemptDriver != driver) || crashedKeys.contains(key)) + continue; + if (suspectKeys.contains(key)) + { + ErrorLog(std::format("driver crash guard: the session before ended again while the driver ({}) made {}; it isn't made again with this driver ({} lists it)", driver, key, + recordsPath)); + recordCrash(key); + continue; + } + suspectKeys.insert(key); + appendRecord(suspectsPath, driver, key); + WriteLog(std::format("driver crash guard: the session before ended while the driver ({}) made {}; if a session ends there again, it isn't made with this driver", driver, key)); + } + removeAttempt(); +} + +DriverCrashGuard::Outcome DriverCrashGuard::Run(std::string_view const key, void (*make)(void *), void *context) +{ + std::scoped_lock lock(mutex); + std::string const name{oneField(key)}; + if (crashedKeys.contains(name)) + { + ErrorLog(std::format("driver crash guard: {} isn't made, the driver ({}) crashed on it before ({} lists it)", name, driver, recordsPath)); + return Outcome::skipped; + } + writeAttempt(name); + bool faulted{false}; + try + { + faulted = (false == CallCatchingFaults(make, context)); + } + catch (...) + { + removeAttempt(); + throw; + } + if (faulted) + { + ErrorLog(std::format("driver crash guard: the driver ({}) crashed while it made {}; the simulator goes on without it and doesn't make it again with this driver ({} lists it)", + driver, name, recordsPath)); + recordCrash(name); + } + else + { + clearSuspect(name); + } + removeAttempt(); + return (faulted ? Outcome::crashed : Outcome::made); +} + +bool DriverCrashGuard::Crashed(std::string_view const key) const +{ + std::scoped_lock lock(mutex); + return crashedKeys.contains(oneField(key)); +} + +bool DriverCrashGuard::Suspect(std::string_view const key) const +{ + std::scoped_lock lock(mutex); + return suspectKeys.contains(oneField(key)); +} + +void DriverCrashGuard::writeAttempt(std::string const &key) const +{ + if (attemptPath.empty()) + return; + // closed before the driver gets the program: what a crash of the process leaves behind is then with the system already + std::ofstream file(attemptPath, std::ios::trunc); + file << driver << separator << key << '\n'; +} + +void DriverCrashGuard::removeAttempt() const +{ + if (attemptPath.empty()) + return; + std::error_code error; + std::filesystem::remove(attemptPath, error); +} + +void DriverCrashGuard::recordCrash(std::string const &key) +{ + crashedKeys.insert(key); + appendRecord(recordsPath, driver, key); + clearSuspect(key); +} + +void DriverCrashGuard::clearSuspect(std::string const &key) +{ + if (0 == suspectKeys.erase(key)) + return; + if (suspectsPath.empty()) + return; + // the file written anew without the program of this driver + auto records{readRecords(suspectsPath)}; + std::erase_if(records, [this, &key](std::pair const &record) { return (record.first == driver) && (record.second == key); }); + std::ofstream file(suspectsPath, std::ios::trunc); + for (auto const &[recordDriver, recordKey] : records) + { + file << recordDriver << separator << recordKey << '\n'; + } +} + +#if defined(_MSC_VER) +bool CallCatchingFaults(void (*function)(void *), void *context) +{ + // no object with a destructor in this function: msvc doesn't take __try where one would have to be unwound + __try + { + function(context); + } + __except (faultFilter(GetExceptionCode())) + { + return false; + } + return true; +} +#else +bool CallCatchingFaults(void (*function)(void *), void *context) +{ + function(context); + return true; +} +#endif + +} // namespace gfx diff --git a/rendering/common/drivercrashguard.h b/rendering/common/drivercrashguard.h new file mode 100644 index 000000000..009840506 --- /dev/null +++ b/rendering/common/drivercrashguard.h @@ -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/. +*/ + +// the programs a graphics driver crashed on while it compiled them. a fault inside the driver (an access violation of its +// compiler, not an error it reports) takes the whole simulator down: the NVIDIA driver 610.88 did that on water_snowlayer.comp +// as the cab loaded, at every start. so a program a renderer can go without (the water and the snow on the windscreens) is made +// under this guard: +// - where the fault can be caught (built with msvc), it is, and the session goes on without the program; +// - the program is written down in the cache of the renderer before the driver gets it and crossed out after, so a session the +// driver took down anyway (a fault not caught, on a thread of the driver) leaves it behind. the next session takes it as +// suspect, and as one the driver crashed on when a session ends while it is made a second time: a session ended from outside +// while the driver compiled (some programs take seconds) doesn't leave the program out. made well, it is no longer suspect; +// - a program the driver crashed on isn't made again with that driver. the records name the driver and the program with the hash +// of its code, so a new version of the driver, or a changed program, is tried again. +// +// no graphics api here (the unit tests build it on its own) + +#pragma once + +#include +#include +#include +#include +#include + +namespace gfx +{ + +class DriverCrashGuard +{ + public: + enum class Outcome + { + made, // the program was made (whether the driver could make it or not is the caller's to tell) + skipped, // the driver crashed on the program before: nothing was done + crashed // the driver faulted while it made the program, caught + }; + + // Directory: the cache of the renderer, with a separator at the end (made when it isn't there); Driver: the device and the + // version of its driver. a program the session before left written down is taken as suspect, or as one the driver crashed on + // when it was suspect already + void Init(std::string_view directory, std::string_view driver); + // Make(Context) run for the program Key (its name and the hash of its code) under the guard. a c++ exception of Make goes on + // through, the program crossed out. one program is made under the guard at a time + Outcome Run(std::string_view key, void (*make)(void *), void *context); + // whether the driver crashed on the program Key before + bool Crashed(std::string_view key) const; + // whether a session ended once while the driver made the program Key + bool Suspect(std::string_view key) const; + + private: + void writeAttempt(std::string const &key) const; + void removeAttempt() const; + void recordCrash(std::string const &key); + void clearSuspect(std::string const &key); + + mutable std::mutex mutex; + // driver_crashes.txt, driver_crash_suspects.txt and driver_crash_attempt.txt of the cache, lines of the driver and the program + // parted by a tab; empty before Init(), when nothing is written down (the programs are still guarded) + std::string recordsPath; + std::string suspectsPath; + std::string attemptPath; + std::string driver; + std::set> crashedKeys; + std::set> suspectKeys; +}; + +// Function(Context); false when it raised a fault (a structured exception of windows other than one of c++, and other than the +// overflow of the stack, which leaves the thread unable to go on) which was caught. a c++ exception goes on through. where faults +// can't be caught (not built with msvc) the call is made as it is and true returned +bool CallCatchingFaults(void (*function)(void *), void *context); + +} // namespace gfx diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index 980e779df..edeb187a3 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -11,12 +11,16 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46water.h" #include "model/Texture.h" +#include "rendering/common/shadersource.h" #include "rendering/renderer.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include #include +#include #include +#include namespace { @@ -47,30 +51,78 @@ constexpr std::array PROGRAM_NAMES{"water_trail.comp", "water_ "water_snowlayer.comp"}; } // namespace +namespace +{ + +// a program of the water made under the guard against the driver crashing on it +struct GuardedProgram +{ + char const *name{nullptr}; + std::unique_ptr program; +}; + +void runGuardedProgram(void *const context) +{ + auto *const job{static_cast(context)}; + gl::shader shader(job->name); + job->program = std::make_unique(std::vector>{shader}); +} + +// a string of the driver, empty when it gives none +std::string driverString(GLenum const name) +{ + auto const *text{reinterpret_cast(::glGetString(name))}; + return (text != nullptr ? std::string(text) : std::string()); +} + +} // namespace + +bool opengl46_windscreen_water::makeGuardedProgram(std::size_t const index) +{ + if (false == crashGuardStarted) + { + crashGuardStarted = true; + auto const path{user_config_path("cache")}; + auto const directory{path.empty() ? std::string("cache/opengl46/") : (path / "opengl46").string() + "/"}; + crashGuard.Init(directory, std::format("opengl {} {} {}", driverString(GL_VENDOR), driverString(GL_RENDERER), driverString(GL_VERSION))); + } + // the program to the guard: its sources with their includes, so a changed one is tried again with a driver which crashed on it + auto const source{gfx::preprocess_shader(gfx::shader_api::opengl46, PROGRAM_NAMES[index], {}, {}, true)}; + GuardedProgram job{PROGRAM_NAMES[index]}; + if (crashGuard.Run(std::format("program {} {:016x}", PROGRAM_NAMES[index], gfx::shader_file_hash(source.text)), &runGuardedProgram, &job) != gfx::DriverCrashGuard::Outcome::made) + { + return false; + } + m_programs[index] = std::move(job.program); + return true; +} + // the program of a pass made; false when it doesn't compile (a pass of the snow then leaves the snow out, both of its passes) bool opengl46_windscreen_water::make_program(std::size_t const Index) { + std::string failure; try { - gl::shader shader(PROGRAM_NAMES[Index]); - m_programs[Index] = std::make_unique(std::vector>{shader}); - return true; + if (makeGuardedProgram(Index)) + return true; + failure = "the driver crashed on it"; } catch (gl::shader_exception const &e) { - if (Index >= pass::snow) - { - ErrorLog("windscreen water: can't use " + std::string(PROGRAM_NAMES[Index]) + ", the glasses of the snow stay clear: " + std::string(e.what())); - m_nosnow = true; - m_programs[pass::snow].reset(); - m_programs[pass::snowlayer].reset(); - } - else - { - ErrorLog("windscreen water: " + std::string(PROGRAM_NAMES[Index]) + " not made: " + std::string(e.what())); - } - return false; + failure = e.what(); } + if (Index >= pass::snow) + { + ErrorLog("windscreen water: can't use " + std::string(PROGRAM_NAMES[Index]) + ", the glasses of the snow stay clear: " + failure); + m_nosnow = true; + m_programs[pass::snow].reset(); + m_programs[pass::snowlayer].reset(); + } + else + { + ErrorLog("windscreen water: " + std::string(PROGRAM_NAMES[Index]) + " not made: " + failure); + } + return false; } // the program of the cells of the rain (rain_cells.comp) made, once; its storage is made with the first bind() diff --git a/rendering/opengl46/opengl46water.h b/rendering/opengl46/opengl46water.h index db914fb93..1e0ffb4b3 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include "rendering/common/drivercrashguard.h" #include "rendering/common/windscreenwater.h" #include "gl/shader.h" #include "gl/ssbo.h" @@ -74,8 +75,14 @@ class opengl46_windscreen_water : public gfx::windscreen_water bool m_raincelltried{false}; bool m_raincellsvalid{false}; // the cells worked out in this frame bool m_nosnow{false}; // a pass of the snow didn't compile: the snow is left out + // the programs are made under the guard against the driver crashing on them (the compiler of the NVIDIA driver 610.88 did on + // water_snowlayer.comp), started with the first of them, in the context of the driver + gfx::DriverCrashGuard crashGuard; + bool crashGuardStarted{false}; bool make_program(std::size_t Index); + // the program of a pass made under crashGuard; false when the driver crashed on it, now or before. throws gl::shader_exception + bool makeGuardedProgram(std::size_t index); void make_rain_cells_program(); // the storage of the cells made, once, cleared void make_rain_cells_storage(); diff --git a/rendering/vulkan14/vulkan14compute.cpp b/rendering/vulkan14/vulkan14compute.cpp index d32f746b5..085e90543 100644 --- a/rendering/vulkan14/vulkan14compute.cpp +++ b/rendering/vulkan14/vulkan14compute.cpp @@ -210,7 +210,8 @@ std::vector reflect_bindings(std::vector const &Shader, VkDescriptorSetLayout Passlayout, std::vector const &Specialization, std::string const &Name) +bool compute_kernel::create(VkDevice Device, pipeline_library &Pipelines, std::shared_ptr const &Shader, VkDescriptorSetLayout Passlayout, std::vector const &Specialization, std::string const &Name, + PipelineGuard const Guard) { m_name = Name; auto const bindings{reflect_bindings(Shader->spirv, COMPUTE_PUSH_SET, VK_SHADER_STAGE_COMPUTE_BIT)}; @@ -243,7 +244,7 @@ bool compute_kernel::create(VkDevice Device, pipeline_library &Pipelines, std::s { return false; } - m_pipeline = Pipelines.compute(Shader, m_layout, Specialization, Name); + m_pipeline = Pipelines.compute(Shader, m_layout, Specialization, Name, Guard); return m_pipeline != VK_NULL_HANDLE; } diff --git a/rendering/vulkan14/vulkan14compute.h b/rendering/vulkan14/vulkan14compute.h index 318d063c3..27d7181bd 100644 --- a/rendering/vulkan14/vulkan14compute.h +++ b/rendering/vulkan14/vulkan14compute.h @@ -69,8 +69,9 @@ class compute_kernel compute_kernel &operator=(compute_kernel const &) = delete; // the kernel of the shader: Passlayout is the layout of the pass set of the scene, set 0 of every kernel; the bindings of - // set 1 are those the shader declares. Specialization: the values of the constants 0, 1, 2 ... - bool create(VkDevice Device, pipeline_library &Pipelines, std::shared_ptr const &Shader, VkDescriptorSetLayout Passlayout, std::vector const &Specialization, std::string const &Name); + // set 1 are those the shader declares. Specialization: the values of the constants 0, 1, 2 ...; Guard: how the pipeline is made + bool create(VkDevice Device, pipeline_library &Pipelines, std::shared_ptr const &Shader, VkDescriptorSetLayout Passlayout, std::vector const &Specialization, std::string const &Name, + PipelineGuard Guard = PipelineGuard::none); void destroy(VkDevice Device); explicit operator bool() const { diff --git a/rendering/vulkan14/vulkan14shaders.cpp b/rendering/vulkan14/vulkan14shaders.cpp index 7f6326901..6c7f560cd 100644 --- a/rendering/vulkan14/vulkan14shaders.cpp +++ b/rendering/vulkan14/vulkan14shaders.cpp @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -163,6 +164,22 @@ template void hash_value(std::uint64_t &Hash, Type_ const &Valu hash_bytes(Hash, &Value, sizeof(Value)); } +// a compute pipeline made under the guard against the driver crashing on it (pipeline_library::makeGuardedCompute()): the call +// alone, nothing with a destructor in the way of a fault of the driver +struct GuardedCompute +{ + VkDevice device{VK_NULL_HANDLE}; + VkComputePipelineCreateInfo const *info{nullptr}; + VkPipeline pipeline{VK_NULL_HANDLE}; + VkResult result{VK_ERROR_UNKNOWN}; +}; + +void runGuardedCompute(void *const context) +{ + auto *const job{static_cast(context)}; + job->result = vkCreateComputePipelines(job->device, VK_NULL_HANDLE, 1, job->info, nullptr, &job->pipeline); +} + std::string user_cache_dir(std::string const &Name) { // with a separator at the end @@ -421,6 +438,15 @@ bool pipeline_library::init(device const &Device, std::string &Reason) } } log_info("pipeline cache " + m_cachepath + (data.empty() ? " (empty)" : " (" + std::to_string(data.size() / 1024) + " KiB)")); + + // the driver the records of the crashes name: its build, as the identity of the pipeline cache tells it apart + auto const &caps{Device.caps()}; + std::string uuid; + for (auto const byte : caps.pipeline_cache_uuid) + { + uuid += std::format("{:02x}", byte); + } + crashGuard.Init(cachedir, std::format("vulkan {:04x}:{:04x} {} {} {} {:08x} {}", caps.vendor_id, caps.device_id, caps.device_name, caps.driver_name, caps.driver_info, caps.driver_version, uuid)); return true; } @@ -757,7 +783,8 @@ VkPipeline pipeline_library::get(pipeline_desc const &Desc) return keep(key, pipeline, std::chrono::duration(std::chrono::steady_clock::now() - start).count()); } -VkPipeline pipeline_library::compute(std::shared_ptr const &Shader, VkPipelineLayout Layout, std::vector const &Specialization, std::string const &Name) +VkPipeline pipeline_library::compute(std::shared_ptr const &Shader, VkPipelineLayout Layout, std::vector const &Specialization, std::string const &Name, + PipelineGuard const Guard) { std::uint64_t key{14695981039346656037ull}; hash_value(key, Shader.get()); @@ -802,18 +829,48 @@ VkPipeline pipeline_library::compute(std::shared_ptr const &S info.layout = Layout; VkPipeline pipeline{VK_NULL_HANDLE}; - if (!VK14_VERIFY(vkCreateComputePipelines(m_device->handle(), m_cache, 1, &info, nullptr, &pipeline))) + if (Guard == PipelineGuard::driverCrash) + { + // the program to the guard: the code and the constants, so a changed shader is tried again with a driver which crashed on it + std::uint64_t code{14695981039346656037ull}; + hash_bytes(code, Shader->spirv.data(), Shader->spirv.size() * sizeof(std::uint32_t)); + for (auto const value : Specialization) + { + hash_value(code, value); + } + pipeline = makeGuardedCompute(info, std::format("compute pipeline {} {:016x}", (Name.empty() ? Shader->name : Name), code), Name); + } + else if (!VK14_VERIFY(vkCreateComputePipelines(m_device->handle(), m_cache, 1, &info, nullptr, &pipeline))) { log_error("the compute pipeline " + Name + " can't be made"); pipeline = VK_NULL_HANDLE; } - else + if (pipeline != VK_NULL_HANDLE) { name_object(m_device->handle(), VK_OBJECT_TYPE_PIPELINE, handle_value(pipeline), Name); } return keep(key, pipeline, std::chrono::duration(std::chrono::steady_clock::now() - start).count()); } +VkPipeline pipeline_library::makeGuardedCompute(VkComputePipelineCreateInfo const &info, std::string const &key, std::string const &name) +{ + // no pipeline cache: the driver may have left a lock of it taken if it faulted in the middle. the drivers keep the compiled + // code on the disk themselves, so the pipeline is still made quickly in the sessions after + GuardedCompute job{m_device->handle(), &info}; + auto const outcome{crashGuard.Run(key, &runGuardedCompute, &job)}; + if (outcome != gfx::DriverCrashGuard::Outcome::made) + { + log_error("the compute pipeline " + name + " isn't made: the driver crashed on it"); + return VK_NULL_HANDLE; + } + if (false == VK14_VERIFY(job.result)) + { + log_error("the compute pipeline " + name + " can't be made"); + return VK_NULL_HANDLE; + } + return job.pipeline; +} + std::string pipeline_library::info() const { std::lock_guard lock(m_mutex); diff --git a/rendering/vulkan14/vulkan14shaders.h b/rendering/vulkan14/vulkan14shaders.h index b03bb1b59..6323be84b 100644 --- a/rendering/vulkan14/vulkan14shaders.h +++ b/rendering/vulkan14/vulkan14shaders.h @@ -24,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "rendering/vulkan14/vulkan14common.h" +#include "rendering/common/drivercrashguard.h" #include "rendering/common/shadersource.h" #include @@ -121,6 +122,15 @@ struct pipeline_desc std::string name; }; +// how a compute pipeline is made +enum class PipelineGuard +{ + none, + // under the guard against the driver crashing on it (gfx::DriverCrashGuard): for the pipelines the renderer can go without. + // one the driver crashed on comes back null, now and in the sessions after with the same driver + driverCrash +}; + class pipeline_library { public: @@ -141,13 +151,18 @@ class pipeline_library VkPipeline get(pipeline_desc const &Desc); // the pipeline of the description when it was made already (Pipeline: it, null when it couldn't be); false: not made yet bool find(pipeline_desc const &Desc, VkPipeline &Pipeline) const; - VkPipeline compute(std::shared_ptr const &Shader, VkPipelineLayout Layout, std::vector const &Specialization = {}, std::string const &Name = {}); + VkPipeline compute(std::shared_ptr const &Shader, VkPipelineLayout Layout, std::vector const &Specialization = {}, std::string const &Name = {}, + PipelineGuard Guard = PipelineGuard::none); std::string info() const; private: std::uint64_t key_of(pipeline_desc const &Desc) const; // the pipeline made for the key by another thread meanwhile is kept, the one of the caller destroyed VkPipeline keep(std::uint64_t Key, VkPipeline Pipeline, double Milliseconds); + // the compute pipeline of Info made under crashGuard, the program named to it by Key + VkPipeline makeGuardedCompute(VkComputePipelineCreateInfo const &info, std::string const &key, std::string const &name); + + gfx::DriverCrashGuard crashGuard; mutable std::mutex m_mutex; device const *m_device{nullptr}; diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index 61910c0f7..46817874c 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -119,7 +119,9 @@ bool windscreen_water::gpu_init() { try { - if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i])) + // under the guard against the driver crashing on a kernel (the compiler of the NVIDIA driver 610.88 did on + // water_snowlayer.comp): the glasses then go without the snow, or without the simulation + if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i], PipelineGuard::driverCrash)) { throw gfx::shader_exception(std::string("no compute pipeline of ") + names[i]); } diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl index 897ae70b9..6a06b4310 100644 --- a/shaders/ogl46/snow_sprites.glsl +++ b/shaders/ogl46/snow_sprites.glsl @@ -184,19 +184,39 @@ struct lump_grid float share; // the share of its cells having a lump at all (1: all of them) }; -// the tiles of the lumps, as the grids take them: the fleece (2-5, and the clumps made of it, 8, 9) and the packed snow (10-15) -const int sn_lump_tiles[12] = int[12](2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15); +// the tables of the snow below are worked out by branches and sums, not read from constant arrays indexed by a number known only +// while running, and the lists of the layer are written whole words at a time (snRefPut()): the compiler of the NVIDIA driver +// 610.88 crashed on water_snowlayer.comp made the other way (a read of address 8 in nvgpucomp64.dll), which took the whole +// simulator down as the cab loaded + +// the tiles of the lumps, as the grids take them: the fleece (2-5, and the clumps made of it, 8, 9) and the packed snow (10-15). +// Index 0 .. 11: the tiles 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15 +int snLumpTile(int index) +{ + return index + ((index < 4) ? 2 : 4); +} // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid // (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5, 8, 9), more and bigger, closing // the glass by 2-3 mm; now and then a single lump of packed snow on top (tiles 10-15) const int SN_GRIDS = 5; -const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( - lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03), - lump_grid(vec2(0.75), 251u, vec2(1.0, 2.6), vec2(2.0, 3.0), 2, 4, 1.0), - lump_grid(vec2(0.0, 0.5), 233u, vec2(0.6, 1.8), vec2(2.0, 3.0), 0, 6, 1.0), - lump_grid(vec2(0.75, 0.25), 151u, vec2(0.2, 1.0), vec2(1.8, 2.8), 2, 4, 1.0), - lump_grid(vec2(0.0), 31u, vec2(0.02, 0.5), vec2(1.4, 2.4), 2, 4, 1.0)); +// Grid 0 .. SN_GRIDS - 1 +lump_grid snGrid(int grid) +{ + switch (grid) + { + case 0: + return lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03); + case 1: + return lump_grid(vec2(0.75), 251u, vec2(1.0, 2.6), vec2(2.0, 3.0), 2, 4, 1.0); + case 2: + return lump_grid(vec2(0.0, 0.5), 233u, vec2(0.6, 1.8), vec2(2.0, 3.0), 0, 6, 1.0); + case 3: + return lump_grid(vec2(0.75, 0.25), 151u, vec2(0.2, 1.0), vec2(1.8, 2.8), 2, 4, 1.0); + default: + return lump_grid(vec2(0.0), 31u, vec2(0.02, 0.5), vec2(1.4, 2.4), 2, 4, 1.0); + } +} // (nine grids before: each grid alone covers the glass a few times over, so five close it as well, with fewer sprites one on // another at a pixel) @@ -258,7 +278,7 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - int tile = sn_lump_tiles[grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1)]; + int tile = snLumpTile(grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1)); float random = RandF(seed); float aniso = mix(0.8, 1.0, RandF(seed)); float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); @@ -332,13 +352,14 @@ snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) vec2 perL = span / snow_lump_cell; for (int g = 0; g < SN_GRIDS; ++g) { - vec2 pL = uv * perL + sn_grids[g].shift; + lump_grid grid = snGrid(g); + vec2 pL = uv * perL + grid.shift; ivec2 hereL = ivec2(floor(pL)); for (int k = 0; k < 9; ++k) { if (layer.a >= SN_COVERED) return snFinish(flakes, layer); // the grids over this one cover the pixel - snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, 0.0, layer); + snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, grid, pixelUV, 0.0, layer); } } return snFinish(flakes, layer); @@ -353,13 +374,35 @@ const int SN_REFS = 6; // the top ones, the listing stops when full (sixteen // the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out const float SN_LIST_COVERED = 0.97; -void snRef(uint ref, inout uvec4 refs, inout int count) +// the list Refs with the sprite Ref put at its place Count (0 .. 15) +uvec4 snRefPut(uvec4 refs, int count, uint ref) { - if (count >= SN_REFS) - return; uint shift = 8u * uint(count & 3); - refs[count >> 2] = (refs[count >> 2] & ~(255u << shift)) | ((ref + 1u) << shift); - ++count; + uint keep = ~(255u << shift); + uint bits = (ref + 1u) << shift; + int word = count >> 2; + if (word == 0) + refs.x = (refs.x & keep) | bits; + else if (word == 1) + refs.y = (refs.y & keep) | bits; + else if (word == 2) + refs.z = (refs.z & keep) | bits; + else + refs.w = (refs.w & keep) | bits; + return refs; +} + +// the word of the list Refs holding its place Count (0 .. 15) +uint snRefWord(uvec4 refs, int count) +{ + int word = count >> 2; + if (word == 0) + return refs.x; + if (word == 1) + return refs.y; + if (word == 2) + return refs.z; + return refs.w; } // the sprites of the texel of the layer centred at UV (PixelUV its size in the uv), as the layer holds them @@ -383,7 +426,10 @@ uvec4 snList(vec2 uv, vec2 span, float pixelUV) if (count >= 2) break; // two flakes at most, the rest of the list for the lumps if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) - snRef(uint(k), refs, count); + { + refs = snRefPut(refs, count, uint(k)); + ++count; + } } vec2 perL = span / snow_lump_cell; float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; @@ -391,14 +437,18 @@ uvec4 snList(vec2 uv, vec2 span, float pixelUV) { if ((layer.a >= SN_LIST_COVERED) || (count >= SN_REFS)) break; // the grids over this one cover the texel, or the list is full - vec2 pL = uv * perL + sn_grids[g].shift; + lump_grid grid = snGrid(g); + vec2 pL = uv * perL + grid.shift; ivec2 hereL = ivec2(floor(pL)); for (int k = 0; k < 9; ++k) { if (count >= SN_REFS) break; // the list is full: nothing more worked out, and the cover counts only the sprites the glass lays - if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, reachL, layer)) - snRef(uint(16 * (g + 1) + k), refs, count); + if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, grid, pixelUV, reachL, layer)) + { + refs = snRefPut(refs, count, uint(16 * (g + 1) + k)); + ++count; + } } } return refs; @@ -417,7 +467,7 @@ snow_layer_s snComposeRefs(vec2 uv, vec2 centreUV, vec2 span, float pixelUV, uve vec2 perL = span / snow_lump_cell; for (int r = 0; r < SN_REFS; ++r) { - uint ref = (refs[r >> 2] >> (8u * uint(r & 3))) & 255u; + uint ref = (snRefWord(refs, r) >> (8u * uint(r & 3))) & 255u; if (ref == 0u) break; --ref; @@ -431,13 +481,27 @@ snow_layer_s snComposeRefs(vec2 uv, vec2 centreUV, vec2 span, float pixelUV, uve } if ((list > SN_GRIDS) || (k >= 9) || (layer.a >= SN_COVERED)) continue; // nothing laid, or the grids over this one cover the pixel - lump_grid grid = sn_grids[list - 1]; + lump_grid grid = snGrid(list - 1); ivec2 here = ivec2(floor(centreUV * perL + grid.shift)); snLumpCell(uv * perL + grid.shift, here + offset, perL, grid, pixelUV, 0.0, layer); } return snFinish(flakes, layer); } +// the K-th (0 .. 8) of the texel itself, the ones beside it and the corners: (0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), +// (-1, 1), (1, -1), (-1, -1) +ivec2 snNear(int k) +{ + if (k == 0) + return ivec2(0); + if (k <= 4) + { + int side = ((k & 1) == 1) ? 1 : -1; + return (k <= 2) ? ivec2(side, 0) : ivec2(0, side); + } + return ivec2(((k & 1) == 1) ? 1 : -1, (k <= 6) ? 1 : -1); +} + // the metres of the glass in a unit of its uv at UV, from the texel of its map there or, at the edge of the glass, the nearest // one next to it the glass is on; false when there is none bool snSpan(uint slot, vec2 uv, out vec2 span) @@ -445,10 +509,9 @@ bool snSpan(uint slot, vec2 uv, out vec2 span) span = vec2(0.05); ivec2 at = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); // the texel itself first, then the ones beside it, then the corners - const ivec2 near[9] = ivec2[9](ivec2(0), ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1), ivec2(1), ivec2(-1, 1), ivec2(1, -1), ivec2(-1)); for (int k = 0; k < 9; ++k) { - ivec2 t = clamp(at + near[k], ivec2(0), ivec2(WATER_MAP - 1)); + ivec2 t = clamp(at + snNear(k), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (slot * uint(WATER_MAP * WATER_MAP) + uint(t.y * WATER_MAP + t.x)) * 2u; if (water_axes[axis].w > 0.0) { diff --git a/shaders/ogl46/water_snowlayer.comp b/shaders/ogl46/water_snowlayer.comp index a27a884dc..516a9bf9f 100644 --- a/shaders/ogl46/water_snowlayer.comp +++ b/shaders/ogl46/water_snowlayer.comp @@ -26,14 +26,16 @@ const float SNOW_LAYER_BLADE_MARGIN = 0.06; // whether a blade went over the texel of the map, or near it, in the step bool snow_layer_swept(uint mapTexel) { - vec4 place = water_blades[mapTexel]; for (int blade = 0; blade < 4; ++blade) { float now = water_blades_now[blade]; float before = water_blades_before[blade]; - if ((now < 0.0) || (now == before) || (place[blade] <= 0.001)) + // read from the storage as water_snow.comp does, not from a copy in a local vec4 indexed by the blade (snow_sprites.glsl: + // the compiler of the NVIDIA driver 610.88 crashed on this kernel) + float place = water_blades[mapTexel][blade]; + if ((now < 0.0) || (now == before) || (place <= 0.001)) continue; - if ((place[blade] >= min(now, before) - SNOW_LAYER_BLADE_MARGIN) && (place[blade] <= max(now, before) + SNOW_LAYER_BLADE_MARGIN)) + if ((place >= min(now, before) - SNOW_LAYER_BLADE_MARGIN) && (place <= max(now, before) + SNOW_LAYER_BLADE_MARGIN)) return true; } return false; diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl index 897ae70b9..6a06b4310 100644 --- a/shaders/vk14/snow_sprites.glsl +++ b/shaders/vk14/snow_sprites.glsl @@ -184,19 +184,39 @@ struct lump_grid float share; // the share of its cells having a lump at all (1: all of them) }; -// the tiles of the lumps, as the grids take them: the fleece (2-5, and the clumps made of it, 8, 9) and the packed snow (10-15) -const int sn_lump_tiles[12] = int[12](2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15); +// the tables of the snow below are worked out by branches and sums, not read from constant arrays indexed by a number known only +// while running, and the lists of the layer are written whole words at a time (snRefPut()): the compiler of the NVIDIA driver +// 610.88 crashed on water_snowlayer.comp made the other way (a read of address 8 in nvgpucomp64.dll), which took the whole +// simulator down as the cab loaded + +// the tiles of the lumps, as the grids take them: the fleece (2-5, and the clumps made of it, 8, 9) and the packed snow (10-15). +// Index 0 .. 11: the tiles 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15 +int snLumpTile(int index) +{ + return index + ((index < 4) ? 2 : 4); +} // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid // (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5, 8, 9), more and bigger, closing // the glass by 2-3 mm; now and then a single lump of packed snow on top (tiles 10-15) const int SN_GRIDS = 5; -const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( - lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03), - lump_grid(vec2(0.75), 251u, vec2(1.0, 2.6), vec2(2.0, 3.0), 2, 4, 1.0), - lump_grid(vec2(0.0, 0.5), 233u, vec2(0.6, 1.8), vec2(2.0, 3.0), 0, 6, 1.0), - lump_grid(vec2(0.75, 0.25), 151u, vec2(0.2, 1.0), vec2(1.8, 2.8), 2, 4, 1.0), - lump_grid(vec2(0.0), 31u, vec2(0.02, 0.5), vec2(1.4, 2.4), 2, 4, 1.0)); +// Grid 0 .. SN_GRIDS - 1 +lump_grid snGrid(int grid) +{ + switch (grid) + { + case 0: + return lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03); + case 1: + return lump_grid(vec2(0.75), 251u, vec2(1.0, 2.6), vec2(2.0, 3.0), 2, 4, 1.0); + case 2: + return lump_grid(vec2(0.0, 0.5), 233u, vec2(0.6, 1.8), vec2(2.0, 3.0), 0, 6, 1.0); + case 3: + return lump_grid(vec2(0.75, 0.25), 151u, vec2(0.2, 1.0), vec2(1.8, 2.8), 2, 4, 1.0); + default: + return lump_grid(vec2(0.0), 31u, vec2(0.02, 0.5), vec2(1.4, 2.4), 2, 4, 1.0); + } +} // (nine grids before: each grid alone covers the glass a few times over, so five close it as well, with fewer sprites one on // another at a pixel) @@ -258,7 +278,7 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - int tile = sn_lump_tiles[grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1)]; + int tile = snLumpTile(grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1)); float random = RandF(seed); float aniso = mix(0.8, 1.0, RandF(seed)); float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); @@ -332,13 +352,14 @@ snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) vec2 perL = span / snow_lump_cell; for (int g = 0; g < SN_GRIDS; ++g) { - vec2 pL = uv * perL + sn_grids[g].shift; + lump_grid grid = snGrid(g); + vec2 pL = uv * perL + grid.shift; ivec2 hereL = ivec2(floor(pL)); for (int k = 0; k < 9; ++k) { if (layer.a >= SN_COVERED) return snFinish(flakes, layer); // the grids over this one cover the pixel - snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, 0.0, layer); + snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, grid, pixelUV, 0.0, layer); } } return snFinish(flakes, layer); @@ -353,13 +374,35 @@ const int SN_REFS = 6; // the top ones, the listing stops when full (sixteen // the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out const float SN_LIST_COVERED = 0.97; -void snRef(uint ref, inout uvec4 refs, inout int count) +// the list Refs with the sprite Ref put at its place Count (0 .. 15) +uvec4 snRefPut(uvec4 refs, int count, uint ref) { - if (count >= SN_REFS) - return; uint shift = 8u * uint(count & 3); - refs[count >> 2] = (refs[count >> 2] & ~(255u << shift)) | ((ref + 1u) << shift); - ++count; + uint keep = ~(255u << shift); + uint bits = (ref + 1u) << shift; + int word = count >> 2; + if (word == 0) + refs.x = (refs.x & keep) | bits; + else if (word == 1) + refs.y = (refs.y & keep) | bits; + else if (word == 2) + refs.z = (refs.z & keep) | bits; + else + refs.w = (refs.w & keep) | bits; + return refs; +} + +// the word of the list Refs holding its place Count (0 .. 15) +uint snRefWord(uvec4 refs, int count) +{ + int word = count >> 2; + if (word == 0) + return refs.x; + if (word == 1) + return refs.y; + if (word == 2) + return refs.z; + return refs.w; } // the sprites of the texel of the layer centred at UV (PixelUV its size in the uv), as the layer holds them @@ -383,7 +426,10 @@ uvec4 snList(vec2 uv, vec2 span, float pixelUV) if (count >= 2) break; // two flakes at most, the rest of the list for the lumps if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) - snRef(uint(k), refs, count); + { + refs = snRefPut(refs, count, uint(k)); + ++count; + } } vec2 perL = span / snow_lump_cell; float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; @@ -391,14 +437,18 @@ uvec4 snList(vec2 uv, vec2 span, float pixelUV) { if ((layer.a >= SN_LIST_COVERED) || (count >= SN_REFS)) break; // the grids over this one cover the texel, or the list is full - vec2 pL = uv * perL + sn_grids[g].shift; + lump_grid grid = snGrid(g); + vec2 pL = uv * perL + grid.shift; ivec2 hereL = ivec2(floor(pL)); for (int k = 0; k < 9; ++k) { if (count >= SN_REFS) break; // the list is full: nothing more worked out, and the cover counts only the sprites the glass lays - if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, reachL, layer)) - snRef(uint(16 * (g + 1) + k), refs, count); + if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, grid, pixelUV, reachL, layer)) + { + refs = snRefPut(refs, count, uint(16 * (g + 1) + k)); + ++count; + } } } return refs; @@ -417,7 +467,7 @@ snow_layer_s snComposeRefs(vec2 uv, vec2 centreUV, vec2 span, float pixelUV, uve vec2 perL = span / snow_lump_cell; for (int r = 0; r < SN_REFS; ++r) { - uint ref = (refs[r >> 2] >> (8u * uint(r & 3))) & 255u; + uint ref = (snRefWord(refs, r) >> (8u * uint(r & 3))) & 255u; if (ref == 0u) break; --ref; @@ -431,13 +481,27 @@ snow_layer_s snComposeRefs(vec2 uv, vec2 centreUV, vec2 span, float pixelUV, uve } if ((list > SN_GRIDS) || (k >= 9) || (layer.a >= SN_COVERED)) continue; // nothing laid, or the grids over this one cover the pixel - lump_grid grid = sn_grids[list - 1]; + lump_grid grid = snGrid(list - 1); ivec2 here = ivec2(floor(centreUV * perL + grid.shift)); snLumpCell(uv * perL + grid.shift, here + offset, perL, grid, pixelUV, 0.0, layer); } return snFinish(flakes, layer); } +// the K-th (0 .. 8) of the texel itself, the ones beside it and the corners: (0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), +// (-1, 1), (1, -1), (-1, -1) +ivec2 snNear(int k) +{ + if (k == 0) + return ivec2(0); + if (k <= 4) + { + int side = ((k & 1) == 1) ? 1 : -1; + return (k <= 2) ? ivec2(side, 0) : ivec2(0, side); + } + return ivec2(((k & 1) == 1) ? 1 : -1, (k <= 6) ? 1 : -1); +} + // the metres of the glass in a unit of its uv at UV, from the texel of its map there or, at the edge of the glass, the nearest // one next to it the glass is on; false when there is none bool snSpan(uint slot, vec2 uv, out vec2 span) @@ -445,10 +509,9 @@ bool snSpan(uint slot, vec2 uv, out vec2 span) span = vec2(0.05); ivec2 at = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); // the texel itself first, then the ones beside it, then the corners - const ivec2 near[9] = ivec2[9](ivec2(0), ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1), ivec2(1), ivec2(-1, 1), ivec2(1, -1), ivec2(-1)); for (int k = 0; k < 9; ++k) { - ivec2 t = clamp(at + near[k], ivec2(0), ivec2(WATER_MAP - 1)); + ivec2 t = clamp(at + snNear(k), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (slot * uint(WATER_MAP * WATER_MAP) + uint(t.y * WATER_MAP + t.x)) * 2u; if (water_axes[axis].w > 0.0) { diff --git a/shaders/vk14/water_snowlayer.comp b/shaders/vk14/water_snowlayer.comp index 264e5881f..5a14c5e27 100644 --- a/shaders/vk14/water_snowlayer.comp +++ b/shaders/vk14/water_snowlayer.comp @@ -28,14 +28,16 @@ const float SNOW_LAYER_BLADE_MARGIN = 0.06; // whether a blade went over the texel of the map, or near it, in the step bool snow_layer_swept(uint mapTexel) { - vec4 place = water_blades[mapTexel]; for (int blade = 0; blade < 4; ++blade) { float now = water_blades_now[blade]; float before = water_blades_before[blade]; - if ((now < 0.0) || (now == before) || (place[blade] <= 0.001)) + // read from the storage as water_snow.comp does, not from a copy in a local vec4 indexed by the blade (snow_sprites.glsl: + // the compiler of the NVIDIA driver 610.88 crashed on this kernel) + float place = water_blades[mapTexel][blade]; + if ((now < 0.0) || (now == before) || (place <= 0.001)) continue; - if ((place[blade] >= min(now, before) - SNOW_LAYER_BLADE_MARGIN) && (place[blade] <= max(now, before) + SNOW_LAYER_BLADE_MARGIN)) + if ((place >= min(now, before) - SNOW_LAYER_BLADE_MARGIN) && (place <= max(now, before) + SNOW_LAYER_BLADE_MARGIN)) return true; } return false; diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 44684b79b..5262c9d25 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -36,6 +36,8 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/rendering/common/texturealpha.cpp" # and the movement of the free camera the motion blur takes "${CMAKE_SOURCE_DIR}/rendering/common/freecameramotion.cpp" + # and the guard against the graphics driver crashing on a program + "${CMAKE_SOURCE_DIR}/rendering/common/drivercrashguard.cpp" # and the http client the editor fetches its aids with "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" "${CMAKE_SOURCE_DIR}/utilities/asciiname.cpp" diff --git a/tests/unit/test_driver_crash_guard.cpp b/tests/unit/test_driver_crash_guard.cpp new file mode 100644 index 000000000..942fe883f --- /dev/null +++ b/tests/unit/test_driver_crash_guard.cpp @@ -0,0 +1,164 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "rendering/common/drivercrashguard.h" + +#include +#include +#include +#include +#include + +#if defined(_MSC_VER) +#include +#endif + +// the programs a graphics driver crashed on while it compiled them (rendering/common/drivercrashguard.h): written down before the +// driver gets them, crossed out after; one whose fault was caught, or one left behind by two sessions the driver took down, isn't +// made again with that driver +namespace { + +std::string readFile(std::string const &path) { + std::ifstream file{path}; + return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; +} + +struct MakeCall { + int calls{0}; + std::string attemptPath; + std::string attemptSeen; // what the attempt file held while the program was made +}; + +void makeProgram(void *const context) { + auto *const call{static_cast(context)}; + ++call->calls; + call->attemptSeen = readFile(call->attemptPath); +} + +void throwFromMake(void *const context) { + makeProgram(context); + throw std::runtime_error("no program"); +} + +#if defined(_MSC_VER) +void faultInMake(void *const context) { + makeProgram(context); + ::RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, nullptr); +} +#endif + +} // namespace + +TEST_CASE("driver crash guard: a program made is written down while the driver has it, then crossed out") { + test::scratch_folder const folder{"driver_crash_guard_made"}; + gfx::DriverCrashGuard guard; + guard.Init(folder.path(), "vulkan nvidia 610.88"); + MakeCall call{0, folder.path("driver_crash_attempt.txt")}; + CHECK(guard.Run("compute pipeline water_snowlayer.comp 0123", &makeProgram, &call) == gfx::DriverCrashGuard::Outcome::made); + CHECK(call.calls == 1); + CHECK(call.attemptSeen == "vulkan nvidia 610.88\tcompute pipeline water_snowlayer.comp 0123\n"); + CHECK_FALSE(std::filesystem::exists(folder.path("driver_crash_attempt.txt"))); + CHECK_FALSE(guard.Crashed("compute pipeline water_snowlayer.comp 0123")); + // and made again the next time + CHECK(guard.Run("compute pipeline water_snowlayer.comp 0123", &makeProgram, &call) == gfx::DriverCrashGuard::Outcome::made); + CHECK(call.calls == 2); +} + +TEST_CASE("driver crash guard: a session ending once while the driver makes a program leaves it suspect, still made") { + test::scratch_folder const folder{"driver_crash_guard_suspect"}; + folder.write("driver_crash_attempt.txt", "vulkan nvidia 610.88\tcompute pipeline water_gather.comp 0123\n"); + + gfx::DriverCrashGuard guard; + guard.Init(folder.path(), "vulkan nvidia 610.88"); + CHECK_FALSE(std::filesystem::exists(folder.path("driver_crash_attempt.txt"))); + CHECK_FALSE(std::filesystem::exists(folder.path("driver_crashes.txt"))); + CHECK(guard.Suspect("compute pipeline water_gather.comp 0123")); + CHECK_FALSE(guard.Crashed("compute pipeline water_gather.comp 0123")); + // made well, it is no longer suspect, in this session or the next + MakeCall call{0, folder.path("driver_crash_attempt.txt")}; + CHECK(guard.Run("compute pipeline water_gather.comp 0123", &makeProgram, &call) == gfx::DriverCrashGuard::Outcome::made); + CHECK(call.calls == 1); + CHECK_FALSE(guard.Suspect("compute pipeline water_gather.comp 0123")); + gfx::DriverCrashGuard next; + next.Init(folder.path(), "vulkan nvidia 610.88"); + CHECK_FALSE(next.Suspect("compute pipeline water_gather.comp 0123")); + + // a leftover of another driver doesn't matter + folder.write("driver_crash_attempt.txt", "vulkan nvidia 600.00\tcompute pipeline water_gather.comp 0123\n"); + gfx::DriverCrashGuard updated; + updated.Init(folder.path(), "vulkan nvidia 610.88"); + CHECK_FALSE(updated.Suspect("compute pipeline water_gather.comp 0123")); + CHECK_FALSE(std::filesystem::exists(folder.path("driver_crash_attempt.txt"))); +} + +TEST_CASE("driver crash guard: the program two sessions were making when they ended isn't made again with that driver") { + test::scratch_folder const folder{"driver_crash_guard_attempt"}; + folder.write("driver_crash_attempt.txt", "vulkan nvidia 610.88\tcompute pipeline water_snowlayer.comp 0123\n"); + gfx::DriverCrashGuard first; + first.Init(folder.path(), "vulkan nvidia 610.88"); + CHECK(first.Suspect("compute pipeline water_snowlayer.comp 0123")); + // the second session ends while it makes the program again + folder.write("driver_crash_attempt.txt", "vulkan nvidia 610.88\tcompute pipeline water_snowlayer.comp 0123\n"); + + gfx::DriverCrashGuard guard; + guard.Init(folder.path(), "vulkan nvidia 610.88"); + CHECK_FALSE(std::filesystem::exists(folder.path("driver_crash_attempt.txt"))); + CHECK(readFile(folder.path("driver_crashes.txt")) == "vulkan nvidia 610.88\tcompute pipeline water_snowlayer.comp 0123\n"); + CHECK(readFile(folder.path("driver_crash_suspects.txt")).empty()); + CHECK(guard.Crashed("compute pipeline water_snowlayer.comp 0123")); + CHECK_FALSE(guard.Suspect("compute pipeline water_snowlayer.comp 0123")); + MakeCall call{0, folder.path("driver_crash_attempt.txt")}; + CHECK(guard.Run("compute pipeline water_snowlayer.comp 0123", &makeProgram, &call) == gfx::DriverCrashGuard::Outcome::skipped); + CHECK(call.calls == 0); + // another program, and the same one changed (another hash), are made + CHECK(guard.Run("compute pipeline water_snow.comp 4567", &makeProgram, &call) == gfx::DriverCrashGuard::Outcome::made); + CHECK(guard.Run("compute pipeline water_snowlayer.comp 89ab", &makeProgram, &call) == gfx::DriverCrashGuard::Outcome::made); + CHECK(call.calls == 2); + + // the records are read again by the next session; another version of the driver tries the program again + gfx::DriverCrashGuard same; + same.Init(folder.path(), "vulkan nvidia 610.88"); + CHECK(same.Crashed("compute pipeline water_snowlayer.comp 0123")); + gfx::DriverCrashGuard updated; + updated.Init(folder.path(), "vulkan nvidia 621.14"); + CHECK_FALSE(updated.Crashed("compute pipeline water_snowlayer.comp 0123")); + CHECK(updated.Run("compute pipeline water_snowlayer.comp 0123", &makeProgram, &call) == gfx::DriverCrashGuard::Outcome::made); +} + +TEST_CASE("driver crash guard: an exception of the program goes on through, the program crossed out and not recorded") { + test::scratch_folder const folder{"driver_crash_guard_exception"}; + gfx::DriverCrashGuard guard; + guard.Init(folder.path(), "opengl nvidia 610.88"); + MakeCall call{0, folder.path("driver_crash_attempt.txt")}; + CHECK_THROWS_AS(guard.Run("program water_snowlayer.comp 0123", &throwFromMake, &call), std::runtime_error); + CHECK(call.calls == 1); + CHECK_FALSE(std::filesystem::exists(folder.path("driver_crash_attempt.txt"))); + CHECK_FALSE(std::filesystem::exists(folder.path("driver_crashes.txt"))); + CHECK_FALSE(guard.Crashed("program water_snowlayer.comp 0123")); +} + +TEST_CASE("driver crash guard: tabs and line ends of the names don't break the records") { + test::scratch_folder const folder{"driver_crash_guard_fields"}; + folder.write("driver_crashes.txt", "vulkan nvidia 610.88\tprogram a b\r\n"); + gfx::DriverCrashGuard guard; + guard.Init(folder.path(), "vulkan\tnvidia\n610.88"); + CHECK(guard.Crashed("program\ta\rb")); +} + +#if defined(_MSC_VER) +TEST_CASE("driver crash guard: a fault of the driver is caught, recorded and the program not made again") { + test::scratch_folder const folder{"driver_crash_guard_fault"}; + gfx::DriverCrashGuard guard; + guard.Init(folder.path(), "vulkan nvidia 610.88"); + MakeCall call{0, folder.path("driver_crash_attempt.txt")}; + CHECK(guard.Run("compute pipeline water_snowlayer.comp 0123", &faultInMake, &call) == gfx::DriverCrashGuard::Outcome::crashed); + CHECK(call.calls == 1); + CHECK_FALSE(std::filesystem::exists(folder.path("driver_crash_attempt.txt"))); + CHECK(readFile(folder.path("driver_crashes.txt")) == "vulkan nvidia 610.88\tcompute pipeline water_snowlayer.comp 0123\n"); + CHECK(guard.Run("compute pipeline water_snowlayer.comp 0123", &makeProgram, &call) == gfx::DriverCrashGuard::Outcome::skipped); + CHECK(call.calls == 1); + CHECK_FALSE(gfx::CallCatchingFaults(&faultInMake, &call)); + CHECK(gfx::CallCatchingFaults(&makeProgram, &call)); +} +#endif From ae2ce61e9a6a7b21ed7a12b82a97192c79f3b73b Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Mon, 30 Nov 2026 20:09:18 +0100 Subject: [PATCH 17/20] fix(vulkan): stickers on vehicles no longer vanish behind the body seen at an angle With the depth prepass of the scene, the colour pass of the alpha tested materials (default, normalmap, pbr, ...) doesn't write the depth the prepass drew (keepdepth) and tested it without a bias. The prepass draws everything a little farther (constant -1, slope -1), so a surface lying up to a pixel's worth of the slope behind the front one passed as well, and the one drawn last covered the other. Seen from the side a few metres away that is more than a millimetre: the warning stickers 1 mm off the buffer beam of the EP07 (303e) vanished under the beam, drawn after them. Those draws now test their depth with the bias of the prepass, nearer by two units and 1/16 of the slope (the position is invariant in both programs). The colour pass sets its bias in apply_draw_state() for the kept draws and the decals together; the depth drawn inside the colour pass holds its own. The OpenGL 4.6 renderer writes the depth in its colour pass and isn't affected. No asset changes. --- rendering/vulkan14/vulkan14context.h | 8 ++- rendering/vulkan14/vulkan14frame.cpp | 3 ++ rendering/vulkan14/vulkan14indirect.cpp | 13 ++++- rendering/vulkan14/vulkan14scene.cpp | 71 +++++++++++++++++++++---- 4 files changed, 82 insertions(+), 13 deletions(-) diff --git a/rendering/vulkan14/vulkan14context.h b/rendering/vulkan14/vulkan14context.h index 26010523c..b676f7d39 100644 --- a/rendering/vulkan14/vulkan14context.h +++ b/rendering/vulkan14/vulkan14context.h @@ -796,6 +796,7 @@ struct vulkan14_renderer::draw_state VkCullModeFlags cull{VK_CULL_MODE_FLAG_BITS_MAX_ENUM}; int depthtest{-1}; int depthwrite{-1}; + int depthBias{-1}; // the bias of the colour pass apply_draw_state() set (colourDepthBias()), -1 not known std::uint32_t pushed_draw{~0u}; // the state of the walk (setup_drawing() and the glare of the opengl renderer) bool blending{false}; @@ -805,9 +806,14 @@ struct vulkan14_renderer::draw_state // the colour pass of the opaque scene after its depth (render_scene_depth()), keepdepth: the draws whose depth the prepass drew with // the alpha test (prepassed, set by walk_material()) find it in the depth buffer and don't write it again. without the write the // depth is tested before their fragment shaders, which discard, and the hidden leaves aren't lit. the solid surfaces write theirs - // as they did, so what's in front of what stays as it was + // as they did. what's in front of what among the draws which don't write it is kept by the bias they test it with + // (colourDepthBias()) bool keepdepth{false}; bool prepassed{false}; + // a decal drawn pulled towards the camera, over the surface it lies on (walk_decal()) + bool decal{false}; + // the bias is the one of the depth drawn inside the colour pass (draw_indirect_depth()), apply_draw_state() leaves it as it is + bool biasHeld{false}; // the pipelines and the textures a draw needs first may be made by the background threads, the draw left out till then (the walks // of the scene, gfx.vulkan.asyncresources); the draws outside of them (the cab, the sky, the particles) wait for what they need bool async{false}; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 1cd33df8b..e6682fd5d 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1195,6 +1195,9 @@ void vulkan14_renderer::start_draws(vk14::target_formats const &Targets, int con draw.cull = VK_CULL_MODE_FLAG_BITS_MAX_ENUM; draw.depthtest = -1; draw.depthwrite = -1; + draw.depthBias = -1; + draw.decal = false; + draw.biasHeld = false; draw.pushed_draw = ~0u; draw.block = ~0u; draw.cullface = true; diff --git a/rendering/vulkan14/vulkan14indirect.cpp b/rendering/vulkan14/vulkan14indirect.cpp index d47428fe7..236e7e542 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -257,6 +257,8 @@ void vulkan14_renderer::resume_rendering() auto const cullface{draw.cullface}; auto const glare{draw.glare}; auto const depthmask_off{draw.depthmask_off}; + auto const decal{draw.decal}; + auto const biasHeld{draw.biasHeld}; auto *program{draw.program}; auto const textures{draw.textures}; start_draws(*draw.targets, static_cast(draw.extent.width), static_cast(draw.extent.height), set, shadows); @@ -264,11 +266,14 @@ void vulkan14_renderer::resume_rendering() draw.cullface = cullface; draw.glare = glare; draw.depthmask_off = depthmask_off; + draw.decal = decal; + draw.biasHeld = biasHeld; draw.program = program; draw.textures = textures; - if (draw.depthpass) + if (draw.depthpass || draw.biasHeld) { - // the bias of the depth pass of the scene (render_scene_depth()) + // the bias of the depth pass of the scene (render_scene_depth()) and of the depth drawn inside the colour pass + // (draw_indirect_depth()) commands->set_depth_bias_enable(VK_TRUE); commands->set_depth_bias(-1.f, 0.f, -1.f); } @@ -565,6 +570,7 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_depth(vk14:: { commands->set_depth_bias_enable(VK_TRUE); commands->set_depth_bias(-1.f, 0.f, -1.f); + draw.biasHeld = true; } walk_blending(false); // the draws without the alpha test first, then the ones with it, one program each @@ -616,6 +622,9 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_depth(vk14:: if (insidecolour) { commands->set_depth_bias_enable(VK_FALSE); + // the draws of the colour pass set theirs again (apply_draw_state()) + draw.biasHeld = false; + draw.depthBias = -1; } return counts; } diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 0e221446a..9598f7f9f 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -309,6 +309,46 @@ VkImageView layer_view(VkDevice Device, vk14::image const &Image, std::uint32_t return view; } +// the biases of the depth, constant and slope. the depth is reversed (VK_COMPARE_OP_GREATER_OR_EQUAL): a positive bias comes nearer +// the camera. the depth pass of the scene draws everything a little farther than it lies (render_scene_depth()) +struct DepthBias +{ + float constant{0.f}; + float slope{0.f}; +}; +constexpr DepthBias prepassBias{-1.f, -1.f}; +// a decal goes as much nearer as glPolygonOffset(2, 8) of the opengl renderer takes it (slope 2, constant 8) +constexpr DepthBias decalBias{8.f, 2.f}; +// a draw whose depth the prepass kept (draw_state::keepdepth) doesn't write it, and passes wherever its own depth is as near as the +// one there. tested without a bias, it passed on a surface lying up to the whole bias of the prepass behind the one the prepass found +// in front (a pixel's worth of the slope: at a grazing angle a few millimetres some metres away), and the draw made last covered the +// other one: a sticker a millimetre off the body of a vehicle, drawn before the body, was lost. so it tests its depth moved as the +// prepass moved it, nearer by two units and a sixteenth of the slope for what the two programs may still work out apart (the +// position is invariant in both) +constexpr DepthBias keptBias{prepassBias.constant + 2.f, prepassBias.slope + 1.f / 16.f}; + +// the bias of a draw of the colour pass of the kind colourDepthKind() gives +DepthBias colourDepthBias(int const Kind) +{ + DepthBias bias; + if ((Kind & 2) != 0) + { + bias = keptBias; + } + if ((Kind & 1) != 0) + { + bias.constant += decalBias.constant; + bias.slope += decalBias.slope; + } + return bias; +} + +// which bias a draw of the colour pass tests its depth with: 0 none, 1 a decal, 2 its depth kept from the prepass, 3 both +int colourDepthKind(bool const Kept, bool const Decal) +{ + return (Kept ? 2 : 0) | (Decal ? 1 : 0); +} + } // namespace // the resources of the scene @@ -1871,22 +1911,17 @@ void vulkan14_renderer::walk_decal(bool const Enabled) { return; } - // the depth is reversed (VK_COMPARE_OP_GREATER_OR_EQUAL): a positive bias comes nearer the camera, as glPolygonOffset(2, 8) of - // the opengl renderer (slope 2, constant 8). the depth pass of the scene draws everything a little farther (-1, -1, - // render_scene_depth()), the decal goes as much nearer from there + // the depth pass of the scene draws everything a little farther (render_scene_depth()), the decal goes as much nearer from there if (draw.depthpass) { if (Enabled) - draw.commands->set_depth_bias(-1.f + 8.f, 0.f, -1.f + 2.f); + draw.commands->set_depth_bias(prepassBias.constant + decalBias.constant, 0.f, prepassBias.slope + decalBias.slope); else - draw.commands->set_depth_bias(-1.f, 0.f, -1.f); + draw.commands->set_depth_bias(prepassBias.constant, 0.f, prepassBias.slope); return; } - draw.commands->set_depth_bias_enable(Enabled ? VK_TRUE : VK_FALSE); - if (Enabled) - { - draw.commands->set_depth_bias(8.f, 0.f, 2.f); - } + // the colour pass sets it with the draws (apply_draw_state()) + draw.decal = Enabled; } void vulkan14_renderer::walk_glare(bool const Enabled) @@ -2876,6 +2911,22 @@ void vulkan14_renderer::apply_draw_state(bool const Triangles) draw.commands->set_depth_write_enable(depthwrite ? VK_TRUE : VK_FALSE); draw.depthwrite = depthwrite; } + // the bias of the colour pass; the depth pass of the scene, the depth drawn inside the colour pass and the shadows set theirs + if (draw.shadows || draw.depthpass || draw.biasHeld) + { + return; + } + auto const biasKind{colourDepthKind(kept, draw.decal)}; + if (biasKind != draw.depthBias) + { + draw.commands->set_depth_bias_enable(biasKind != 0 ? VK_TRUE : VK_FALSE); + if (biasKind != 0) + { + auto const bias{colourDepthBias(biasKind)}; + draw.commands->set_depth_bias(bias.constant, 0.f, bias.slope); + } + draw.depthBias = biasKind; + } } // the textures of the draw pushed: the material's, the white stand-in where there is none or it isn't there yet From 0409591b72cd6da519225d6218b1cf8745f1cc2d Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Mon, 30 Nov 2026 20:51:52 +0100 Subject: [PATCH 18/20] fix(vulkan): the cab drawn early writes all of its depth again Without rain or snow the colour pass draws the cab first (9b7d02e5). Since the depth of the prepass is kept for the alpha tested draws (ff2ff308), the cab drawn first fell under that too: its screens, stickers and desk lamps wrote no depth of their own, and what came after them, the scene and the simplified desk (cab1) of the outer model a few centimetres behind, came through in patches cut along the triangles. The released exe shows it as well. The early cab now writes its depth, as in the rain and in the OpenGL renderer; the rest of the scene keeps the depth of the prepass as before. --- rendering/vulkan14/vulkan14frame.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index e6682fd5d..7ef1b5f3a 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1870,9 +1870,12 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) // opaque parts... what the prepass drew with the alpha test keeps its depth (draw_state::keepdepth) ctx.passes.begin_pass("colour, opaque"); - m_draw->keepdepth = scenedepth && m_keepprepassdepth && (false == m_prepassincomplete); + auto const keepPrepassDepth{scenedepth && m_keepprepassdepth && (false == m_prepassincomplete)}; walk_blending(false); - // without rain/snow we can render the cab early to limit the overdraw + // without rain/snow we can render the cab early to limit the overdraw. the cab writes all of its depth, as in the rain and in the + // opengl renderer: drawn first with the depth of the prepass kept, its alpha tested parts (the screens, the stickers, the lamps of + // the desk) left no depth of their own, and the simplified desk of the outer model a few centimetres behind them came through + m_draw->keepdepth = false; if (!FreeFlyModeFlag && Global.Overcast <= 1.0f && Global.render_cab && simulation::Train) { model_ubs.future = m_cabfuture; @@ -1886,6 +1889,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) } setup_shadow_color(m_shadowcolor); model_ubs.future = future; + m_draw->keepdepth = keepPrepassDepth; walk_region(simulation::Region, false); m_indirectcolourpending = false; m_draw->keepdepth = false; From c90113f4d397a758654598d8d145a435df9a6813 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Mon, 30 Nov 2026 23:37:40 +0100 Subject: [PATCH 19/20] fix(vulkan): textures filled by the host fall back to staging buffers where the driver can't make their images On a GeForce GTX 1050 (driver 582.28) every DDS texture loaded in the background came out white: the driver reports hostImageCopy for the format, but an image with VK_IMAGE_USAGE_HOST_TRANSFER_BIT can't be made (vmaCreateImage fails with VK_ERROR_FEATURE_NOT_PRESENT), and the texture was left without a gpu image. - The check of a format (once a format) also asks the allocator for the memory a trial image of the textures' kind would go to, and uses hostImageCopy only when there is such memory and it is device local. - Each texture is checked against the limits of the format for that use (maxExtent, maxMipLevels), which were left unread. - An image the driver still can't make is made again without the host transfer usage and filled through a staging buffer, and the rest of its format goes that way too. - The log says once a format which way its textures go. Devices where hostImageCopy works keep it: the check is made once a format. --- rendering/vulkan14/vulkan14texture.cpp | 145 +++++++++++++++++++++---- rendering/vulkan14/vulkan14texture.h | 22 +++- 2 files changed, 140 insertions(+), 27 deletions(-) diff --git a/rendering/vulkan14/vulkan14texture.cpp b/rendering/vulkan14/vulkan14texture.cpp index ff6951298..7b395a09f 100644 --- a/rendering/vulkan14/vulkan14texture.cpp +++ b/rendering/vulkan14/vulkan14texture.cpp @@ -16,8 +16,10 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" +#include #include #include +#include #include #include #include @@ -104,6 +106,24 @@ struct job_ticket std::atomic taken{false}; }; +// the image of a texture. one to be filled by the host (HostCopy) which the driver can't make after all is made to be filled through +// a staging buffer, HostCopy cleared, and so are the next ones of its format +bool createTextureImage(image &Target, allocator const &Memory, uploader &Uploads, image_desc &Desc, std::string const &Name, bool &HostCopy) +{ + if (Target.create(Memory, Desc, Name)) + { + return true; + } + if (false == HostCopy) + { + return false; + } + Uploads.RefuseHostCopy(Desc.format); + HostCopy = false; + Desc.usage &= ~VkImageUsageFlags{VK_IMAGE_USAGE_HOST_TRANSFER_BIT}; + return Target.create(Memory, Desc, Name); +} + } // namespace // uploader @@ -148,17 +168,53 @@ bool uploader::can_blit(VkFormat Format) const return result; } -bool uploader::can_host_copy(VkFormat Format) const +bool uploader::can_host_copy(VkFormat Format, VkExtent3D const &Extent, std::uint32_t const Mips) const { if (false == m_hostcopy) { return false; } - std::lock_guard lock(m_mutex); - auto const lookup{m_hostcopyable.find(Format)}; - if (lookup != m_hostcopyable.end()) + auto const limits{hostCopyLimits(Format)}; + return limits.usable && (Extent.width <= limits.maxExtent.width) && (Extent.height <= limits.maxExtent.height) && (Extent.depth <= limits.maxExtent.depth) && + (Mips <= limits.maxMips); +} + +void uploader::RefuseHostCopy(VkFormat Format) +{ + auto refused{false}; { - return lookup->second; + std::scoped_lock lock(m_mutex); + auto &limits{m_hostcopyable[Format]}; + refused = limits.usable; + limits.usable = false; + } + if (refused) + { + log_warning(std::format("the textures of format {} are filled through staging buffers: the driver can't make their images to be filled by the host, although it says it can", static_cast(Format))); + } +} + +uploader::HostCopyLimits uploader::hostCopyLimits(VkFormat Format) const +{ + { + std::scoped_lock lock(m_mutex); + if (auto const lookup{m_hostcopyable.find(Format)}; lookup != m_hostcopyable.end()) + { + return lookup->second; + } + } + // asked outside of the lock (the allocator makes a trial image); two threads asking at once find the same, the first one kept + auto const limits{probeHostCopy(Format)}; + std::scoped_lock lock(m_mutex); + return m_hostcopyable.try_emplace(Format, limits).first->second; +} + +uploader::HostCopyLimits uploader::probeHostCopy(VkFormat Format) const +{ + HostCopyLimits limits; + if (m_allocator == nullptr) + { + return limits; } // the format filled by the host, and an image which can be is as fast for the gpu as one which can't VkFormatProperties3 properties3{}; @@ -167,24 +223,67 @@ bool uploader::can_host_copy(VkFormat Format) const properties.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2; properties.pNext = &properties3; vkGetPhysicalDeviceFormatProperties2(m_physical, Format, &properties); - auto result{(properties3.optimalTilingFeatures & VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT) != 0}; - if (result) + if ((properties3.optimalTilingFeatures & VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT) == 0) { - VkHostImageCopyDevicePerformanceQuery performance{}; - performance.sType = VK_STRUCTURE_TYPE_HOST_IMAGE_COPY_DEVICE_PERFORMANCE_QUERY; - VkImageFormatProperties2 imageproperties{}; - imageproperties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; - imageproperties.pNext = &performance; - VkPhysicalDeviceImageFormatInfo2 info{}; - info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; - info.format = Format; - info.type = VK_IMAGE_TYPE_2D; - info.tiling = VK_IMAGE_TILING_OPTIMAL; - info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_HOST_TRANSFER_BIT; - result = (vkGetPhysicalDeviceImageFormatProperties2(m_physical, &info, &imageproperties) == VK_SUCCESS) && (performance.optimalDeviceAccess == VK_TRUE); + return limits; } - m_hostcopyable.emplace(Format, result); - return result; + auto const usage{VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_HOST_TRANSFER_BIT}; + VkHostImageCopyDevicePerformanceQuery performance{}; + performance.sType = VK_STRUCTURE_TYPE_HOST_IMAGE_COPY_DEVICE_PERFORMANCE_QUERY; + VkImageFormatProperties2 imageproperties{}; + imageproperties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; + imageproperties.pNext = &performance; + VkPhysicalDeviceImageFormatInfo2 formatinfo{}; + formatinfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; + formatinfo.format = Format; + formatinfo.type = VK_IMAGE_TYPE_2D; + formatinfo.tiling = VK_IMAGE_TILING_OPTIMAL; + formatinfo.usage = usage; + if ((vkGetPhysicalDeviceImageFormatProperties2(m_physical, &formatinfo, &imageproperties) != VK_SUCCESS) || (performance.optimalDeviceAccess != VK_TRUE)) + { + return limits; + } + auto const &formatlimits{imageproperties.imageFormatProperties}; + if ((formatlimits.maxExtent.width == 0) || (formatlimits.maxExtent.height == 0) || (formatlimits.maxMipLevels == 0)) + { + return limits; + } + // the memory: the host transfer usage is among what decides the memory types an image can be in (its size and levels aren't), and + // a driver can have none for it although the format allows the usage (a geforce gtx 1050 with the driver 582.28 did). the allocator + // makes a trial image of the textures' kind and finds the memory it would go to + VkImageCreateInfo imageinfo{}; + imageinfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + imageinfo.imageType = VK_IMAGE_TYPE_2D; + imageinfo.format = Format; + imageinfo.extent = {std::min(64u, formatlimits.maxExtent.width), std::min(64u, formatlimits.maxExtent.height), 1}; + imageinfo.mipLevels = 1; + imageinfo.arrayLayers = 1; + imageinfo.samples = VK_SAMPLE_COUNT_1_BIT; + imageinfo.tiling = VK_IMAGE_TILING_OPTIMAL; + imageinfo.usage = usage; + imageinfo.sharingMode = m_allocator->sharing(false, imageinfo.queueFamilyIndexCount, imageinfo.pQueueFamilyIndices); + imageinfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VmaAllocationCreateInfo allocation{}; + allocation.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; + std::uint32_t memorytype{0}; + if (auto const result{vmaFindMemoryTypeIndexForImageInfo(m_allocator->handle(), &imageinfo, &allocation, &memorytype)}; result != VK_SUCCESS) + { + log_info(std::format("the textures of format {} are filled through staging buffers: no memory for images filled by the host (vkresult {})", static_cast(Format), static_cast(result))); + return limits; + } + VkMemoryPropertyFlags memoryflags{0}; + vmaGetMemoryTypeProperties(m_allocator->handle(), memorytype, &memoryflags); + if ((memoryflags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) + { + // in the memory of the host the gpu would read them slower than the copies of staging buffers + log_info(std::format("the textures of format {} are filled through staging buffers: images filled by the host go to the memory of the host", static_cast(Format))); + return limits; + } + log_info(std::format("the textures of format {} are filled by the host (memory type {})", static_cast(Format), memorytype)); + limits.usable = true; + limits.maxExtent = formatlimits.maxExtent; + limits.maxMips = formatlimits.maxMipLevels; + return limits; } void uploader::begin_frame(command_stream *Commands, std::uint64_t Value) @@ -932,15 +1031,15 @@ vulkan14_texture::make_result vulkan14_texture::make(bool const Background) auto const generate{(levels.size() == 1) && (false == format.compressed) && m_resources.uploads->can_blit(format.format)}; // the levels the file gives are filled by the host where it can, by a background thread (what the gpu makes goes through the // commands of a frame) - auto const hostcopy{Background && (false == generate) && m_resources.uploads->can_host_copy(format.format)}; image_desc desc; desc.format = format.format; desc.extent = {data_width, data_height, 1}; desc.mips = (generate ? static_cast(std::floor(std::log2(std::max(data_width, data_height)))) + 1 : static_cast(levels.size())); + auto hostcopy{Background && (false == generate) && m_resources.uploads->can_host_copy(format.format, desc.extent, desc.mips)}; desc.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | (generate ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : 0) | (hostcopy ? VK_IMAGE_USAGE_HOST_TRANSFER_BIT : 0); desc.components = format.components; auto image{std::make_shared()}; - if (false == image->create(*m_resources.memory, desc, name)) + if (false == createTextureImage(*image, *m_resources.memory, *m_resources.uploads, desc, name, hostcopy)) { ErrorLog("Bad texture: no gpu image for \"" + name + "\"", logtype::texture); return failed(); diff --git a/rendering/vulkan14/vulkan14texture.h b/rendering/vulkan14/vulkan14texture.h index b15846b33..3f4aeeab8 100644 --- a/rendering/vulkan14/vulkan14texture.h +++ b/rendering/vulkan14/vulkan14texture.h @@ -87,13 +87,18 @@ class uploader } // whether the format can be filtered by blits (the mipmaps made on the gpu) bool can_blit(VkFormat Format) const; - // whether images of the format are filled by the host (hostImageCopy) straight to the layout they're sampled in, without a loss of - // speed for the gpu. Copyable: the device does that for the layout (decided when the device is made) + // whether images are filled by the host (hostImageCopy) straight to the layout they're sampled in, without a loss of speed for the + // gpu. Copyable: the device does that for the layout (decided when the device is made) void enable_host_copy(bool Copyable) { m_hostcopy = Copyable; } - bool can_host_copy(VkFormat Format) const; + // whether an image of the format, of Extent and Mips levels is: the format allows it, the device has memory of its own for such + // images (asked once a format) and the image is within the limits of the format for that use + bool can_host_copy(VkFormat Format, VkExtent3D const &Extent, std::uint32_t Mips) const; + // an image of the format which can_host_copy() allowed couldn't be made: the images of the format are filled through staging + // buffers from now on + void RefuseHostCopy(VkFormat Format); private: struct job @@ -106,7 +111,16 @@ class uploader std::shared_ptr buffertarget; std::vector> parts; }; + // what hostImageCopy can do with the images of a format + struct HostCopyLimits + { + bool usable{false}; + VkExtent3D maxExtent{0, 0, 0}; + std::uint32_t maxMips{0}; + }; void record(job &Job); + HostCopyLimits hostCopyLimits(VkFormat Format) const; + HostCopyLimits probeHostCopy(VkFormat Format) const; mutable std::mutex m_mutex; allocator const *m_allocator{nullptr}; @@ -121,7 +135,7 @@ class uploader std::atomic m_uploaded{0}; mutable std::unordered_map m_blittable; bool m_hostcopy{false}; - mutable std::unordered_map m_hostcopyable; + mutable std::unordered_map m_hostcopyable; }; // the images the shaders can be given by an id. added to by any thread drawing (a texture made when a draw needs it), removed from From 02f450c1abd50080a9268bb25ae89d3ee9546d3a Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Tue, 1 Dec 2026 16:03:43 +0100 Subject: [PATCH 20/20] fix(vulkan): a texture image that fails for another reason doesn't turn off host copy for its format An image to be filled by the host which can't be made is tried again without the host transfer usage, and only when that one can be made is the format filled through staging buffers from then on. When it can't either (the memory ran out), the texture fails as before and the format keeps the host copy. The warning says the error logged before it was recovered from. --- rendering/vulkan14/vulkan14texture.cpp | 18 ++++++++++++------ rendering/vulkan14/vulkan14texture.h | 4 ++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/rendering/vulkan14/vulkan14texture.cpp b/rendering/vulkan14/vulkan14texture.cpp index 7b395a09f..df85f9a3e 100644 --- a/rendering/vulkan14/vulkan14texture.cpp +++ b/rendering/vulkan14/vulkan14texture.cpp @@ -106,8 +106,10 @@ struct job_ticket std::atomic taken{false}; }; -// the image of a texture. one to be filled by the host (HostCopy) which the driver can't make after all is made to be filled through -// a staging buffer, HostCopy cleared, and so are the next ones of its format +// the image of a texture. one to be filled by the host (HostCopy) which can't be made is tried again to be filled through a staging +// buffer, HostCopy cleared. only when that one can be made is it the host transfer the driver can't do, and the next images of the +// format are filled through staging buffers too; when it can't either, it's something else (the memory ran out) and the format keeps +// the host copy bool createTextureImage(image &Target, allocator const &Memory, uploader &Uploads, image_desc &Desc, std::string const &Name, bool &HostCopy) { if (Target.create(Memory, Desc, Name)) @@ -118,10 +120,14 @@ bool createTextureImage(image &Target, allocator const &Memory, uploader &Upload { return false; } - Uploads.RefuseHostCopy(Desc.format); - HostCopy = false; Desc.usage &= ~VkImageUsageFlags{VK_IMAGE_USAGE_HOST_TRANSFER_BIT}; - return Target.create(Memory, Desc, Name); + if (false == Target.create(Memory, Desc, Name)) + { + return false; + } + HostCopy = false; + Uploads.RefuseHostCopy(Desc.format); + return true; } } // namespace @@ -190,7 +196,7 @@ void uploader::RefuseHostCopy(VkFormat Format) } if (refused) { - log_warning(std::format("the textures of format {} are filled through staging buffers: the driver can't make their images to be filled by the host, although it says it can", static_cast(Format))); + log_warning(std::format("the textures of format {} are filled through staging buffers: the driver can't make their images to be filled by the host, although it says it can (the error above, recovered from)", static_cast(Format))); } } diff --git a/rendering/vulkan14/vulkan14texture.h b/rendering/vulkan14/vulkan14texture.h index 3f4aeeab8..ec1144ce1 100644 --- a/rendering/vulkan14/vulkan14texture.h +++ b/rendering/vulkan14/vulkan14texture.h @@ -96,8 +96,8 @@ class uploader // whether an image of the format, of Extent and Mips levels is: the format allows it, the device has memory of its own for such // images (asked once a format) and the image is within the limits of the format for that use bool can_host_copy(VkFormat Format, VkExtent3D const &Extent, std::uint32_t Mips) const; - // an image of the format which can_host_copy() allowed couldn't be made: the images of the format are filled through staging - // buffers from now on + // an image of the format which can_host_copy() allowed couldn't be made, and the same one without the host transfer could: the + // images of the format are filled through staging buffers from now on void RefuseHostCopy(VkFormat Format); private: