From 4575f61cc8d8919571a72c9023b7cd584c81cba1 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 15:52:38 +0200
Subject: [PATCH 001/430] whois: add lookahead mode for the timetable entry
after the next stop
Dispatcher scripts that route trains at a station based on where they
go afterwards (e.g. a big terminal throat with several outbound
directions) have no way to read that: whois +40 only exposes the
current/next timetable entry (NextStop()/IsStop()), which while the
train is at that very station is that station itself.
Adds flags::whois_ahead (bit 6, previously unused) plus
TTrainParameters::StationNameAhead(Offset)/StationIsStopAhead(Offset),
returning the raw TimeTable[] entry Offset positions past StationIndex
(name and whether it's a booked stop, "none"/false past the end of the
timetable). The new whois branch calls both with Offset=1, mirroring
the existing +40 branch's UpdateValues()/WriteLog() shape.
Logic-verified with an isolated harness mirroring the touched types
(TTrainParameters/TController/TMemCell shapes and the exact function
bodies); not yet build-tested against the full engine locally - relying
on CI for that.
---
world/Event.cpp | 31 ++++++++++++++++++++++++++++++-
world/Event.h | 1 +
world/mtable.cpp | 16 ++++++++++++++++
world/mtable.h | 4 ++++
4 files changed, 51 insertions(+), 1 deletion(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index eb679e720..e47dbea23 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1018,13 +1018,42 @@ whois_event::run_() {
auto *targetcell { static_cast( std::get( target ) ) };
if( targetcell == nullptr ) { continue; }
// event effect code
+ // +64: station after the next one, unused, stop there or passthrough
// +40: next station name, unused, stop at next station (duplicate of +0 2nd numeric value)
// +32: vehicle name
// +24: vehicle type, consist brake level, obstacle distance
// +16: load type, load amount, max load amount
// +8: destination, direction, engine power
// +0: train name, station count, stop on next station
- if( m_input.flags & flags::whois_name ) {
+ if( m_input.flags & flags::whois_ahead ) {
+ // +64
+ // the timetable entry one past the next stop, and whether the train stops there
+ auto const *owner { (
+ m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
+ m_activator->Mechanik :
+ m_activator->ctOwner ) };
+ auto const aheadname { (
+ owner != nullptr ?
+ owner->TrainTimetable().StationNameAhead( 1 ) :
+ "none" ) };
+ auto const aheadstop { (
+ owner != nullptr && owner->TrainTimetable().StationIsStopAhead( 1 ) ?
+ 1 :
+ 0 ) };
+
+ targetcell->UpdateValues(
+ aheadname, // station after the next one
+ 0, // unused
+ aheadstop, // stop there or passthrough
+ m_input.flags & ( flags::text | flags::value1 | flags::value2 ) );
+
+ WriteLog(
+ "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - "
+ + "[station after next: " + aheadname + "], "
+ + "[X], "
+ + "[stop there: " + ( aheadstop != 0 ? "yes" : "no" ) + "]" );
+ }
+ else if( m_input.flags & flags::whois_name ) {
// +32 or +40
// next station name
if( m_input.flags & flags::mode_alt ) {
diff --git a/world/Event.h b/world/Event.h
index 52ee3468d..55be65de1 100644
--- a/world/Event.h
+++ b/world/Event.h
@@ -37,6 +37,7 @@ public:
mode_alt = 1 << 3,
whois_load = 1 << 4,
whois_name = 1 << 5,
+ whois_ahead = 1 << 6,
// condition values
track_busy = 1 << 3,
track_free = 1 << 4,
diff --git a/world/mtable.cpp b/world/mtable.cpp
index cec54f870..75e6c8ad0 100644
--- a/world/mtable.cpp
+++ b/world/mtable.cpp
@@ -77,6 +77,22 @@ bool TTrainParameters::IsLastStop() const {
return StationIndex >= StationCount;
}
+std::string TTrainParameters::StationNameAhead( int Offset ) const
+{ // nazwa wpisu rozkladu Offset pozycji za aktualnym (bez pomijania przelotow)
+ int const idx { StationIndex + Offset };
+ if( ( idx < 1 ) || ( idx > StationCount ) )
+ return "none";
+ return TimeTable[idx].StationName;
+}
+
+bool TTrainParameters::StationIsStopAhead( int Offset ) const
+{ // czy wpis Offset pozycji za aktualnym to zaplanowany postoj
+ int const idx { StationIndex + Offset };
+ if( ( idx < 1 ) || ( idx > StationCount ) )
+ return false;
+ return TimeTable[idx].Ah >= 0; //-1 to brak postoju
+}
+
bool TTrainParameters::IsMaintenance() const {
if( StationIndex <= StationCount )
diff --git a/world/mtable.h b/world/mtable.h
index c58d120ff..701b0c6ca 100644
--- a/world/mtable.h
+++ b/world/mtable.h
@@ -70,6 +70,10 @@ class TTrainParameters
std::string ShowRelation() const;
double WatchMTable(double DistCounter);
std::string NextStop() const;
+ // nazwa wpisu rozkladu Offset pozycji za StationIndex (Offset>=1); "none" poza koncem rozkladu
+ std::string StationNameAhead( int Offset ) const;
+ // true, gdy ten wpis to zaplanowany postoj (ma godzine przyjazdu), false dla przelotu / poza koncem
+ bool StationIsStopAhead( int Offset ) const;
sound_source next_stop_sound() const;
sound_source last_stop_sound() const;
bool IsStop() const;
From 5705062cd29826b9bb1386eb2ccfa5be258a3204 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 20:28:28 +0200
Subject: [PATCH 002/430] whois: select the lookahead mode via +48 instead of a
new bit
Per review: +48 (whois_name | whois_load, mode_alt clear) was an
unused combination of the existing mode bits - use that instead of
claiming a new bit 6. +56 (same, with mode_alt set) stays free for a
future mode. No new flags::* entry needed; mtable.h/.cpp unchanged.
---
world/Event.cpp | 8 +++++---
world/Event.h | 1 -
2 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index e47dbea23..ebfc73958 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1018,15 +1018,17 @@ whois_event::run_() {
auto *targetcell { static_cast( std::get( target ) ) };
if( targetcell == nullptr ) { continue; }
// event effect code
- // +64: station after the next one, unused, stop there or passthrough
+ // +48: station after the next one, unused, stop there or passthrough
// +40: next station name, unused, stop at next station (duplicate of +0 2nd numeric value)
// +32: vehicle name
// +24: vehicle type, consist brake level, obstacle distance
// +16: load type, load amount, max load amount
// +8: destination, direction, engine power
// +0: train name, station count, stop on next station
- if( m_input.flags & flags::whois_ahead ) {
- // +64
+ if( ( m_input.flags & ( flags::whois_name | flags::whois_load | flags::mode_alt ) )
+ == ( flags::whois_name | flags::whois_load ) ) {
+ // +48 (the whois_name | whois_load combination was unused; +56, same with mode_alt
+ // set, stays free for a future mode)
// the timetable entry one past the next stop, and whether the train stops there
auto const *owner { (
m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
diff --git a/world/Event.h b/world/Event.h
index 55be65de1..52ee3468d 100644
--- a/world/Event.h
+++ b/world/Event.h
@@ -37,7 +37,6 @@ public:
mode_alt = 1 << 3,
whois_load = 1 << 4,
whois_name = 1 << 5,
- whois_ahead = 1 << 6,
// condition values
track_busy = 1 << 3,
track_free = 1 << 4,
From 93463a3850e50f8818d12c042a6ef7e3639b84f3 Mon Sep 17 00:00:00 2001
From: Piotr Warszawski
Date: Fri, 4 Sep 2026 21:24:01 +0200
Subject: [PATCH 003/430] whois: consolidate the two lookahead accessors into
one
Per review: StationNameAhead()/StationIsStopAhead() duplicated the same
bounds check for no reason. Replaced with a single
TimeTableEntryAhead(Offset) returning the TMTableLine itself; the whois
branch reads .StationName/.Ah off it directly.
---
world/Event.cpp | 12 +++++-------
world/mtable.cpp | 17 +++++------------
world/mtable.h | 7 +++----
3 files changed, 13 insertions(+), 23 deletions(-)
diff --git a/world/Event.cpp b/world/Event.cpp
index ebfc73958..319ad0591 100644
--- a/world/Event.cpp
+++ b/world/Event.cpp
@@ -1034,14 +1034,12 @@ whois_event::run_() {
m_activator->Mechanik != nullptr && m_activator->Mechanik->primary() ?
m_activator->Mechanik :
m_activator->ctOwner ) };
- auto const aheadname { (
+ auto const *entry { (
owner != nullptr ?
- owner->TrainTimetable().StationNameAhead( 1 ) :
- "none" ) };
- auto const aheadstop { (
- owner != nullptr && owner->TrainTimetable().StationIsStopAhead( 1 ) ?
- 1 :
- 0 ) };
+ &owner->TrainTimetable().TimeTableEntryAhead( 1 ) :
+ nullptr ) };
+ auto const aheadname { ( entry != nullptr ? entry->StationName : "none" ) };
+ auto const aheadstop { ( entry != nullptr && entry->Ah >= 0 ? 1 : 0 ) };
targetcell->UpdateValues(
aheadname, // station after the next one
diff --git a/world/mtable.cpp b/world/mtable.cpp
index 75e6c8ad0..dd84b6c23 100644
--- a/world/mtable.cpp
+++ b/world/mtable.cpp
@@ -77,20 +77,13 @@ bool TTrainParameters::IsLastStop() const {
return StationIndex >= StationCount;
}
-std::string TTrainParameters::StationNameAhead( int Offset ) const
-{ // nazwa wpisu rozkladu Offset pozycji za aktualnym (bez pomijania przelotow)
+TMTableLine const &TTrainParameters::TimeTableEntryAhead( int Offset ) const
+{ // wpis rozkladu Offset pozycji za aktualnym (bez pomijania przelotow);
+ // poza zakresem 1..StationCount zwraca techniczny wpis zerowy
int const idx { StationIndex + Offset };
if( ( idx < 1 ) || ( idx > StationCount ) )
- return "none";
- return TimeTable[idx].StationName;
-}
-
-bool TTrainParameters::StationIsStopAhead( int Offset ) const
-{ // czy wpis Offset pozycji za aktualnym to zaplanowany postoj
- int const idx { StationIndex + Offset };
- if( ( idx < 1 ) || ( idx > StationCount ) )
- return false;
- return TimeTable[idx].Ah >= 0; //-1 to brak postoju
+ return TimeTable[0];
+ return TimeTable[idx];
}
diff --git a/world/mtable.h b/world/mtable.h
index 701b0c6ca..2d20a27bb 100644
--- a/world/mtable.h
+++ b/world/mtable.h
@@ -70,10 +70,9 @@ class TTrainParameters
std::string ShowRelation() const;
double WatchMTable(double DistCounter);
std::string NextStop() const;
- // nazwa wpisu rozkladu Offset pozycji za StationIndex (Offset>=1); "none" poza koncem rozkladu
- std::string StationNameAhead( int Offset ) const;
- // true, gdy ten wpis to zaplanowany postoj (ma godzine przyjazdu), false dla przelotu / poza koncem
- bool StationIsStopAhead( int Offset ) const;
+ // wpis rozkladu Offset pozycji za StationIndex (Offset>=1); poza zakresem 1..StationCount
+ // zwraca techniczny wpis zerowy (TimeTable[0], StationName=="nowhere", Ah==-1)
+ TMTableLine const &TimeTableEntryAhead( int Offset ) const;
sound_source next_stop_sound() const;
sound_source last_stop_sound() const;
bool IsStop() const;
From 95f41f069f9f918c517410f9ed865d8178da0cf2 Mon Sep 17 00:00:00 2001
From: pawelw
Date: Wed, 23 Sep 2026 01:02:11 +0200
Subject: [PATCH 004/430] Speed table: keep it sorted and keep the signal
indices valid (#178)
* Fix the speed table index remap in TablePurger()
TablePurger() rebuilds the speed table and has to move SemNextIndex and
SemNextStopIndex along with it. Two cases came out wrong.
A trimmed point was never invalidated: the index was first overwritten with
the position the next kept point would take, and the guard that should reset
it to -1 compared the loop counter against that new value, so it only matched
when nothing had been trimmed before it. The index then pointed at an
unrelated record, and if that record happens to sit at zero velocity the
placement can no longer be updated either, because the update requires the
recorded one to be non-zero.
An index pointing at the last entry was left untouched, because the loop stops
one short of it and that entry is appended afterwards. The stale value ended
up past the end of the trimmed table, which is what the provisory check in
TableTraceRoute() catches.
The placements are now recorded separately and assigned once the new table is
complete, with the always-kept last entry handled too. The trim condition is
shared by the counting and the copying pass instead of being spelled out
twice.
TableCheck() drops entries beyond a switch that changed under the scan without
adjusting the placements either, so they are invalidated there as well. The
check in TableTraceRoute() stays as a safety net, without the TODO.
* Sort the whole speed table in TableSort()
TableSort() made a single bubble pass over the table. That only moves an entry
one place towards the front, but TableTraceRoute() adds the scanned events of a
track before the track itself, so a track carrying k scanned events lands k
places too far and needs k passes. With two or more events in one slot - a cab
signal resonator next to a signal, a signal and a W4 - the track entry stays
behind entries that are farther away, and TableUpdate() walks the table out of
distance order until enough later scans have shifted it back.
The range before the last slot is now sorted with std::stable_sort, and the
semaphor placements are moved along by looking their events up again.
---------
Co-authored-by: pwarszawski
---
vehicle/Driver.cpp | 114 ++++++++++++++++++++++++++-------------------
1 file changed, 67 insertions(+), 47 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 43f2f924c..9a6de8596 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -540,8 +540,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle)
}
else {
if( iTableDirection == 0 ) { return; }
- // NOTE: provisory fix for BUG: sempahor indices no longer matching table size
- // TODO: find and really fix the reason it happens
+ // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table
if( SemNextIndex != -1
&& SemNextIndex >= sSpeedTable.size() ) {
SemNextIndex = -1;
@@ -800,6 +799,15 @@ void TController::TableCheck(double fDistance)
sSpeedTable.pop_back();
--iLast;
}
+ // a semaphor recorded beyond the switch went away with the discarded entries
+ if( SemNextIndex != -1
+ && SemNextIndex >= sSpeedTable.size() ) {
+ SemNextIndex = -1;
+ }
+ if( SemNextStopIndex != -1
+ && SemNextStopIndex >= sSpeedTable.size() ) {
+ SemNextStopIndex = -1;
+ }
tLast = sSpeedTable[ i ].trTrack;
TableTraceRoute( fDistance, pVehicles[ end::rear ] );
TableSort();
@@ -1739,14 +1747,16 @@ void TController::TablePurger()
return;
}
// simplest approach should be good enough for start -- just copy whatever is still relevant, then swap
+ auto const isexpendable = []( TSpeedPos const &Speedpoint ) {
+ return
+ 0 == ( Speedpoint.iFlags & spEnabled )
+ || ( ( Speedpoint.iFlags & ( spElapsed | spTrack | spCurve | spSwitch ) ) == ( spElapsed | spTrack | spCurve )
+ && Speedpoint.fVelNext < 0.0 ); };
// do a trial run first, to see if we need to bother at all
std::size_t trimcount{ 0 };
for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) {
- auto const &speedpoint = sSpeedTable[ idx ];
- if( 0 == (speedpoint.iFlags & spEnabled)
- || ( (speedpoint.iFlags & (spElapsed | spTrack | spCurve | spSwitch)) == (spElapsed | spTrack | spCurve)
- && speedpoint.fVelNext < 0.0 ) ) {
- // NOTE: we could break out early here, but running through entire thing gives us exact size needed for new table
+ // NOTE: we could break out early here, but running through entire thing gives us exact size needed for new table
+ if( isexpendable( sSpeedTable[ idx ] ) ) {
++trimcount;
}
}
@@ -1755,34 +1765,34 @@ void TController::TablePurger()
return;
}
std::vector trimmedtable; trimmedtable.reserve( sSpeedTable.size() - trimcount );
- // we can only update pointers safely after new table is finalized, so record their indices until then
+ // the indices are only valid for the old table, so the new placements are recorded separately
+ // and assigned once the new table is complete
+ auto semnextindex { std::size_t( -1 ) };
+ auto semnextstopindex { std::size_t( -1 ) };
+ auto const trackplacement = [&]( std::size_t const Index, bool const Kept ) {
+ // a trimmed point leaves the index invalid, a kept one lands where the new table ends
+ if( Index == SemNextIndex ) {
+ semnextindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) );
+ }
+ if( Index == SemNextStopIndex ) {
+ semnextstopindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) );
+ } };
+
for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) {
- // cache placement of semaphors in the new table, if we encounter them
- if( idx == SemNextIndex ) {
- SemNextIndex = trimmedtable.size();
- }
- if( idx == SemNextStopIndex ) {
- SemNextStopIndex = trimmedtable.size();
- }
auto const &speedpoint = sSpeedTable[ idx ];
- if( 0 == (speedpoint.iFlags & spEnabled)
- || ( (speedpoint.iFlags & (spElapsed | spTrack | spCurve | spSwitch)) == (spElapsed | spTrack | spCurve)
- && speedpoint.fVelNext < 0.0 ) ) {
- // if the trimmed point happens to be currently active semaphor we need to invalidate their placements
- if( idx == SemNextIndex ) {
- SemNextIndex = -1;
- }
- if( idx == SemNextStopIndex ) {
- SemNextStopIndex = -1;
- }
- continue;
- }
+ auto const kept { false == isexpendable( speedpoint ) };
+ trackplacement( idx, kept );
+ if( false == kept ) { continue; }
// we're left with useful speed point record we should copy
trimmedtable.emplace_back( speedpoint );
}
- // always copy the last entry
+ // always copy the last entry; an index pointing at it has to follow it as well
+ trackplacement( sSpeedTable.size() - 1, true );
trimmedtable.emplace_back( sSpeedTable.back() );
+ SemNextIndex = semnextindex;
+ SemNextStopIndex = semnextstopindex;
+
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table garbage collection for " + OwnerName() + " cut away " + std::to_string( trimcount ) + ( trimcount == 1 ? " record" : " records" ) );
}
@@ -1797,25 +1807,35 @@ void TController::TableSort() {
// we skip last slot and no point in checking if there's only one other entry
return;
}
- TSpeedPos sp_temp = TSpeedPos(); // uzywany do przenoszenia
- for( int i = 0; i < iLast - 1; ++i ) {
- // pętla tylko do dwóch pozycji od końca bo ostatniej nie modyfikujemy
- if (sSpeedTable[i].fDist > sSpeedTable[i + 1].fDist)
- { // jesli pozycja wcześniejsza jest dalej to źle
- sp_temp = sSpeedTable[i + 1];
- sSpeedTable[i + 1] = sSpeedTable[i]; // zamiana
- sSpeedTable[i] = sp_temp;
- // jeszcze sprawdzenie czy pozycja nie była indeksowana dla eventów
- if (SemNextIndex == i)
- ++SemNextIndex;
- else if (SemNextIndex == i + 1)
- --SemNextIndex;
- if (SemNextStopIndex == i)
- ++SemNextStopIndex;
- else if (SemNextStopIndex == i + 1)
- --SemNextStopIndex;
- }
- }
+ // the last slot holds the track the scan stopped at and stays where it is.
+ // a single bubble pass is not enough: TableTraceRoute() adds the events of a track before the
+ // track itself, so a track with k scanned events lands k places too far and needs k passes
+ auto const sortedcount { static_cast( iLast ) };
+ auto const inrange = [&]( std::size_t const Index ) {
+ return Index < sortedcount; };
+ // the placements point at semaphor entries; remember which ones, the sort moves them around
+ auto const *semnextevent { inrange( SemNextIndex ) ? sSpeedTable[ SemNextIndex ].evEvent : nullptr };
+ auto const *semnextstopevent { inrange( SemNextStopIndex ) ? sSpeedTable[ SemNextStopIndex ].evEvent : nullptr };
+
+ std::stable_sort(
+ std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount,
+ []( TSpeedPos const &Left, TSpeedPos const &Right ) {
+ return Left.fDist < Right.fDist; } );
+
+ auto const relocate = [&]( basic_event const *Event, std::size_t &Index ) {
+ if( Event == nullptr ) { return; }
+ auto const lookup {
+ std::find_if(
+ std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount,
+ [Event]( TSpeedPos const &Point ) {
+ return Point.evEvent == Event; } ) };
+ Index = (
+ lookup != std::begin( sSpeedTable ) + sortedcount ?
+ static_cast( std::distance( std::begin( sSpeedTable ), lookup ) ) :
+ std::size_t( -1 ) );
+ };
+ relocate( semnextevent, SemNextIndex );
+ relocate( semnextstopevent, SemNextStopIndex );
}
//---------------------------------------------------------------------------
From b1bdd4217818ba82521015968ee18901a4a14cda Mon Sep 17 00:00:00 2001
From: maj00r <73280030+maj00r@users.noreply.github.com>
Date: Wed, 23 Sep 2026 01:03:01 +0200
Subject: [PATCH 005/430] Forget a buffer's bindings when it is deleted (#182)
The binding tracker kept the name of a deleted buffer. When gl handed that
name to a new buffer, the tracker took it for already bound and skipped the
bind, so a new vao was left without its index buffer and the nvidia driver
read indices from a null pointer.
---
gl/buffer.cpp | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/gl/buffer.cpp b/gl/buffer.cpp
index 8b8bd4869..b80cee3e9 100644
--- a/gl/buffer.cpp
+++ b/gl/buffer.cpp
@@ -58,6 +58,11 @@ gl::buffer::buffer()
gl::buffer::~buffer()
{
+ // forget the bindings of this buffer; gl can hand its name to a new buffer,
+ // which the tracker would then treat as already bound and skip the bind
+ for (auto &point : binding_points)
+ if (point == *this)
+ point = 0;
glDeleteBuffers(1, *this);
}
From 8fbb48235033729d57366444dc5470285469de6a Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Sun, 27 Sep 2026 00:09:16 +0200
Subject: [PATCH 006/430] feat(materials): texture randomization for loads
* feat(materials): texture randomization for loads
---
.../renderer/source/materialparser.cpp | 8 +
model/AnimModel.cpp | 4 +
model/Model3d.cpp | 117 ++++++++++++
model/Model3d.h | 10 ++
model/material.cpp | 169 ++++++++++++------
model/material.h | 32 +++-
rendering/opengl33renderer.cpp | 18 +-
rendering/openglrenderer.cpp | 28 ++-
utilities/utilities.cpp | 40 ++++-
utilities/utilities.h | 8 +
vehicle/DynObj.cpp | 4 +
vehicle/DynObj.h | 4 +
12 files changed, 379 insertions(+), 63 deletions(-)
diff --git a/betterRenderer/renderer/source/materialparser.cpp b/betterRenderer/renderer/source/materialparser.cpp
index 20ef43221..0530916be 100644
--- a/betterRenderer/renderer/source/materialparser.cpp
+++ b/betterRenderer/renderer/source/materialparser.cpp
@@ -187,6 +187,14 @@ bool MaterialAdapterLegacyMatFile::ParseLevel(cParser& parser, int priority) {
else if (key.compare(0, 7, "texture") == 0) {
key.erase(0, 7);
+ // "textureN_variants:" declares a pool of textures picked per model instance. this renderer
+ // doesn't support per instance variants yet, so the pool is reduced to a single entry drawn
+ // when the material is loaded, which is how such texture used to be picked before variants
+ if (auto const variantmarker{key.find("_variants")};
+ variantmarker != std::string::npos) {
+ key.erase(variantmarker, std::string("_variants").size());
+ }
+
auto value{deserialize_random_set(parser)};
replace_slashes(value);
auto& [tex_priority, texture] = m_texture_mapping[key];
diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp
index ef4f90a8a..bc2d6e844 100644
--- a/model/AnimModel.cpp
+++ b/model/AnimModel.cpp
@@ -627,6 +627,10 @@ void TAnimModel::RaPrepare()
}
}
TSubModel::iInstance = reinterpret_cast( this ); //żeby nie robić cudzych animacji
+ // NOTE: scenery models don't pick texture variants of their own, so we clear the seed left by the
+ // last rendered vehicle. instanced draws share a single material bind anyway, which would make
+ // per instance variants inconsistent between batched and individually drawn models
+ TSubModel::iVariantSeed = 0;
TSubModel::pasText = &asText; // przekazanie tekstu do wyświetlacza (!!!! do przemyślenia)
for (auto entry : m_animlist) {
diff --git a/model/Model3d.cpp b/model/Model3d.cpp
index 5f59558b3..38f39080f 100644
--- a/model/Model3d.cpp
+++ b/model/Model3d.cpp
@@ -30,6 +30,7 @@ using namespace Mtable;
float TSubModel::fSquareDist = 0.f;
std::uintptr_t TSubModel::iInstance; // numer renderowanego egzemplarza obiektu
+std::uint32_t TSubModel::iVariantSeed = 0; // ziarno losowania wariantów tekstur renderowanego egzemplarza
texture_handle const *TSubModel::ReplacableSkinId = nullptr;
int TSubModel::iAlpha = 0x30300030; // maska do testowania flag tekstur wymiennych
TModel3d *TSubModel::pRoot; // Ra: tymczasowo wskaźnik na model widoczny z submodelu
@@ -2460,6 +2461,120 @@ void TModel3d::LoadFromTextFile(std::string const &FileName, bool dynamic)
}
}
+std::uint32_t TSubModel::VariantId(TSubModel const *Submodel)
+{ // the seed is already well scattered, so the group is merely added to it. this way branches of one model
+ // are guaranteed to land on different variants, as long as the pool holds at least as many entries as
+ // the model has branches -- two containers carried by the same wagon won't come up with the same number
+ return iVariantSeed + static_cast(Submodel != nullptr ? Submodel->m_variantgroup : 0);
+}
+
+namespace
+{
+// two branches sitting no farther than this from each other are treated as one object.
+// generous, a simplified lod mesh doesn't have to sit exactly where the detailed one does
+float const variantgrouptolerance{0.25f};
+
+// assigns provided variant group id to the submodel and all of its children
+void mark_variant_group(TSubModel *Submodel, int const Group, bool const Includesiblings)
+{
+ while (Submodel != nullptr)
+ {
+ Submodel->m_variantgroup = Group;
+ mark_variant_group(Submodel->ChildGet(), Group, true);
+ if (false == Includesiblings)
+ {
+ break;
+ }
+ Submodel = Submodel->NextGet();
+ }
+}
+
+// expands provided bounding area to cover geometry carried by the submodel and all of its children
+void accumulate_mesh_bounds(TSubModel const *Submodel, glm::vec3 &Minimum, glm::vec3 &Maximum, bool &Isempty, bool const Includesiblings)
+{
+ while (Submodel != nullptr)
+ {
+ if (auto const &vertices{(Submodel->m_geometry.handle != null_handle ? GfxRenderer->Vertices(Submodel->m_geometry.handle) : Submodel->Vertices)};
+ false == vertices.empty())
+ {
+ // the transformation chain can still hold a rotation, so the vertices go through it
+ // rather than get taken at their face value
+ float4x4 parentmatrix;
+ Submodel->ParentMatrix(&parentmatrix);
+ auto const transformationmatrix{glm::make_mat4(parentmatrix.readArray())};
+ for (auto const &vertex : vertices)
+ {
+ auto const position{glm::vec3{transformationmatrix * glm::vec4{vertex.position, 1}}};
+ Minimum = glm::min(Minimum, position);
+ Maximum = glm::max(Maximum, position);
+ }
+ Isempty = false;
+ }
+ accumulate_mesh_bounds(Submodel->Child, Minimum, Maximum, Isempty, true);
+ if (false == Includesiblings)
+ {
+ break;
+ }
+ Submodel = Submodel->Next;
+ }
+}
+
+// returns position of provided branch of the model, relative to the model root
+glm::vec3 branch_position(TSubModel const *Branch)
+{
+ // the transformation chain is the cheap way to get there, as it doesn't touch the geometry,
+ // which keeps this affordable even for models made of thousands of branches...
+ auto const offset{Branch->offset()};
+ if (glm::length2(offset) > variantgrouptolerance * variantgrouptolerance)
+ {
+ return offset;
+ }
+ // ...but it only tells us anything for branches which actually carry a transform. models loaded from
+ // text format can have theirs baked into the vertices instead, which leaves the whole model piled up
+ // at the origin and, without the fallback below, all of its branches in a single variant group.
+ // NOTE: it's the centre of the bounding area we're after, and not the average vertex position offset()
+ // would give us -- the latter drifts with vertex density, which puts each lod mesh of one object in
+ // a group of its own and has the object change its texture variant as the lods get swapped
+ glm::vec3 minimum{std::numeric_limits::max()};
+ glm::vec3 maximum{std::numeric_limits::lowest()};
+ bool isempty{true};
+ accumulate_mesh_bounds(Branch, minimum, maximum, isempty, false);
+ return (false == isempty ? (minimum + maximum) * 0.5f : offset);
+}
+} // namespace
+
+void TModel3d::assign_variant_groups()
+{ // each top level branch of the model gets a group id, which it passes down to all of its children.
+ // for load models a branch is a single load chunk, and the group id is what makes two chunks of the same
+ // model pick different texture variants, while keeping all parts of one chunk on the same variant.
+ // the id comes from the position of the branch, not from its ordinal: lod variants of one object are
+ // separate branches drawn in disjoint distance ranges, and grouping them by position is what keeps the
+ // object on the same variant no matter which of them is currently on screen
+ std::vector grouppositions; // position of each group, indexed by its id
+ auto const groupid = [&grouppositions](TSubModel const *Branch) {
+ auto const position{branch_position(Branch)};
+ for (std::size_t index = 0; index < grouppositions.size(); ++index)
+ {
+ if (glm::length2(grouppositions[index] - position) < variantgrouptolerance * variantgrouptolerance)
+ {
+ return static_cast(index);
+ }
+ }
+ grouppositions.emplace_back(position);
+ return static_cast(grouppositions.size() - 1);
+ };
+
+ for (auto *trunk = Root; trunk != nullptr; trunk = trunk->NextGet())
+ {
+ // root level submodels are usually mere containers, but can carry geometry of their own
+ trunk->m_variantgroup = groupid(trunk);
+ for (auto *branch = trunk->ChildGet(); branch != nullptr; branch = branch->NextGet())
+ {
+ mark_variant_group(branch, groupid(branch), false);
+ }
+ }
+}
+
void TModel3d::Init()
{ // obrócenie początkowe układu współrzędnych, dla
// pojazdów wykonywane po analizie animacji
@@ -2492,6 +2607,8 @@ void TModel3d::Init()
Root->m_boundingradius = std::max(Root->m_boundingradius, root->m_boundingradius);
}
+ assign_variant_groups();
+
if (Global.iConvertModels & 1 && false == asBinary.empty())
{
SaveToBinFile(asBinary);
diff --git a/model/Model3d.h b/model/Model3d.h
index 7ebb13170..0e053609e 100644
--- a/model/Model3d.h
+++ b/model/Model3d.h
@@ -137,6 +137,9 @@ public:
TSubModel *Child { nullptr };
public:
material_handle m_material { null_handle }; // numer tekstury, -1 wymienna, 0 brak
+ // index of the top level branch of the model this submodel belongs to. submodels sharing a branch
+ // also share the texture variant picked for them, so a multi-mesh load chunk stays consistent
+ int m_variantgroup { 0 };
bool bWire { false }; // nie używane, ale wczytywane
float Opacity { 1.0f };
float f_Angle { 0.0f };
@@ -168,6 +171,9 @@ public:
public:
static size_t iInstance; // identyfikator egzemplarza, który aktualnie renderuje model
+ // seed of the currently rendered model instance, combined with m_variantgroup it picks
+ // texture variants for materials which declare them. 0 for instances without own seed
+ static std::uint32_t iVariantSeed;
static material_handle const *ReplacableSkinId;
static int iAlpha; // maska bitowa dla danego przebiegu
static float fSquareDist;
@@ -211,6 +217,8 @@ public:
static void ReplacableSet(material_handle const *r, int a) {
ReplacableSkinId = r;
iAlpha = a; };
+ // returns id of texture variant to use for provided submodel of the currently rendered instance
+ static std::uint32_t VariantId(TSubModel const *Submodel);
void Name_Material( std::string const &Name );
void Name( std::string const &Name );
// Ra: funkcje do budowania terenu z E3D
@@ -291,6 +299,8 @@ public:
void SaveToBinFile(std::string const &FileName);
uint32_t Flags() const { return iFlags; };
void Init();
+ // assigns each top level branch of the model, and everything below it, its own variant group id
+ void assign_variant_groups();
std::string NameGet() const { return m_filename; };
nameoffset_sequence const & smoke_sources() const {
return m_smokesources; }
diff --git a/model/material.cpp b/model/material.cpp
index f5e32689b..19fa0b375 100644
--- a/model/material.cpp
+++ b/model/material.cpp
@@ -64,55 +64,96 @@ std::map texture_bindings {
{ "normalmap", 1 }
};
+int opengl_material::texture_slot( std::string const &Key )
+{
+ auto key { Key };
+
+ if( ( key.size() > 0 ) && ( key[ 0 ] != '_' ) )
+ {
+ // numbered binding, "textureN:" fills the slot N-1
+ key.erase( key.find_first_not_of( "-1234567890" ) );
+ size_t const num = std::stoi( key ) - 1;
+ if( num < gl::MAX_TEXTURES ) {
+ return static_cast( num );
+ }
+ log_error( "invalid texture binding: " + std::to_string( num ) );
+ is_good = false;
+ return -1;
+ }
+
+ if( key.size() > 2 )
+ {
+ // named binding, the slot it fills is up to the shader
+ key.erase( 0, 1 );
+ key.pop_back();
+ if( shader && ( shader->texture_conf.find( key ) != shader->texture_conf.end() ) ) {
+ return static_cast( shader->texture_conf[ key ].id );
+ }
+ auto const lookup { texture_bindings.find( key ) };
+ if( ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) {
+ return lookup->second;
+ }
+ // ignore unrecognized texture bindings in legacy render mode, it's most likely data for more advanced shaders
+ if( Global.GfxRenderer == "default" ) {
+ log_error( "unknown texture binding: " + key );
+ is_good = false;
+ }
+ return -1;
+ }
+
+ log_error( "unrecognized texture binding: " + key );
+ is_good = false;
+ return -1;
+}
+
+void opengl_material::build_texture_variants( std::vector const &Bindings, bool const Loadnow )
+{
+ if( true == Bindings.empty() ) { return; }
+
+ // build a texture set for each entry of the largest of the declared pools.
+ // pools of different size can be combined, shorter ones simply repeat from the start
+ std::size_t variantcount { 0 };
+ for( auto const &[ slot, pool ] : Bindings ) {
+ variantcount = std::max( variantcount, pool->size() );
+ }
+ texture_variants.resize( variantcount, textures );
+
+ for( auto const &[ slot, pool ] : Bindings ) {
+ for( std::size_t variantindex = 0; variantindex < variantcount; ++variantindex ) {
+ auto const &texturename { ( *pool )[ variantindex % pool->size() ] };
+ auto const texturehandle { GfxRenderer->Fetch_Texture( texturename, Loadnow ) };
+ if( texturehandle == null_handle ) {
+ // a single bad entry shouldn't take down the whole material, fall back to the basic texture
+ log_error( "missing texture variant: " + texturename );
+ continue;
+ }
+ texture_variants[ variantindex ][ slot ] = texturehandle;
+ }
+ }
+}
+
void opengl_material::finalize(bool Loadnow)
{
is_good = true;
if (parse_info)
{
- for (auto it : parse_info->tex_mapping)
- {
- std::string key = it.first;
- std::string value = it.second.name;
+ // texture bindings which come with a pool of alternatives, gathered while resolving regular bindings
+ std::vector variantbindings;
- if (key.size() > 0 && key[0] != '_')
- {
- key.erase( key.find_first_not_of( "-1234567890" ) );
- size_t num = std::stoi(key) - 1;
- if (num < gl::MAX_TEXTURES) {
- textures[num] = GfxRenderer->Fetch_Texture(value, Loadnow);
- }
- else {
- log_error("invalid texture binding: " + std::to_string(num));
- is_good = false;
- }
- }
- else if (key.size() > 2)
- {
- key.erase(0, 1);
- key.pop_back();
- std::map::iterator lookup;
- if( shader && shader->texture_conf.find( key ) != shader->texture_conf.end() ) {
- textures[ shader->texture_conf[ key ].id ] = GfxRenderer->Fetch_Texture( value, Loadnow );
- }
- else if( shader == nullptr
- && ( lookup = texture_bindings.find( key ) ) != texture_bindings.end() ) {
- textures[ lookup->second ] = GfxRenderer->Fetch_Texture( value, Loadnow );
- }
- else {
- // ignore unrecognized texture bindings in legacy render mode, it's most likely data for more advanced shaders
- if( Global.GfxRenderer == "default" ) {
- log_error( "unknown texture binding: " + key );
- is_good = false;
- }
- }
- }
- else {
- log_error("unrecognized texture binding: " + key);
- is_good = false;
+ for( auto const &[ bindingkey, binding ] : parse_info->tex_mapping )
+ {
+ auto const slot { texture_slot( bindingkey ) };
+ if( slot < 0 ) { continue; }
+
+ textures[ slot ] = GfxRenderer->Fetch_Texture( binding.name, Loadnow );
+ if( binding.variants.size() > 1 ) {
+ variantbindings.emplace_back( static_cast( slot ), &( binding.variants ) );
}
}
+ build_texture_variants( variantbindings, Loadnow );
+
if (!shader)
{
// TODO: add error severity to logging, re-enable these errors as low severity messages
@@ -289,6 +330,44 @@ bool is_weather( std::string const &String ) {
}
// imports member data pair from the config file
+void opengl_material::deserialize_texture_mapping( cParser &Input, std::string const &Key, int const Priority ) {
+
+ // a texture binding can be provided as a pool of alternatives, "textureN_variants: [ a b c ]".
+ // unlike a regular random set, which is resolved once when the material is loaded and thus shared
+ // by everything using it, such pool is preserved whole and one entry is picked per model instance
+ auto key { Key };
+ auto const variantmarker { key.find( "_variants" ) };
+ auto const isvariantset { variantmarker != std::string::npos };
+ if( true == isvariantset ) {
+ // reduce the key to its plain form, "N_variants:" becomes "N:"
+ key.erase( variantmarker, std::string( "_variants" ).size() );
+ }
+
+ std::vector variants;
+ std::string value;
+ if( false == isvariantset ) {
+ value = deserialize_random_set( Input );
+ replace_slashes( value );
+ }
+ else {
+ variants = deserialize_set( Input );
+ for( auto &variant : variants ) {
+ replace_slashes( variant );
+ }
+ if( true == variants.empty() ) {
+ log_error( "empty texture variant pool: " + key );
+ return;
+ }
+ // first entry doubles as the regular, variant-agnostic texture of the material
+ value = variants.front();
+ }
+
+ auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, parse_info_s::tex_def{ value, Priority, variants } ) };
+ if( ( false == inserted ) && ( Priority > it->second.priority ) ) {
+ it->second = parse_info_s::tex_def{ value, Priority, variants };
+ }
+}
+
bool
opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool const Loadnow ) {
@@ -324,17 +403,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c
else if (key.compare(0, 7, "texture") == 0) {
key.erase(0, 7);
-
- auto value { deserialize_random_set( Input ) };
- replace_slashes( value );
- auto it = parse_info->tex_mapping.find(key);
- if (it == parse_info->tex_mapping.end())
- parse_info->tex_mapping.emplace(std::make_pair(key, parse_info_s::tex_def({ value, Priority })));
- else if (Priority > it->second.priority)
- {
- parse_info->tex_mapping.erase(it);
- parse_info->tex_mapping.emplace(std::make_pair(key, parse_info_s::tex_def({ value, Priority })));
- }
+ deserialize_texture_mapping( Input, key, Priority );
}
else if (key.compare(0, 5, "param") == 0) {
key.erase(0, 5);
diff --git a/model/material.h b/model/material.h
index 6d3f2b8d3..7e04514cd 100644
--- a/model/material.h
+++ b/model/material.h
@@ -18,7 +18,13 @@ http://mozilla.org/MPL/2.0/.
// a collection of parameters for the rendering setup.
// for modern opengl this translates to set of attributes for shaders
struct opengl_material : public IMaterial {
- std::array textures = { null_handle };
+ using texture_set = std::array;
+
+ texture_set textures = { null_handle };
+ // alternative texture sets, defined with "textureN_variants:" key.
+ // one of them is picked per rendered model instance, empty when the material declares no variants.
+ // NOTE: all variants share the remaining material properties, opacity and translucency included
+ std::vector texture_variants;
std::array params;
std::vector params_state;
@@ -60,6 +66,14 @@ struct opengl_material : public IMaterial {
{
return textures[slot];
}
+ // returns texture set to use for model instance identified by provided variant id
+ texture_set const &GetTextures(std::uint32_t const Variant) const
+ {
+ return (
+ texture_variants.empty() ?
+ textures :
+ texture_variants[Variant % texture_variants.size()]);
+ }
// members
static struct path_data {
std::unordered_map index_map;
@@ -71,10 +85,23 @@ struct opengl_material : public IMaterial {
bool update_on_season_change{ false };
private:
+// types
+ // texture binding which comes with a pool of alternatives: slot the binding fills, and the pool itself
+ using variant_binding = std::pair const *>;
+
// methods
// imports member data pair from the config file
bool
deserialize_mapping( cParser &Input, int const Priority, bool const Loadnow );
+ // imports texture binding, potentially carrying a pool of alternatives, from the config file
+ void
+ deserialize_texture_mapping( cParser &Input, std::string const &Key, int const Priority );
+ // returns texture slot provided binding key resolves to, or -1 if it doesn't resolve to any
+ int
+ texture_slot( std::string const &Key );
+ // fills the alternative texture sets from provided pools, one set per entry of the longest pool
+ void
+ build_texture_variants( std::vector const &Bindings, bool const Loadnow );
void log_error(const std::string &str);
// members
@@ -90,6 +117,9 @@ private:
{
std::string name;
int priority;
+ // optional pool of alternative textures for the same binding, one picked per model instance.
+ // empty for regular, single texture bindings
+ std::vector variants;
};
struct param_def
{
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index 576cf404f..5419bbcdf 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -1286,6 +1286,7 @@ bool opengl33_renderer::Render_lowpoly( TDynamicObject *Dynamic, float const Squ
if( Setup ) {
TSubModel::iInstance = reinterpret_cast( Dynamic ); //żeby nie robić cudzych animacji
+ TSubModel::iVariantSeed = Dynamic->variant_seed();
glm::dvec3 const originoffset{ Dynamic->vPosition - m_renderpass.pass_camera.position() };
Dynamic->ABuLittleUpdate( Squaredistance ); // ustawianie zmiennych submodeli dla wspólnego modelu
@@ -2262,14 +2263,21 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel
else
model_ubs.alpha_mult = 1.0f;
+ // materials which declare texture variants provide a different texture set per model instance,
+ // picked from the seed of the rendered instance and the variant group of the submodel
+ auto const &materialtextures{
+ material.texture_variants.empty() ?
+ material.textures :
+ material.GetTextures(TSubModel::VariantId(sm))};
+
if (GLAD_GL_ARB_multi_bind)
{
GLuint lastdiff = 0;
size_t i;
for (i = 0; i < gl::MAX_TEXTURES; i++)
- if (material.textures[i] != null_handle)
+ if (materialtextures[i] != null_handle)
{
- opengl_texture &tex = m_textures.mark_as_used(material.textures[i]);
+ opengl_texture &tex = m_textures.mark_as_used(materialtextures[i]);
tex.create();
if (opengl_texture::units[i] != tex.id)
{
@@ -2286,7 +2294,7 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel
else
{
size_t unit = 0;
- for (auto &tex : material.textures)
+ for (auto &tex : materialtextures)
{
if (tex == null_handle)
break;
@@ -3351,6 +3359,7 @@ bool opengl33_renderer::Render(TDynamicObject *Dynamic)
// setup
TSubModel::iInstance = reinterpret_cast(Dynamic); //żeby nie robić cudzych animacji
+ TSubModel::iVariantSeed = Dynamic->variant_seed();
glm::dvec3 const originoffset = Dynamic->vPosition - m_renderpass.pass_camera.position();
// lod visibility ranges are defined for base (x 1.0) viewing distance. for render we adjust them for actual range multiplier and zoom
float squaredistance;
@@ -3518,10 +3527,12 @@ bool opengl33_renderer::Render_cab(TDynamicObject const *Dynamic, float const Li
{
TSubModel::iInstance = 0;
+ TSubModel::iVariantSeed = 0;
return false;
}
TSubModel::iInstance = reinterpret_cast(Dynamic);
+ TSubModel::iVariantSeed = Dynamic->variant_seed();
if ((true == FreeFlyModeFlag) || (false == Dynamic->bDisplayCab) || (Dynamic->mdKabina == Dynamic->mdModel))
{
@@ -4445,6 +4456,7 @@ bool opengl33_renderer::Render_Alpha(TDynamicObject *Dynamic)
// setup
TSubModel::iInstance = (size_t)Dynamic; //żeby nie robić cudzych animacji
+ TSubModel::iVariantSeed = Dynamic->variant_seed();
glm::dvec3 const originoffset = Dynamic->vPosition - m_renderpass.pass_camera.position();
// lod visibility ranges are defined for base (x 1.0) viewing distance. for render we adjust them for actual range multiplier and zoom
float squaredistance;
diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp
index d159c31aa..1da66ba51 100644
--- a/rendering/openglrenderer.cpp
+++ b/rendering/openglrenderer.cpp
@@ -801,6 +801,7 @@ bool opengl_renderer::Render_lowpoly( TDynamicObject *Dynamic, float const Squar
if( Setup ) {
TSubModel::iInstance = reinterpret_cast( Dynamic ); //żeby nie robić cudzych animacji
+ TSubModel::iVariantSeed = Dynamic->variant_seed();
Dynamic->ABuLittleUpdate( Squaredistance ); // ustawianie zmiennych submodeli dla wspólnego modelu
::glPushMatrix();
@@ -1759,10 +1760,17 @@ opengl_renderer::Bind_Material( material_handle const Material, TSubModel const
return;
}
+ // materials which declare texture variants provide a different texture set per model instance,
+ // picked from the seed of the rendered instance and the variant group of the submodel
+ auto const &materialtextures {
+ material.texture_variants.empty() ?
+ material.textures :
+ material.GetTextures( TSubModel::VariantId( sm ) ) };
+
if( false == Global.BasicRenderer ) {
- m_textures.bind( m_normaltextureunit, material.textures[1] );
+ m_textures.bind( m_normaltextureunit, materialtextures[1] );
}
- m_textures.bind( m_diffusetextureunit, material.textures[0] );
+ m_textures.bind( m_diffusetextureunit, materialtextures[0] );
}
else {
// null material, unbind all textures
@@ -2475,6 +2483,7 @@ opengl_renderer::Render( TDynamicObject *Dynamic ) {
// setup
TSubModel::iInstance = reinterpret_cast( Dynamic ); //żeby nie robić cudzych animacji
+ TSubModel::iVariantSeed = Dynamic->variant_seed();
Dynamic->ABuLittleUpdate( squaredistance ); // ustawianie zmiennych submodeli dla wspólnego modelu
::glPushMatrix();
@@ -2574,10 +2583,12 @@ opengl_renderer::Render_cab( TDynamicObject const *Dynamic, float const Lightlev
if( Dynamic == nullptr ) {
TSubModel::iInstance = 0;
+ TSubModel::iVariantSeed = 0;
return false;
}
TSubModel::iInstance = reinterpret_cast( Dynamic );
+ TSubModel::iVariantSeed = Dynamic->variant_seed();
if( ( true == FreeFlyModeFlag )
|| ( false == Dynamic->bDisplayCab )
@@ -2866,11 +2877,11 @@ opengl_renderer::Render( TSubModel *Submodel ) {
// material configuration:
// textures...
if( Submodel->m_material < 0 ) { // zmienialne skóry
- Bind_Material( Submodel->ReplacableSkinId[ -Submodel->m_material ] );
+ Bind_Material( TSubModel::ReplacableSkinId[ -Submodel->m_material ], Submodel );
}
else {
// również 0
- Bind_Material( Submodel->m_material );
+ Bind_Material( Submodel->m_material, Submodel );
}
// main draw call
m_geometry.draw( Submodel->m_geometry.handle );
@@ -2884,11 +2895,11 @@ opengl_renderer::Render( TSubModel *Submodel ) {
::glColor3fv( glm::value_ptr( pick_color( m_pickcontrolsitems.size() ) ) );
// textures...
if( Submodel->m_material < 0 ) { // zmienialne skóry
- Bind_Material( Submodel->ReplacableSkinId[ -Submodel->m_material ] );
+ Bind_Material( TSubModel::ReplacableSkinId[ -Submodel->m_material ], Submodel );
}
else {
// również 0
- Bind_Material( Submodel->m_material );
+ Bind_Material( Submodel->m_material, Submodel );
}
// main draw call
m_geometry.draw( Submodel->m_geometry.handle );
@@ -3657,6 +3668,7 @@ opengl_renderer::Render_Alpha( TDynamicObject *Dynamic ) {
// setup
TSubModel::iInstance = ( size_t )Dynamic; //żeby nie robić cudzych animacji
+ TSubModel::iVariantSeed = Dynamic->variant_seed();
glm::dvec3 const originoffset = Dynamic->vPosition - m_renderpass.camera.position();
// lod visibility ranges are defined for base (x 1.0) viewing distance. for render we adjust them for actual range multiplier and zoom
float squaredistance;
@@ -3909,11 +3921,11 @@ opengl_renderer::Render_Alpha( TSubModel *Submodel ) {
// material configuration:
// textures...
if( Submodel->m_material < 0 ) { // zmienialne skóry
- Bind_Material( Submodel->ReplacableSkinId[ -Submodel->m_material ] );
+ Bind_Material( TSubModel::ReplacableSkinId[ -Submodel->m_material ], Submodel );
}
else {
// również 0
- Bind_Material( Submodel->m_material );
+ Bind_Material( Submodel->m_material, Submodel );
}
// main draw call
m_geometry.draw( Submodel->m_geometry.handle );
diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp
index c1d0b73d0..14e448973 100644
--- a/utilities/utilities.cpp
+++ b/utilities/utilities.cpp
@@ -527,4 +527,42 @@ std::string deserialize_random_set(cParser &Input, char const *Break)
// shouldn't ever get here but, eh
return "";
}
-}
\ No newline at end of file
+}
+
+// returns hash of provided string, combined with provided seed
+std::uint32_t hash_string(std::string const &String, std::uint32_t const Seed)
+{
+ // FNV-1a, 32 bit, with the seed mixed into the standard offset basis
+ std::uint32_t hash{2166136261u ^ Seed};
+ for (auto const character : String)
+ {
+ hash ^= static_cast(static_cast(character));
+ hash *= 16777619u;
+ }
+ return hash;
+}
+
+// extracts a group of tokens from provided data stream, returns all of them
+std::vector deserialize_set(cParser &Input, char const *Break)
+{
+
+ std::vector tokens;
+
+ auto token{Input.getToken(true, Break)};
+ std::ranges::replace(token, '\\', '/');
+ if (token != "[")
+ {
+ // simple case, single token
+ if (false == token.empty())
+ {
+ tokens.emplace_back(token);
+ }
+ return tokens;
+ }
+ // '[' marks a beginning of a set, retrieve all entries until it's closed
+ while ((token = deserialize_random_set(Input, Break)) != "" && token != "]")
+ {
+ tokens.emplace_back(token);
+ }
+ return tokens;
+}
diff --git a/utilities/utilities.h b/utilities/utilities.h
index 70cf1c07c..91d74e67a 100644
--- a/utilities/utilities.h
+++ b/utilities/utilities.h
@@ -377,6 +377,14 @@ glm::dvec3 LoadPoint(class cParser &Input);
// extracts a group of tokens from provided data stream
std::string deserialize_random_set(cParser &Input, char const *Break = "\n\r\t ;");
+// extracts a group of tokens from provided data stream, returns all of them.
+// a single token, not enclosed in "[]", is returned as one element sequence
+std::vector deserialize_set(cParser &Input, char const *Break = "\n\r\t ;");
+
+// returns hash of provided string, combined with provided seed. FNV-1a, picked for having
+// identical result regardless of platform and standard library, unlike std::hash
+std::uint32_t hash_string(std::string const &String, std::uint32_t const Seed = 0);
+
// extracts a group of pairs from provided data stream
// NOTE: expects no more than single pair per line
template void deserialize_map(MapType_ &Map, cParser &Input)
diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp
index 184d432ae..e84af6137 100644
--- a/vehicle/DynObj.cpp
+++ b/vehicle/DynObj.cpp
@@ -1934,6 +1934,10 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424"
iDirection = Reversed ? 0 : 1; // Ra: 0, jeśli ma być wstawiony jako obrócony tyłem
asBaseDir = paths::dynamic + BaseDir + "/"; // McZapkie-310302
asName = Name;
+ // derived from the name and the seed of the simulation rather than drawn at random, so that the vehicle
+ // keeps the same look for the whole session and looks the same for everyone in a multiplayer game, while
+ // another run of the same scenario, with another seed, dresses it differently
+ m_variantseed = hash_string( asName, Global.random_seed );
std::string asAnimName; // zmienna robocza do wyszukiwania osi i wózków
// Ra: zmieniamy znaczenie obsady na jednoliterowe, żeby dosadzić kierownika
if (DriverType == "headdriver")
diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h
index f8f2ce780..c48e40e14 100644
--- a/vehicle/DynObj.h
+++ b/vehicle/DynObj.h
@@ -634,6 +634,10 @@ private:
std::string asName;
const std::string &name() const {
return asName; }
+ // seed for texture variants of materials used by this vehicle and its load
+ std::uint32_t m_variantseed { 0 };
+ std::uint32_t variant_seed() const {
+ return m_variantseed; }
std::string asBaseDir;
// std::ofstream PneuLogFile; //zapis parametrow pneumatycznych
From 36d4f16c01abd9404c7e3b59547260f33191b0ba Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Sun, 27 Sep 2026 17:50:07 +0200
Subject: [PATCH 007/430] Brake force table: take the rapid step threshold from
the distributor
TMoverParameters::BrakeForceR() halves the force of a vehicle set to R
below 40 km/h. That is one approximation for every distributor, but a
NESt3/ESt4 distributor with a rapid relay engages the step above 70 km/h
and keeps it down to 50 km/h (TNESt3::GetPF, RapidStatus), and below
that its cylinder pressure is divided by the relay's own multiplier
(TRapid, RapidMult). For a vehicle braking from speed the full force
therefore lasts down to 50 km/h, not 40. The AI builds its consist brake
table (fBrake_a0/a1) from BrakeForceR(), so between 40 and 50 km/h it
expected twice the force the wagons actually deliver.
Add TBrake::GetRapidRatio(), which keeps the old approximation as the
default, and override it in TNESt3 with the relay's threshold and
multiplier. The brake itself is unchanged; only the prediction is.
---
McZapkie/Mover.cpp | 4 ++--
McZapkie/Oerlikon_ESt.cpp | 11 +++++++++++
McZapkie/Oerlikon_ESt.h | 2 ++
McZapkie/hamulce.h | 5 +++++
4 files changed, 20 insertions(+), 2 deletions(-)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 83c918e24..a58878ab4 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -5166,8 +5166,8 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity)
press = MaxBrakePress[3];
if (DynamicBrakeType == dbrake_automatic)
ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02);
- if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1 && velocity < 40)
- ratio = ratio / 2;
+ if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1)
+ ratio *= Hamulec->GetRapidRatio(velocity);
if (TrainType == dt_DMU && velocity < 30.0)
{
ratio -= 0.3;
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index 9559d3052..d8d5b3da8 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -324,6 +324,17 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c
RapidStaly = false;
}
+double TNESt3::GetRapidRatio(double const Vel) const
+{
+ // ESt3 has no rapid relay, and with disc brakes the rapid step stays engaged at all speeds
+ if( ( PrzekRapid == nullptr ) || ( true == RapidStaly ) ) {
+ return 1.0;
+ }
+ // a braking vehicle comes from above, so the step is still engaged down to the speed
+ // at which GetPF() drops it, not the one at which it engages
+ return ( Vel < 50.0 ? 1.0 / PrzekRapid->GetRapidMult() : 1.0 );
+}
+
double TNESt3::GetCRP()
{
return CntrlRes->P();
diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h
index c12691851..180c47206 100644
--- a/McZapkie/Oerlikon_ESt.h
+++ b/McZapkie/Oerlikon_ESt.h
@@ -117,6 +117,7 @@ class TRapid : public TPrzekladnik {
public:
void SetRapidParams(double mult, double size);
void SetRapidStatus(bool rs);
+ double GetRapidMult() const { return RapidMult; }
void Update(double dt) /*override*/;
inline TRapid() :
TPrzekladnik()
@@ -213,6 +214,7 @@ class TNESt3 : public TBrake {
virtual double GetPF( double const PP, double const dt, double const Vel ) /*override*/; // przeplyw miedzy komora wstepna i PG
void EStParams(double i_crc); // parametry charakterystyczne dla ESt
virtual double GetCRP() /*override*/;
+ double GetRapidRatio(double const Vel) const override;
void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy
void CheckReleaser(double const dt); // odluzniacz
double CVs(double const BP); // napelniacz sterujacego
diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h
index a05a36359..11b8bdfb3 100644
--- a/McZapkie/hamulce.h
+++ b/McZapkie/hamulce.h
@@ -442,6 +442,11 @@ class TBrake
/// Sets the rapid step ratio. Default no-op; overridden where supported.
/// Rapid ratio.
virtual void SetRM(double const RMR) {}; // ustalenie przelozenia rapida
+ /// Share of the full cylinder pressure the distributor delivers at the given speed
+ /// while the vehicle is slowing down through it, for a vehicle set to R. Used only to predict
+ /// the brake force; the default is the approximation BrakeForceR() has always used.
+ /// Vehicle velocity [km/h].
+ virtual double GetRapidRatio(double const Vel) const { return Vel < 40.0 ? 0.5 : 1.0; }
/// Sets the velocity threshold for the rapid step.
/// Velocity threshold (same unit as Vel passed to GetPF).
virtual void SetRV(double const RVR)
From 92bd7ef827196e0ae7f3dfa6e5cbabf93eb87390 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 28 Sep 2026 15:45:10 +0200
Subject: [PATCH 008/430] AI braking: hold the speed on a descent
Two changes that only work together: the first on its own lets a heavy
freight train brake less on a descent than it needs (in testing an
ET42 with 30 loaded wagons overran the stop signal by 16-48 m at 20 per
mille), the second makes the hold on a descent what it should be.
The comparison that decides whether the AI may skip its reaction time
between two brake steps stays on the brake-only demand, as before: it
is about how much brake is asked for, and a heavy train in G approaching
a stop on a descent needs its brake built up at once. Compared in the
resultant frame, that train built up its brake one step per reaction
time and overran the signal (16 copies of the ET42 train, x20:
22 of 32 overruns with the comparison moved, 0 of 48 with it kept).
1. Compare the measured deceleration in the same frame.
Going downhill, adjust_desired_speed_for_current_speed() subtracts the
gravity component from AccDesired, so that IncBrake() sizes the handle
position for what the brake alone has to deliver. control_braking_force()
then compares that brake-only value with AbsAccS, which is the resultant
acceleration and already contains the gravity. On a 20 per mille descent
the two differ by about 0.2 m/s2, so the AI asked for more braking than
the target needed and then released, and repeated that.
Keep the subtracted part in fAccDesiredGravity and add it back wherever
AccDesired is compared with AbsAccS. It is zero everywhere else (flat,
uphill, braking test), so the behaviour there does not change.
2. Hold the speed with one continuous law.
On a descent the AI looks ahead to decide whether it will exceed the
target speed. The look-ahead was (1 - a0) * 30 / 3.6 s, a few seconds,
while a pneumatic brake in G takes tens of seconds to apply or to
release; the AI therefore acted on an estimate the train had already
left behind. The demand then jumped between the braking threshold above
the target and a lerp towards full acceleration below it, and with the
brake that slow this turned into long alternating applications and
releases.
- look ahead for half the brake application time while the train is
speeding up and half the release time while it is slowing down
(brake_response_horizon), never less than before;
- use one law on both sides of the target, proportional to the
predicted difference, and hold a band just below the limit that widens
with the gradient (pneumatic up to 3 km/h, EP/electric up to 1.5 km/h);
- once below a lower limit ahead, hold that limit instead of speeding up
towards the line speed and braking again.
---
vehicle/Driver.cpp | 101 ++++++++++++++++++++++++++++++++++-----------
vehicle/Driver.h | 1 +
2 files changed, 77 insertions(+), 25 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 9a6de8596..5b61b6dd1 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -7483,6 +7483,25 @@ TController::adjust_desired_speed_for_limits() {
}
}
+// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time
+// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G
+// is tens of seconds; never shorter than the look-ahead the AI has always used
+static double
+brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) {
+
+ auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 };
+ if( Brakesystem == TBrakeSystem::Pneumatic ) {
+ auto const isrelease { Acceleration < 0.0 };
+ horizon = std::max(
+ horizon,
+ 0.5 * (
+ Vehicle->BrakeDelayFlag > bdelay_G ?
+ Vehicle->BrakeDelay[ isrelease ? 0 : 1 ] :
+ Vehicle->BrakeDelay[ isrelease ? 2 : 3 ] ) );
+ }
+ return horizon;
+}
+
void
TController::adjust_desired_speed_for_target_speed( double const Range ) {
// ustalanie zadanego przyspieszenia
@@ -7496,6 +7515,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
// gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze
// normalna jazda
AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01;
+ fAccDesiredGravity = 0.0;
auto const vel { DirectionalVel() };
@@ -7654,35 +7674,57 @@ TController::adjust_desired_speed_for_current_speed() {
if( fAccGravity > 0.025 ) {
// going sharply downhill we may need to start braking sooner than usual
// try to estimate increase of current velocity before engaged brakes start working
- auto const speedestimate = vel + ( 1.0 - fBrake_a0[ 0 ] ) * 30.0 * AbsAccS;
- if( speedestimate > VelDesired ) {
- // jesli jedzie za szybko do AKTUALNEGO
- if( VelDesired == 0.0 ) {
- // jesli stoj, to hamuj, ale i tak juz za pozno :)
- AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie
- }
- else {
- // if it looks like we'll exceed maximum speed start thinking about slight slowing down
- AccDesired = std::min( AccDesired, -0.05 + fAccThreshold );
- // HACK: for cargo trains with high braking threshold ensure we cross that threshold
- if( true == IsCargoTrain
- && fBrake_a0[0] > 0.2 ) {
- AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
- }
- }
+ // look ahead for as long as the brake takes to respond, since that is how long the
+ // present acceleration will last whatever is done with the handle now; a pneumatic
+ // brake applies and releases on its own time scale, which in G is tens of seconds
+ auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
+ auto const speedestimate = vel + 3.6 * horizon * AbsAccS;
+ // already below a lower limit ahead, the train has no business speeding up towards it
+ auto holdlimit { VelDesired };
+ if( ( VelNext > 0.0 )
+ && ( VelNext < holdlimit )
+ && ( vel <= VelNext + fVelPlus )
+ && ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) {
+ holdlimit = VelNext;
+ }
+ // hold a band just below the limit; the steeper the descent the harder the train pulls
+ // away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille)
+ // an electro-pneumatic or electric brake responds at once and needs far less room
+ auto const holdspeed { holdlimit - (
+ BrakeSystem == TBrakeSystem::Pneumatic ?
+ std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) :
+ std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) };
+ if( ( speedestimate > VelDesired )
+ && ( VelDesired == 0.0 ) ) {
+ // jesli stoj, to hamuj, ale i tak juz za pozno :)
+ AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie
}
else {
- // stop accelerating when close enough to target speed
+ // one continuous law on both sides of the target, proportional to the predicted
+ // difference: a demand that jumps to the braking threshold above the target and to
+ // full acceleration below it alternates, with a brake that responds in seconds,
+ // between a hard application and a full release
AccDesired = std::min(
AccDesired, // but don't override decceleration for VelNext
- std::lerp( // ease off as you close to the target velocity
- EU07_AI_NOACCELERATION, AccPreferred,
- std::clamp( VelDesired - speedestimate, 0.0, fVelMinus ) / fVelMinus ) );
+ std::clamp(
+ EU07_AI_NOACCELERATION - 0.04 * ( speedestimate - holdspeed ),
+ -0.05 + fAccThreshold,
+ std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
+ // HACK: for cargo trains with high braking threshold ensure we cross that threshold
+ if( true == IsCargoTrain
+ && fBrake_a0[0] > 0.2
+ && speedestimate > holdlimit ) {
+ AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
+ }
}
// final tweaks
if( vel > EU07_AI_NOMOVEMENT ) {
// going downhill also take into account impact of gravity
AccDesired -= fAccGravity;
+ // from here on AccDesired is what the brake alone has to deliver, which is what
+ // IncBrake() sizes the handle position for; AbsAccS already contains the gravity,
+ // so the comparisons with it have to add this part back
+ fAccDesiredGravity = fAccGravity;
// HACK: if the max allowed speed was exceeded something went wrong; brake harder
AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 );
}
@@ -7773,6 +7815,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 1: {
AccDesired = EU07_AI_BRAKINGTESTACCELERATION;
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( ElapsedTime - DBT_BrakingTime > 1 ) {
ForcePNBrake = true;
@@ -7783,6 +7826,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 2: {
AccDesired = EU07_AI_BRAKINGTESTACCELERATION;
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( ElapsedTime - DBT_BrakingTime > 2 ) {
DBT_BrakingTime = ElapsedTime;
@@ -7794,6 +7838,7 @@ TController::adjust_desired_speed_for_braking_test() {
}
case 3: {
AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 );
+ fAccDesiredGravity = 0.0;
VelDesired = DBT_VelocityBrake;
if( vel <= DBT_VelocityRelease ) {
DynamicBrakeTest = 4;
@@ -7980,6 +8025,10 @@ void TController::control_braking_force() {
}
}
+ // AbsAccS is the resultant acceleration, gravity included, so it is compared with the
+ // resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent
+ auto const accdesiredresultant { AccDesired + fAccDesiredGravity };
+
if( is_emu() && !ForcePNBrake ) {
// właściwie, to warunek powinien być na działający EP
// Ra: to dobrze hamuje EP w EZT
@@ -7991,13 +8040,13 @@ void TController::control_braking_force() {
auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ?
0.05 : 0.0;
if( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
- && ( AbsAccS > AccDesired + accmargin
+ && ( AbsAccS > accdesiredresultant + accmargin
|| BrakeCtrlPosition < 0 ) ) {
// hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired)
cue_action( driver_hint::brakingforceincrease );
}
else if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca
- if( AbsAccS < AccDesired - 0.05 ) {
+ if( AbsAccS < accdesiredresultant - 0.05 ) {
// jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo
// TBD: check if the condition isn't redundant with the DecBrake() code
if( BrakeCtrlPosition >= 0 ) {
@@ -8013,10 +8062,12 @@ void TController::control_braking_force() {
} // type & dt_ezt
else {
// a stara wersja w miarę dobrze działa na składy wagonowe
- if( ( AccDesired < fAccGravity - 0.1 && AbsAccS > AccDesired + fBrake_a1[0] ) // regular braking
+ if( ( accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + fBrake_a1[0] ) // regular braking
|| ( fAccGravity < -0.05 && velocity < -0.1 ) ) { // also brake if uphill and slipping back
// u góry ustawia się hamowanie na fAccThreshold
if( fBrakeTime < 0.0
+ // the size of the brake demand decides whether to skip the reaction time, so the brake-only part
+ // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow)
|| AccDesired < fAccGravity - 0.5
|| BrakeCtrlPosition <= 0 ) {
// jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował
@@ -8033,8 +8084,8 @@ void TController::control_braking_force() {
* 0.5 ); // Ra: tymczasowo, bo przeżyna S1
}
}
- if ( AccDesired < fAccGravity - 0.05
- && AccDesired - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
+ if ( accdesiredresultant < fAccGravity - 0.05
+ && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
// jak hamuje, to nie tykaj kranu za często
// yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2
if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index e7c4fac00..c493afc8a 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -387,6 +387,7 @@ private:
double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj)
double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal
double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie
+ double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
double VelLimit = -1.0; // predkość zadawana przez event jednokierunkowego ograniczenia prędkości // -1: brak ograniczenia prędkości
From ce87aa0e090d4b5fba7042588df6e5e71895d5a1 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 28 Sep 2026 15:45:10 +0200
Subject: [PATCH 009/430] AI braking: plan approaches from the consist brake,
stop 8-15 m short
The new braking curve below plans the stop at the signal itself unless
the stopping point moves with it (in testing, trains stopped 0-3 m past
the signal), so both go in one change.
1. The braking curve.
The braking curve towards a lower speed or a stop assumed a constant
deceleration from the present speed over the whole distance. A pneumatic
brake does not work like that:
- it acts on the state the train is in once it has applied; while the
train is still speeding up (downhill), plan from the speed it will have
reached by then, over the distance left by then;
- cast iron blocks grip harder as the train slows, so a constant
deceleration plan asks for too much at the start and then releases;
follow the shape of the consist brake table (fBrake_a0/a1) over speed
instead (shaped_braking_demand), over the distance left once the brake
has had its fill time;
- no power while the train is still above the speed it is braking for.
IncBrake() only adds braking when the brake table says the present
position is not enough. When the table overestimates the consist (see
the previous rapid step fix, or a descent), the train keeps slowing too
little with the handle held. After the full fill time with the handle
unchanged, believe the train rather than the table (fBrakeHeldTime).
When the AI asks for no braking and the train is still slowing down more
than that, release. With the gentler plan above the demand eases off
early, and without this a heavy freight train in G came to a stand a few
hundred metres before a W4 with its brake still on (seen in testing).
2. The stopping window.
In train running the final approach to a stop signal began at
fMaxProximityDist (15-40 m, cargo 25-50 m), aimed at half of
fMinProximityDist (10-15 m, cargo 20-25 m), and set VelDesired = 0,
which asks for hard braking whatever the distance left. Where a train
came to a stand depended on how it entered that phase: on the test
sceneries anywhere from 1 to 45 m short of the signal on the flat and
25-42 m uphill for heavy freight.
For train running only (a W4 stop point, shunting and coupling keep the
old margins and the old final approach):
- stop 8-15 m short of the signal whatever the length of the train, aim
at the middle of that window (stopping_margin) both with the braking
curve and in the final approach, and ask there only for what the
distance left takes, following the consist brake table;
- start the final approach 50 m out (cargo 60 m) whether the train is
moving or standing; it used to be 15-40 m while moving and 50 m once
stopped, and with the gentler final approach above a train that came
to a stand between the two released to creep closer and, uphill,
rolled back and tried again;
- uphill, while the gradient alone would bring the train to a stand short
of the window, keep it rolling at no more than the speed the gradient
can take off by then, with power if needed;
- uphill, put the train brake on as the train comes to a stand, keep it
on while it stands, and apply it for real if the train rolls back. This
is done at the very end of pick_optimal_speed(): the adjustments made
before it assume a train moving forward and can raise the demand back
to "no braking" (with the rule placed earlier, EMUs rolled back up to
90 m in testing). The EMU branch of
control_braking_force() gets the "slipping back" condition the wagon
branch has always had.
3. Known limitation.
Heavy trains of wagons with the ESt3AL2 distributor (413S, 601W and
alike) respond more slowly than the AI expects: with the present brake
model the distributor fills the AL2 relay chamber, whose capacity is set
to 2 in TNESt3::SetSize (Przekladniki[i]->CreateCap(i)), through
orifices sized for about 1 l, so these wagons need 34 s to reach 95 %
cylinder pressure in G against 21 s for a plain ESt3. On a 20 per mille
descent an ET22 with 20 loaded 413S wagons overran the stop signal by up
to 6.5 m in 6 of 24 runs at x20 with this change. With the relay chamber
at 1 l and the release orifices at about 80 % of their diameter, as the
author of the brake model suggested, none of them did (0 of 16).
---
vehicle/Driver.cpp | 217 ++++++++++++++++++++++++++++++++++++++++-----
vehicle/Driver.h | 7 ++
2 files changed, 200 insertions(+), 24 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 5b61b6dd1..09b607b69 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -3122,6 +3122,17 @@ bool TController::IncBrake()
}
}
}
+ else if( BrakeCtrlPosition > 0.0
+ && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting
+ && fBrakeHeldTime > (
+ mvOccupied->BrakeDelayFlag > bdelay_G ?
+ mvOccupied->BrakeDelay[ 1 ] :
+ mvOccupied->BrakeDelay[ 3 ] ) ) {
+ // the table says the present position is enough, but the brake has had its full fill
+ // time since the handle last moved and the train is still not slowing down as asked:
+ // believe the train rather than the table
+ OK = BrakeLevelAdd( BrakingLevelIncrease );
+ }
else
OK = false;
}
@@ -3781,6 +3792,7 @@ void TController::BrakeLevelSet(double b)
if (BrakeCtrlPosition == b)
return; // nie przeliczać, jak nie ma zmiany
BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX);
+ fBrakeHeldTime = 0.0;
}
bool TController::BrakeLevelAdd(double b)
@@ -5911,6 +5923,7 @@ TController::update_timers( double dt ) {
ElapsedTime += dt;
WaitingTime += dt;
fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca
+ fBrakeHeldTime += dt;
if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) {
// brake charging timeout starts after charging ends
BrakeChargingCooldown += dt;
@@ -6659,12 +6672,27 @@ TController::determine_proximity_ranges() {
// na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody
// jeśli pociąg
if( is_train() ) {
- fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
- fMaxProximityDist = std::clamp( 10 + iVehicles, 15, 40 );
+ if( true == IsAtPassengerStop ) {
+ // a stop point keeps the margins its W4 parameters (head or middle of the consist,
+ // platform length) were set up against
+ fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
+ fMaxProximityDist = std::clamp( 10 + iVehicles, 15, 40 );
+ if( IsCargoTrain ) {
+ fMinProximityDist += 10.0;
+ }
+ }
+ else {
+ // a train stops 8-15 m short of the signal whatever its length; closer than the lower
+ // edge it stops at once, the braking aims at the middle of the window, 3.5 m further out
+ fMinProximityDist = 8.0;
+ // the final approach begins far enough out to slow from the coasting speed down to the window,
+ // and at the same distance whether the train is moving or standing, so it does not flip
+ // between creeping closer and holding still when it comes to a stand short of the window
+ fMaxProximityDist = 50.0;
+ }
if( IsCargoTrain ) {
- // increase distances for cargo trains to take into account slower reaction to brakes
- fMinProximityDist += 10.0;
+ // start the final approach earlier for cargo trains, their brakes react more slowly
fMaxProximityDist += 10.0;
/*
if( IsHeavyCargoTrain ) {
@@ -6683,7 +6711,7 @@ TController::determine_proximity_ranges() {
if( mvOccupied->Vel < 0.1 ) {
// jak stanie za daleko, to niech nie dociąga paru metrów
- fMaxProximityDist = 50.0;
+ fMaxProximityDist = std::max( fMaxProximityDist, 50.0 );
}
if( iDrivigFlags & moveLate ) {
@@ -7314,6 +7342,26 @@ TController::pick_optimal_speed( double const Range ) {
is_car() ? -2.0 : -0.9,
is_car() ? 2.0 : 0.9 );
+ if( ( true == is_train() )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( VelNext == 0.0 )
+ && ( ActualProximityDist <= fMaxProximityDist )
+ && ( fAccGravity < -0.025 ) ) {
+ // uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released
+ // brake applies; so the train brake goes on while the train is coming to a stand, stays on while it
+ // stands, and is applied for real if the train has started to roll back. done last, so that none of
+ // the adjustments above, made for a train moving forward, can undo it
+ auto const vel { DirectionalVel() };
+ if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) {
+ VelDesired = 0.0;
+ AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
+ }
+ else if( ( vel < 0.0 )
+ || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) ) {
+ AccDesired = std::min( AccDesired, fAccGravity - 0.15 );
+ }
+ }
+
// if the route ahead is blocked we might need to head the other way
check_route_behind( 1000 ); // NOTE: legacy scan range value
}
@@ -7502,6 +7550,55 @@ brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brak
return horizon;
}
+// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand
+static double
+uphill_stopping_distance( double const Velocity, double const Gravity ) {
+ return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) );
+}
+
+// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m]
+static double
+uphill_coasting_speed( double const Distance, double const Gravity ) {
+ return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) );
+}
+
+// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train
+// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the
+// consist brake table says it does (cast iron blocks grip harder as the train slows)
+static double
+shaped_braking_demand(
+ double const Velocity, double const Target, double const Distance, double const Gravity,
+ double const Vmax, double const *Brakea0, double const *Brakea1, int const Tablesize ) {
+
+ auto const fullbraking = [&]( double const Kmh ) {
+ auto const index { std::clamp( static_cast( Tablesize * Kmh / std::max( 1.0, Vmax ) ), 1, Tablesize ) };
+ return std::max( 0.01, Brakea0[ index ] + 12.0 * Brakea1[ index ] ); };
+ auto const travel = [&]( double const Ratio ) {
+ auto const steps { 24 };
+ auto const step { ( Velocity - Target ) / steps };
+ auto distance { 0.0 };
+ for( auto i { 0 }; i < steps; ++i ) {
+ auto const kmh { Target + ( i + 0.5 ) * step };
+ auto const deceleration { Ratio * fullbraking( kmh ) - Gravity };
+ if( deceleration <= 0.001 ) {
+ return std::numeric_limits::max();
+ }
+ distance += ( kmh / 3.6 ) * ( step / 3.6 ) / deceleration;
+ }
+ return distance; };
+
+ auto low { 0.0 };
+ auto high { 3.0 };
+ if( travel( high ) > Distance ) {
+ return Gravity - high * fullbraking( Velocity );
+ }
+ for( auto i { 0 }; i < 30; ++i ) {
+ auto const middle { 0.5 * ( low + high ) };
+ ( travel( middle ) > Distance ? low : high ) = middle;
+ }
+ return Gravity - high * fullbraking( Velocity );
+}
+
void
TController::adjust_desired_speed_for_target_speed( double const Range ) {
// ustalanie zadanego przyspieszenia
@@ -7552,9 +7649,33 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
}
else {
// hamowanie tak, aby stanąć
- VelDesired = VelNext;
- AccDesired = ( VelNext * VelNext - vel * vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
- AccDesired = std::min( AccDesired, fAccThreshold );
+ if( ( OrderCurrentGet() & Obey_train ) == 0 ) {
+ VelDesired = VelNext;
+ AccDesired = ( VelNext * VelNext - vel * vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
+ AccDesired = std::min( AccDesired, fAccThreshold );
+ }
+ else {
+ // a train keeps its desired speed until the lower edge of the stopping window (a desired
+ // speed of 0 here asks for hard braking whatever the distance left), aims at the middle
+ // of the window, and asks only for what that takes
+ auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) };
+ AccDesired = (
+ BrakeSystem == TBrakeSystem::Pneumatic ?
+ // cast iron blocks grip harder as the train comes to a stand
+ shaped_braking_demand(
+ vel, VelNext, stoppingroom, fAccGravity,
+ mvOccupied->Vmax, fBrake_a0, fBrake_a1, BrakeAccTableSize ) :
+ ( VelNext * VelNext - vel * vel ) / ( 25.92 * stoppingroom ) );
+ if( ( fAccGravity < -0.025 )
+ && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all
+ && ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > stopping_margin() ) ) {
+ // uphill the gradient alone would bring the train to a stand short of the
+ // middle of the stopping window; keep it rolling at the present speed until that changes,
+ // but no faster than the gradient alone can take off by the middle of the window
+ AccDesired = std::min( 0.0, AccPreferred );
+ VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) );
+ }
+ }
}
}
else {
@@ -7578,17 +7699,57 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) {
if( brakingdistance + std::max(slowdowndistance, fMaxProximityDist) >= ActualProximityDist - fMaxProximityDist ) {
// don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good
// ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever
- auto const brakingpointoffset = VelNext * braking_distance_multiplier( VelNext );
- AccDesired = std::min(
- AccDesired,
- ( VelNext * VelNext - vel * vel )
- / ( 25.92
- * std::max(
- ActualProximityDist - brakingpointoffset,
- std::min(
- ActualProximityDist,
- brakingpointoffset ) )
- + 0.1 ) ); // najpierw hamuje mocniej, potem zluzuje
+ auto const brakingpointoffset = (
+ ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ?
+ stopping_margin() : // the same stopping point as the final approach
+ VelNext * braking_distance_multiplier( VelNext ) );
+ // a pneumatic brake acts on the state the train will be in once it has responded; while the
+ // train is still speeding up, plan the deceleration from there, so more is asked for at once
+ auto velocity { vel };
+ auto distance { ActualProximityDist };
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic )
+ && ( AbsAccS > 0.0 ) ) {
+ auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
+ velocity = vel + 3.6 * horizon * AbsAccS;
+ distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( vel + velocity ) * 0.5 / 3.6 * horizon );
+ }
+ auto const brakingroom {
+ std::max(
+ distance - brakingpointoffset,
+ std::min(
+ distance,
+ brakingpointoffset ) ) };
+ auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) };
+ if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) {
+ // follow the shape of the consist brake force over speed rather than assume a constant
+ // deceleration, over the distance left once the brake has had time to fill (while the
+ // train is still speeding up, the prediction above has taken that off already)
+ auto room { brakingroom };
+ if( ( AbsAccS <= 0.0 )
+ && ( ( VelNext > 0.0 ) || ( BrakeCtrlPosition <= 0.0 ) ) ) { // for a stop, only while the brake is still to be applied
+ room = std::max(
+ 0.5 * brakingroom,
+ brakingroom - vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) );
+ }
+ deceleration = shaped_braking_demand(
+ velocity, VelNext, room + 0.1 / 25.92, fAccGravity,
+ mvOccupied->Vmax, fBrake_a0, fBrake_a1, BrakeAccTableSize );
+ }
+ AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje
+ if( vel > VelNext ) {
+ if( deceleration < fAccGravity - 0.001 ) {
+ // no power while still above the speed being braked for
+ AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
+ }
+ else if( ( fAccGravity < -0.025 )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( ActualProximityDist - uphill_stopping_distance( vel, fAccGravity ) > brakingpointoffset ) ) {
+ // uphill the gradient alone slows the train down more than it is asked to;
+ // keep it rolling at the present speed until that changes
+ AccDesired = std::min( 0.0, AccPreferred );
+ VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) );
+ }
+ }
}
}
}
@@ -7959,7 +8120,13 @@ void TController::control_tractive_force() {
if( ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance
fMaxProximityDist) ? // other vehicle types keep wider margin
true :
- velocity + 1.0 < VelNext ) {
+ ( velocity + 1.0 < VelNext )
+ // uphill, a train told to hold its speed on the way to a stop needs the power to do it
+ || ( ( VelNext == 0.0 )
+ && ( ( OrderCurrentGet() & Obey_train ) != 0 )
+ && ( AccDesired >= 0.0 )
+ && ( fAccGravity < -0.025 )
+ && ( ActualProximityDist > fMinProximityDist ) ) ) {
// ...to można przyspieszyć
increase_tractive_force();
}
@@ -8039,9 +8206,10 @@ void TController::control_braking_force() {
auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) };
auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ?
0.05 : 0.0;
- if( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
- && ( AbsAccS > accdesiredresultant + accmargin
- || BrakeCtrlPosition < 0 ) ) {
+ if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
+ && ( AbsAccS > accdesiredresultant + accmargin
+ || BrakeCtrlPosition < 0 ) )
+ || ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back
// hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired)
cue_action( driver_hint::brakingforceincrease );
}
@@ -8084,7 +8252,8 @@ void TController::control_braking_force() {
* 0.5 ); // Ra: tymczasowo, bo przeżyna S1
}
}
- if ( accdesiredresultant < fAccGravity - 0.05
+ if ( ( accdesiredresultant < fAccGravity - 0.05
+ || AccDesired >= EU07_AI_NOACCELERATION ) // no braking asked for, yet the train is slowing down more than that
&& accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 ) {
// jak hamuje, to nie tykaj kranu za często
// yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index c493afc8a..0e65a4b94 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -353,6 +353,12 @@ private:
void control_tractive_force();
void increase_tractive_force();
void control_braking_force();
+ // how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal,
+ // otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before
+ double stopping_margin() const {
+ return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && ( false == IsAtPassengerStop ) ?
+ fMinProximityDist + 3.5 :
+ 0.5 * fMinProximityDist; }
void apply_independent_brake_only();
void check_route_ahead( double const Range );
void check_route_behind( double const Range );
@@ -387,6 +393,7 @@ private:
double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj)
double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal
double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie
+ double fBrakeHeldTime = 0.0; // czas od ostatniego przestawienia kranu hamulca zasadniczego
double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam
double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?)
double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie
From 551f6dbc3bb7d756d50c5e07f5109377898b26de Mon Sep 17 00:00:00 2001
From: Hirek193
Date: Mon, 28 Sep 2026 20:49:18 +0200
Subject: [PATCH 010/430] seasonal model variants for vehicle exterior model
---
rendering/opengl33renderer.cpp | 8 ++++++--
rendering/openglrenderer.cpp | 4 +++-
vehicle/DynObj.cpp | 21 +++++++++++++++++++++
vehicle/DynObj.h | 5 +++++
4 files changed, 35 insertions(+), 3 deletions(-)
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index 5419bbcdf..b99378162 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -3730,7 +3730,9 @@ void opengl33_renderer::Render(TSubModel *Submodel)
case rendermode::shadows:
{
// skip if the shadow caster rank is too low for currently set threshold
- if( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
+ // or if the submodel is hidden (colour pass only fades it out, e.g. inactive seasonal variant)
+ if( ( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
+ || ( Submodel->fVisible <= 0.f ) )
{
--m_renderpass.draw_stats.submodels;
--m_renderpass.draw_stats.drawcalls;
@@ -4630,7 +4632,9 @@ void opengl33_renderer::Render_Alpha(TSubModel *Submodel)
case rendermode::shadows:
{
// skip if the shadow caster rank is too low for currently set threshold
- if( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
+ // or if the submodel is hidden (colour pass only fades it out, e.g. inactive seasonal variant)
+ if( ( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
+ || ( Submodel->fVisible <= 0.f ) )
{
--m_renderpass.draw_stats.submodels;
--m_renderpass.draw_stats.drawcalls;
diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp
index 1da66ba51..6f06e9b33 100644
--- a/rendering/openglrenderer.cpp
+++ b/rendering/openglrenderer.cpp
@@ -2863,7 +2863,9 @@ opengl_renderer::Render( TSubModel *Submodel ) {
}
case rendermode::shadows: {
// skip if the shadow caster rank is too low for currently set threshold
- if( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
+ // or if the submodel is hidden (colour pass only fades it out, e.g. inactive seasonal variant)
+ if( ( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
+ || ( Submodel->fVisible <= 0.f ) )
{
--m_renderpass.draw_stats.submodels;
--m_renderpass.draw_stats.drawcalls;
diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp
index e84af6137..9f8fd161c 100644
--- a/vehicle/DynObj.cpp
+++ b/vehicle/DynObj.cpp
@@ -800,6 +800,19 @@ TDynamicObject::set_cab_lights( int const Cab, float const Level ) {
}
}
+// aktualizujemy submodele w zaleznosci od aktualnej pory roku
+void TDynamicObject::on_season_update()
+{
+ if (sm_winter_variant != nullptr) // pokazujemy wariant zimowy
+ sm_winter_variant->SetVisibilityLevel(Global.Season == "winter:" ? 1 : 0, true, false);
+ if (sm_spring_variant != nullptr) // pokazujemy wariant wiosenny
+ sm_spring_variant->SetVisibilityLevel(Global.Season == "spring:" ? 1 : 0, true, false);
+ if (sm_summer_variant != nullptr) // pokazujemy wariant letni
+ sm_summer_variant->SetVisibilityLevel(Global.Season == "summer:" ? 1 : 0, true, false);
+ if (sm_autumn_variant != nullptr) // pokazujemy wariant jesienny
+ sm_autumn_variant->SetVisibilityLevel(Global.Season == "autumn:" ? 1 : 0, true, false);
+}
+
// ABu 29.01.05 przeklejone z render i renderalpha: *********************
void TDynamicObject::ABuLittleUpdate(double ObjSqrDist)
{ // ABu290105: pozbierane i uporzadkowane powtarzajace
@@ -814,6 +827,10 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist)
if (vFloor.z > 0.0)
mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor);
+ // model jest współdzielony przez pojazdy, a pora roku może się zmienić w trakcie symulacji
+ if (Global.UpdateMaterials)
+ on_season_update();
+
if (ObjSqrDist < 400 * 400 ) // gdy bliżej niż 400m
{
for( auto &animation : pAnimations ) {
@@ -2493,6 +2510,10 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424"
smBogie[0]->WillBeAnimated();
if (smBogie[1])
smBogie[1]->WillBeAnimated();
+ sm_winter_variant = mdModel->GetFromName("winter_variant");
+ sm_spring_variant = mdModel->GetFromName("spring_variant");
+ sm_summer_variant = mdModel->GetFromName("summer_variant");
+ sm_autumn_variant = mdModel->GetFromName("autumn_variant");
}
// ABu: zainicjowanie zmiennej, zeby nic sie nie ruszylo w pierwszej klatce,
// potem juz liczona prawidlowa wartosc masy
diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h
index c48e40e14..36335a320 100644
--- a/vehicle/DynObj.h
+++ b/vehicle/DynObj.h
@@ -310,6 +310,10 @@ private:
TSubModel *smWahacze[4]; // wahacze (np. nogi, dźwignia w drezynie)
TSubModel *smBrakeMode; // Ra 15-01: nastawa hamulca też
TSubModel *smLoadMode; // Ra 15-01: nastawa próżny/ładowny
+ TSubModel *sm_winter_variant {}; // submodel zimowego wariantu
+ TSubModel *sm_spring_variant {}; // submodel wiosennego wariantu
+ TSubModel *sm_summer_variant {}; // submodel letniego wariantu
+ TSubModel *sm_autumn_variant {}; // submodel jesiennego wariantu
double fWahaczeAmp;
// Winger 160204 - pantografy
double pantspeedfactor;
@@ -462,6 +466,7 @@ private:
void ABuLittleUpdate(double ObjSqrDist);
void ABuBogies();
void ABuModelRoll();
+ void on_season_update();
void TurnOff();
// update state of load exchange operation
void update_exchange( double const Deltatime );
From 4137f5504ae71ee0bdd4415ac9dfba593e64d335 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Mon, 28 Sep 2026 21:07:53 +0200
Subject: [PATCH 011/430] fix: sonar sast fixes - sonar.yml, nosonar, linux
chmod modification
---
.github/workflows/sonar.yml | 22 +++++++++++++++++++---
application/application.cpp | 2 +-
sonar-project.properties | 4 +++-
utilities/Globals.h | 10 ++++++++--
utilities/uart.cpp | 4 ++--
vehicle/Driver.cpp | 2 +-
vehicle/DynObj.cpp | 3 ++-
7 files changed, 36 insertions(+), 11 deletions(-)
diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml
index 8140317ea..66213c236 100644
--- a/.github/workflows/sonar.yml
+++ b/.github/workflows/sonar.yml
@@ -70,7 +70,9 @@ jobs:
pull-requests: read # verify PR head sha via the API
env:
BUILD_WRAPPER_OUT_DIR: bw-output
- SONAR_EXCLUSIONS: betterRenderer/**,ref/**,imgui/**,stb/**,build/**,bw-output/**
+ # .trusted/ holds the checkout of master used to restore the scanner config;
+ # it is not part of the analysed change.
+ SONAR_EXCLUSIONS: betterRenderer/**,ref/**,imgui/**,stb/**,build/**,bw-output/**,.trusted/**
SONAR_SCANNER_JAVA_OPTS: -Xmx5g
steps:
- name: Post pending status
@@ -102,12 +104,26 @@ jobs:
- name: Unpack analysis input
run: |
set -euo pipefail
+ # The archive holds the whole PR workspace and is unpacked over this one,
+ # .trusted/ included. Move the trusted config out of reach first, or a PR
+ # carrying its own .trusted/sonar-project.properties would have it planted
+ # here and restored below as if it came from master.
+ if [ -f "$GITHUB_WORKSPACE/.trusted/sonar-project.properties" ]; then
+ cp "$GITHUB_WORKSPACE/.trusted/sonar-project.properties" /tmp/trusted-sonar-project.properties
+ fi
+ # Nothing may be written outside the workspace: reject absolute members and
+ # any member reaching through a parent directory before unpacking anything.
+ tar -tzf /tmp/sonar-input/workspace.tar.gz > /tmp/archive-members.txt
+ if grep -qE '^/|(^|/)[.][.](/|$)' /tmp/archive-members.txt; then
+ echo "::error::archive contains paths outside the workspace"
+ exit 1
+ fi
tar -xzf /tmp/sonar-input/workspace.tar.gz -C "$GITHUB_WORKSPACE"
# Strip PR-controlled scanner configuration, restore the trusted one.
rm -f "$GITHUB_WORKSPACE/sonar-project.properties" \
"$GITHUB_WORKSPACE/.sonarcloud.properties"
- if [ -f "$GITHUB_WORKSPACE/.trusted/sonar-project.properties" ]; then
- cp "$GITHUB_WORKSPACE/.trusted/sonar-project.properties" "$GITHUB_WORKSPACE/"
+ if [ -f /tmp/trusted-sonar-project.properties ]; then
+ cp /tmp/trusted-sonar-project.properties "$GITHUB_WORKSPACE/sonar-project.properties"
fi
- name: Resolve and verify PR metadata
diff --git a/application/application.cpp b/application/application.cpp
index a6b88ae87..26af01fab 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1105,7 +1105,7 @@ void eu07_application::init_files()
#elif __unix__
unlink("log.txt");
unlink("errors.txt");
- mkdir("logs", 0755);
+ mkdir("logs", 0750);
#endif
}
namespace fs = std::filesystem;
diff --git a/sonar-project.properties b/sonar-project.properties
index 2e3fc88bd..a1e5b66c5 100644
--- a/sonar-project.properties
+++ b/sonar-project.properties
@@ -6,7 +6,9 @@ sonar.sources=.
sonar.sourceEncoding=UTF-8
# Exclusions
-sonar.exclusions=betterRenderer/**,ref/**,imgui/**,stb/**,build/**,bw-output/**
+# .trusted/ is the copy of master the analysis workflow checks out to restore its
+# own configuration; analysing it would duplicate every file of the base branch.
+sonar.exclusions=betterRenderer/**,ref/**,imgui/**,stb/**,build/**,bw-output/**,.trusted/**
# Excluding all files from coverage making the gate skip that
# instead of failing it.
diff --git a/utilities/Globals.h b/utilities/Globals.h
index c4bd26f67..d0f707017 100644
--- a/utilities/Globals.h
+++ b/utilities/Globals.h
@@ -38,8 +38,14 @@ struct global_settings {
bool shiftState{ false }; //m7todo: brzydko
bool ctrlState{ false };
bool altState{ false };
- std::mt19937 random_engine;
- std::mt19937 local_random_engine;
+ // Simulation randomness, never used for anything security related: no keys, tokens or
+ // credentials come out of these. Reproducibility is a requirement here, which is why both
+ // are plain mt19937 -- the run's seed can be written down and passed on, and it travels in
+ // server_hello so that every client in a session replays the same sequence. A generator
+ // that cannot be seeded to a known state would break both of those.
+ std::mt19937 random_engine; // NOSONAR shared run seed, kept in sync across the network
+ std::mt19937 local_random_engine; // NOSONAR re-seeded from a true random source in init_modes,
+ // drives purely local cosmetics (sound pitch, editor placement)
bool ready_to_load{ false };
std::time_t starting_timestamp = 0; // starting time, in local timezone
uint32_t random_seed = 0;
diff --git a/utilities/uart.cpp b/utilities/uart.cpp
index cac7a1986..ab5060fab 100644
--- a/utilities/uart.cpp
+++ b/utilities/uart.cpp
@@ -399,7 +399,7 @@ void uart_input::poll()
char buf[buffer.size() * 3 + 1];
size_t pos = 0;
for (uint8_t b : buffer)
- pos += sprintf(&buf[pos], "%02X ", b);
+ pos += snprintf(&buf[pos], sizeof(buf) - pos, "%02X ", b);
WriteLog("uart: rx: " + std::string(buf));
}
@@ -635,7 +635,7 @@ void uart_input::poll()
buf[ buffer.size() * 3 ] = 0;
size_t pos = 0;
for (uint8_t b : buffer)
- pos += sprintf(&buf[pos], "%02X ", b);
+ pos += snprintf(&buf[pos], sizeof(buf) - pos, "%02X ", b);
WriteLog("uart: tx: " + std::string(buf));
}
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 9a6de8596..9771f7db6 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -1901,7 +1901,7 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche,
#ifdef _WIN32
CreateDirectory( "physicslog", nullptr);
#elif __unix__
- mkdir( "physicslog", 0744 );
+ mkdir( "physicslog", 0740 );
#endif
LogFile.open( std::string( "physicslog/" + VehicleName + ".dat" ),
std::ios::in | std::ios::out | std::ios::trunc );
diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp
index e84af6137..57cc86609 100644
--- a/vehicle/DynObj.cpp
+++ b/vehicle/DynObj.cpp
@@ -3024,7 +3024,8 @@ TDynamicObject::update_load_offset() {
void
TDynamicObject::shuffle_load_order() {
- std::shuffle( std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), Global.random_engine );
+ // order of visible load chunks, nothing security related -- see the engines in Globals.h
+ std::shuffle( std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), Global.random_engine ); // NOSONAR
// shift chunks assigned to corridors to the end of the list, so they show up last
std::stable_partition(
std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ),
From 176427f96b26767b81d3da0303dc7890869e22da Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Mon, 28 Sep 2026 21:08:15 +0200
Subject: [PATCH 012/430] refactor: sonar c++20 changes (#185)
---
application/application.cpp | 7 +---
launcher/scenery_list.cpp | 2 +-
launcher/vehicle_picker.cpp | 2 +-
model/Model3d.cpp | 13 +++---
model/Texture.cpp | 6 +--
network/backend/asio.cpp | 6 ++-
network/message.h | 16 ++++----
rendering/screenshot.cpp | 8 ++--
scene/sn_utils.cpp | 20 +++++----
simulation/simulationstateserializer.cpp | 5 ++-
simulation/simulationtime.cpp | 3 +-
utilities/Globals.cpp | 20 ++-------
utilities/Logs.cpp | 3 +-
utilities/utilities.cpp | 22 ++++++++++
utilities/utilities.h | 4 ++
vehicle/Driver.cpp | 52 ++++++++++--------------
vehicle/Driver.h | 6 +--
widgets/trainingcard.cpp | 22 +++++-----
18 files changed, 111 insertions(+), 106 deletions(-)
diff --git a/application/application.cpp b/application/application.cpp
index 26af01fab..ceb5ec6c7 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -1479,11 +1479,8 @@ bool eu07_application::init_network()
// TODO: sort out this timezone mess
std::time_t utc_now = std::time(nullptr);
- tm tm_local, tm_utc;
- tm *tmp = std::localtime(&utc_now);
- memcpy(&tm_local, tmp, sizeof(tm));
- tmp = std::gmtime(&utc_now);
- memcpy(&tm_utc, tmp, sizeof(tm));
+ std::tm const tm_local = local_tm(utc_now);
+ std::tm const tm_utc = utc_tm(utc_now);
int64_t offset = tm_local.tm_hour * 3600 + tm_local.tm_min * 60 + tm_local.tm_sec - (tm_utc.tm_hour * 3600 + tm_utc.tm_min * 60 + tm_utc.tm_sec);
diff --git a/launcher/scenery_list.cpp b/launcher/scenery_list.cpp
index 0b49e80f1..77f69a350 100644
--- a/launcher/scenery_list.cpp
+++ b/launcher/scenery_list.cpp
@@ -281,7 +281,7 @@ void ui::scenerylist_panel::draw_trainset(trainset_desc &trainset)
for (auto &dyn_desc : trainset.vehicles) {
deferred_image *mini = nullptr;
- if (dyn_desc.skin && dyn_desc.skin->mini.get() != -1)
+ if (dyn_desc.skin && dyn_desc.skin->mini.get() != (GLuint)-1)
mini = &dyn_desc.skin->mini;
else
mini = &placeholder_mini;
diff --git a/launcher/vehicle_picker.cpp b/launcher/vehicle_picker.cpp
index 88c40ef9b..f7d3503fc 100644
--- a/launcher/vehicle_picker.cpp
+++ b/launcher/vehicle_picker.cpp
@@ -270,7 +270,7 @@ bool ui::vehiclepicker_panel::selectable_image(const char *desc, bool selected,
}
GLuint tex = image->get();
- if (tex != -1) {
+ if (tex != (GLuint)-1) {
glm::ivec2 size = image->size();
float width = 30.0f / size.y * size.x;
ImGui::SameLine(ImGui::GetContentRegionAvail().x - width);
diff --git a/model/Model3d.cpp b/model/Model3d.cpp
index 38f39080f..fba07446f 100644
--- a/model/Model3d.cpp
+++ b/model/Model3d.cpp
@@ -24,6 +24,8 @@ Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others
#include "world/mtable.h"
#include "scene/sn_utils.h"
+#include
+
//---------------------------------------------------------------------------
using namespace Mtable;
@@ -224,16 +226,13 @@ inline void readMatrix(cParser &parser, float4x4 &matrix)
template void UserdataParse(cParser &parser, gfx::vertex_userdata &vertex)
{
+ static_assert(sizeof(T) == sizeof(float), "userdata is stored as raw 32-bit values");
parser.getTokens(4);
- union
- {
- T InType;
- float FloatType;
- } buf{};
for (int i = 0; i < 4; ++i)
{
- parser >> buf.InType;
- vertex.data[i] = buf.FloatType;
+ T value{};
+ parser >> value;
+ vertex.data[i] = std::bit_cast(value);
}
}
diff --git a/model/Texture.cpp b/model/Texture.cpp
index a53976630..5c1d852f4 100644
--- a/model/Texture.cpp
+++ b/model/Texture.cpp
@@ -394,12 +394,12 @@ opengl_texture::make_from_memory(size_t width, size_t height, const uint8_t *raw
void opengl_texture::update_from_memory(size_t width, size_t height, const uint8_t *raw)
{
- if (id != -1 && (width != data_width || height != data_height || GL_SRGB8_ALPHA8 != data_format || GL_RGBA != data_components))
+ if (id != (GLuint)-1 && (width != data_width || height != data_height || GL_SRGB8_ALPHA8 != data_format || GL_RGBA != data_components))
{
glDeleteTextures(1, &id);
- id = -1;
+ id = (GLuint)-1;
}
- if (id == -1)
+ if (id == (GLuint)-1)
{
data_width = width;
data_height = height;
diff --git a/network/backend/asio.cpp b/network/backend/asio.cpp
index 958b084ec..c2d1364d8 100644
--- a/network/backend/asio.cpp
+++ b/network/backend/asio.cpp
@@ -12,8 +12,10 @@ network::tcp::connection::connection(asio::io_context &io_ctx, bool client, size
network::tcp::connection::~connection()
{
- m_socket.shutdown(m_socket.shutdown_both);
- m_socket.close();
+ // error_code overloads: the throwing ones would escape the destructor, e.g. when the peer is already gone
+ asio::error_code ec;
+ m_socket.shutdown(m_socket.shutdown_both, ec);
+ m_socket.close(ec);
}
void network::tcp::connection::disconnect()
diff --git a/network/message.h b/network/message.h
index 43ad13ec7..871e833f9 100644
--- a/network/message.h
+++ b/network/message.h
@@ -30,17 +30,17 @@ struct client_hello : public message
virtual void serialize(std::ostream &stream) const override;
virtual void deserialize(std::istream &stream) override;
- int32_t version;
- uint32_t start_packet;
+ int32_t version{};
+ uint32_t start_packet{};
};
struct server_hello : public message
{
server_hello() : message(SERVER_HELLO) {}
- uint32_t seed;
- int64_t timestamp;
- int64_t config;
+ uint32_t seed{};
+ int64_t timestamp{};
+ int64_t config{};
std::string scenario;
virtual void serialize(std::ostream &stream) const override;
@@ -62,9 +62,9 @@ struct frame_info : public request_command
{
frame_info() : request_command(FRAME_INFO) {}
- double render_dt;
- double dt;
- double sync;
+ double render_dt{};
+ double dt{};
+ double sync{};
virtual void serialize(std::ostream &stream) const override;
virtual void deserialize(std::istream &stream) override;
diff --git a/rendering/screenshot.cpp b/rendering/screenshot.cpp
index 285679b7e..eb7e7aac0 100644
--- a/rendering/screenshot.cpp
+++ b/rendering/screenshot.cpp
@@ -2,6 +2,7 @@
#include "rendering/screenshot.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
+#include "utilities/utilities.h"
#include
void screenshot_manager::screenshot_save_thread( char *img, int w, int h )
@@ -29,11 +30,8 @@ void screenshot_manager::screenshot_save_thread( char *img, int w, int h )
}
char datetime[64];
- time_t timer;
- struct tm* tm_info;
- time(&timer);
- tm_info = localtime(&timer);
- strftime(datetime, 64, "%Y-%m-%d_%H-%M-%S", tm_info);
+ std::tm const tm_info = local_tm(std::time(nullptr));
+ strftime(datetime, 64, "%Y-%m-%d_%H-%M-%S", &tm_info);
uint64_t perf;
#ifdef _WIN32
diff --git a/scene/sn_utils.cpp b/scene/sn_utils.cpp
index 71e6549c8..08825d91c 100644
--- a/scene/sn_utils.cpp
+++ b/scene/sn_utils.cpp
@@ -5,6 +5,8 @@
#include "stdafx.h"
#include "scene/sn_utils.h"
+#include
+
// sanity checks
static_assert(std::numeric_limits::is_iec559, "IEEE754 required");
static_assert(sizeof(float) == 4, "Float must be 4 bytes");
@@ -17,7 +19,7 @@ uint16_t sn_utils::ld_uint16(std::istream &s)
uint8_t buf[2];
s.read((char*)buf, 2);
uint16_t v = buf[1] << 8 | buf[0];
- return reinterpret_cast(v);
+ return v;
}
// deserialize little endian uint32
@@ -26,7 +28,7 @@ uint32_t sn_utils::ld_uint32(std::istream &s)
uint8_t buf[4];
s.read((char*)buf, 4);
uint32_t v = buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0];
- return reinterpret_cast(v);
+ return v;
}
// deserialize little endian int32
@@ -35,7 +37,7 @@ int32_t sn_utils::ld_int32(std::istream &s)
uint8_t buf[4];
s.read((char*)buf, 4);
uint32_t v = buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0];
- return reinterpret_cast(v);
+ return static_cast(v);
}
// deserialize little endian uint64
@@ -47,7 +49,7 @@ uint64_t sn_utils::ld_uint64(std::istream &s)
(uint64_t)buf[5] << 40 | (uint64_t)buf[4] << 32 |
(uint64_t)buf[3] << 24 | (uint64_t)buf[2] << 16 |
(uint64_t)buf[1] << 8 | (uint64_t)buf[0];
- return reinterpret_cast(v);
+ return v;
}
// deserialize little endian int64
@@ -59,7 +61,7 @@ int64_t sn_utils::ld_int64(std::istream &s)
(uint64_t)buf[5] << 40 | (uint64_t)buf[4] << 32 |
(uint64_t)buf[3] << 24 | (uint64_t)buf[2] << 16 |
(uint64_t)buf[1] << 8 | (uint64_t)buf[0];
- return reinterpret_cast(v);
+ return static_cast(v);
}
// deserialize little endian ieee754 float32
@@ -68,7 +70,7 @@ float sn_utils::ld_float32(std::istream &s)
uint8_t buf[4];
s.read((char*)buf, 4);
uint32_t v = buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0];
- return reinterpret_cast(v);
+ return std::bit_cast(v);
}
// deserialize little endian ieee754 float64
@@ -80,7 +82,7 @@ double sn_utils::ld_float64(std::istream &s)
(uint64_t)buf[5] << 40 | (uint64_t)buf[4] << 32 |
(uint64_t)buf[3] << 24 | (uint64_t)buf[2] << 16 |
(uint64_t)buf[1] << 8 | (uint64_t)buf[0];
- return reinterpret_cast(v);
+ return std::bit_cast(v);
}
// deserialize null-terminated string
@@ -195,7 +197,7 @@ void sn_utils::ls_int64(std::ostream &s, int64_t v)
void sn_utils::ls_float32(std::ostream &s, float t)
{
- uint32_t v = reinterpret_cast(t);
+ uint32_t v = std::bit_cast(t);
uint8_t buf[4];
buf[0] = v;
buf[1] = v >> 8;
@@ -206,7 +208,7 @@ void sn_utils::ls_float32(std::ostream &s, float t)
void sn_utils::ls_float64(std::ostream &s, double t)
{
- uint64_t v = reinterpret_cast(t);
+ uint64_t v = std::bit_cast(t);
uint8_t buf[8];
buf[0] = v;
buf[1] = v >> 8;
diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp
index ef7cd7dbd..99a733d36 100644
--- a/simulation/simulationstateserializer.cpp
+++ b/simulation/simulationstateserializer.cpp
@@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/.
#include "application/application.h"
#include "rendering/renderer.h"
#include "utilities/Logs.h"
+#include "utilities/utilities.h"
#include "editor/editorTerrainStreamer.hpp"
namespace simulation {
@@ -393,8 +394,8 @@ void state_serializer::init_time() {
auto &time = simulation::Time.data();
if( true == Global.ScenarioTimeCurrent ) {
// calculate time shift required to match scenario time with local clock
- auto const *localtime = std::gmtime( &Global.starting_timestamp );
- Global.ScenarioTimeOffset = ( localtime->tm_hour * 60 + localtime->tm_min - ( time.wHour * 60 + time.wMinute ) ) / 60.f;
+ auto const localtime = utc_tm( Global.starting_timestamp );
+ Global.ScenarioTimeOffset = ( localtime.tm_hour * 60 + localtime.tm_min - ( time.wHour * 60 + time.wMinute ) ) / 60.f;
}
else if( false == std::isnan( Global.ScenarioTimeOverride ) ) {
// scenario time override takes precedence over scenario time offset
diff --git a/simulation/simulationtime.cpp b/simulation/simulationtime.cpp
index 528867099..f1683c534 100644
--- a/simulation/simulationtime.cpp
+++ b/simulation/simulationtime.cpp
@@ -32,7 +32,8 @@ scenario_time::init(std::time_t timestamp) {
auto const requestedminute { requestedtime % 60 };
// cache requested elements, if any
- std::tm *tms = std::gmtime(×tamp);
+ std::tm const tm = utc_tm(timestamp);
+ std::tm const *tms = &tm;
m_time.wYear = tms->tm_year + 1900;
m_time.wMonth = tms->tm_mon + 1;
m_time.wDayOfWeek = tms->tm_wday;
diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp
index f45b6b3eb..47b04d18b 100644
--- a/utilities/Globals.cpp
+++ b/utilities/Globals.cpp
@@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulationenvironment.h"
#include "vehicle/Driver.h"
#include "utilities/Logs.h"
+#include "utilities/utilities.h"
#include "Console.h"
#include "scripting/PyInt.h"
#include "utilities/Timer.h"
@@ -26,15 +27,7 @@ http://mozilla.org/MPL/2.0/.
void global_settings::LoadIniFile(std::string asFileName)
{
// initialize season data in case the main config file doesn't
- std::time_t timenow = std::time(nullptr);
-
- std::tm tm{};
-
-#ifdef _WIN32
- localtime_s(&tm, &timenow);
-#else
- localtime_r(&timenow, &tm);
-#endif
+ std::tm const tm = local_tm(std::time(nullptr));
fMoveLight = tm.tm_yday + 1; // numer bieżącego dnia w roku
simulation::Environment.compute_season(fMoveLight);
@@ -513,14 +506,7 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string&
if (fMoveLight == 0.f)
{
- std::time_t timenow = std::time(nullptr);
- std::tm tm{};
-
-#ifdef _WIN32
- localtime_s(&tm, &timenow);
-#else
- localtime_r(&timenow, &tm);
-#endif
+ std::tm const tm = local_tm(std::time(nullptr));
fMoveLight = tm.tm_yday + 1;
}
diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp
index 554a77b9e..737d25d74 100644
--- a/utilities/Logs.cpp
+++ b/utilities/Logs.cpp
@@ -31,7 +31,8 @@ std::string filename_date() {
#ifdef __unix__
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
- tm *tms = localtime(&ts.tv_sec);
+ std::tm const tm = local_tm(ts.tv_sec);
+ std::tm const *tms = &tm;
st.wYear = tms->tm_year;
st.wMonth = tms->tm_mon;
st.wDayOfWeek = tms->tm_wday;
diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp
index 14e448973..efaf3e6ce 100644
--- a/utilities/utilities.cpp
+++ b/utilities/utilities.cpp
@@ -426,6 +426,28 @@ std::time_t last_modified(std::string const &Filename)
return 0;
}
+std::tm local_tm(std::time_t Time)
+{
+ std::tm tm{};
+#ifdef _WIN32
+ localtime_s(&tm, &Time);
+#else
+ localtime_r(&Time, &tm);
+#endif
+ return tm;
+}
+
+std::tm utc_tm(std::time_t Time)
+{
+ std::tm tm{};
+#ifdef _WIN32
+ gmtime_s(&tm, &Time);
+#else
+ gmtime_r(&Time, &tm);
+#endif
+ return tm;
+}
+
// potentially erases file extension from provided file name. returns: true if extension was removed, false otherwise
bool erase_extension(std::string &Filename)
{
diff --git a/utilities/utilities.h b/utilities/utilities.h
index 91d74e67a..6e761380a 100644
--- a/utilities/utilities.h
+++ b/utilities/utilities.h
@@ -220,6 +220,10 @@ std::pair FileExists(std::vector const &N
// returns time of last modification for specified file
std::time_t last_modified(std::string const &Filename);
+// thread-safe replacements for std::localtime and std::gmtime, which hand out a pointer to shared static storage
+std::tm local_tm(std::time_t Time);
+std::tm utc_tm(std::time_t Time);
+
// potentially erases file extension from provided file name. returns: true if extension was removed, false otherwise
bool erase_extension(std::string &Filename);
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 9771f7db6..9dfd6731b 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -449,8 +449,8 @@ void TController::TableClear()
iTableDirection = 0; // nieznany
tLast = nullptr;
fLastVel = -1.0;
- SemNextIndex = -1;
- SemNextStopIndex = -1;
+ SemNextIndex = npos;
+ SemNextStopIndex = npos;
eSignSkip = nullptr; // nic nie pomijamy
};
@@ -512,8 +512,8 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle)
sSpeedTable.clear();
iLast = -1;
tLast = nullptr; //żaden nie sprawdzony
- SemNextIndex = -1;
- SemNextStopIndex = -1;
+ SemNextIndex = npos;
+ SemNextStopIndex = npos;
*/
if( VelSignalLast == 0.0 ) {
// don't allow potential red light overrun keep us from reversing
@@ -541,16 +541,16 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle)
else {
if( iTableDirection == 0 ) { return; }
// NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table
- if( SemNextIndex != -1
+ if( SemNextIndex != npos
&& SemNextIndex >= sSpeedTable.size() ) {
- SemNextIndex = -1;
+ SemNextIndex = npos;
}
- if( SemNextStopIndex != -1
+ if( SemNextStopIndex != npos
&& SemNextStopIndex >= sSpeedTable.size() ) {
- SemNextStopIndex = -1;
+ SemNextStopIndex = npos;
}
// kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor)
- if( SemNextStopIndex != -1
+ if( SemNextStopIndex != npos
&& sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) {
// znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor
// jeśli jest następny semafor to sprawdzamy czy to on nadał zero
@@ -614,23 +614,23 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle)
fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować
SemNextStopIndex = iLast;
- if (SemNextIndex == -1) {
+ if (SemNextIndex == npos) {
SemNextIndex = iLast;
}
if (Global.iWriteLogEnabled & 8) {
WriteLog("(stop signal from "
- + (SemNextStopIndex != -1 ? sSpeedTable[SemNextStopIndex].GetName() : "unknown semaphor")
+ + (SemNextStopIndex != npos ? sSpeedTable[SemNextStopIndex].GetName() : "unknown semaphor")
+ ")");
}
}
else {
if( true == newspeedpoint.IsProperSemaphor(OrderCurrentGet())
- && SemNextIndex == -1 ) {
+ && SemNextIndex == npos ) {
SemNextIndex = iLast; // sprawdzamy czy pierwszy na drodze
}
if (Global.iWriteLogEnabled & 8) {
WriteLog("(forward signal for "
- + (SemNextIndex != -1 ? sSpeedTable[SemNextIndex].GetName() : "unknown semaphor")
+ + (SemNextIndex != npos ? sSpeedTable[SemNextIndex].GetName() : "unknown semaphor")
+ ")");
}
}
@@ -800,13 +800,13 @@ void TController::TableCheck(double fDistance)
--iLast;
}
// a semaphor recorded beyond the switch went away with the discarded entries
- if( SemNextIndex != -1
+ if( SemNextIndex != npos
&& SemNextIndex >= sSpeedTable.size() ) {
- SemNextIndex = -1;
+ SemNextIndex = npos;
}
- if( SemNextStopIndex != -1
+ if( SemNextStopIndex != npos
&& SemNextStopIndex >= sSpeedTable.size() ) {
- SemNextStopIndex = -1;
+ SemNextStopIndex = npos;
}
tLast = sSpeedTable[ i ].trTrack;
TableTraceRoute( fDistance, pVehicles[ end::rear ] );
@@ -1387,13 +1387,13 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextIndex ].GetName() );
}
- SemNextIndex = -1; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód
+ SemNextIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód
}
if( SemNextStopIndex == Pointindex ) {
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextStopIndex ].GetName() );
}
- SemNextStopIndex = -1; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód
+ SemNextStopIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód
}
switch( Point.evEvent->input_command() ) {
// TBD, TODO: expand emergency_brake handling to a more generic security system signal
@@ -1461,13 +1461,13 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo
}
// jeśli jest mienięty poprzedni semafor a wcześniej
// byl nowy to go dorzucamy do zmiennej, żeby cały czas widział najbliższy
- if( SemNextIndex == -1 ) {
+ if( SemNextIndex == npos ) {
SemNextIndex = Pointindex;
if( Global.iWriteLogEnabled & 8 ) {
WriteLog( "Speed table update for " + OwnerName() + ", next semaphor is " + sSpeedTable[ SemNextIndex ].GetName() );
}
}
- if( SemNextStopIndex == -1
+ if( SemNextStopIndex == npos
|| ( sSpeedTable[SemNextStopIndex].fVelNext != 0
&& Point.fVelNext == 0 ) ) {
SemNextStopIndex = Pointindex;
@@ -1926,17 +1926,9 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche,
fActionTime = -5.0;
};
-void TController::CloseLog()
-{
- if (WriteLogFlag)
- {
- LogFile.close();
- }
-};
-
TController::~TController()
{ // wykopanie mechanika z roboty
- CloseLog();
+ // LogFile is closed by its own destructor
};
// zamiana kodu rozkazu na opis
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index e7c4fac00..b76dbf086 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -542,8 +542,9 @@ private:
double fLastVel = 0.0; // prędkość na poprzednio sprawdzonym torze
TTrack *tLast = nullptr; // ostatni analizowany tor
basic_event *eSignSkip = nullptr; // można pominąć ten SBL po zatrzymaniu
- std::size_t SemNextIndex{ std::size_t( -1 ) };
- std::size_t SemNextStopIndex{ std::size_t( -1 ) };
+ static constexpr std::size_t npos{ std::size_t( -1 ) };
+ std::size_t SemNextIndex{ npos };
+ std::size_t SemNextStopIndex{ npos };
double dMoveLen = 0.0; // odległość przejechana od ostatniego sprawdzenia tabelki
basic_event *eSignNext = nullptr; // sygnał zmieniający prędkość, do pokazania na [F2]
neighbour_data Obstacle; // nearest vehicle detected ahead on current route
@@ -622,7 +623,6 @@ private:
// logs
// methods
void PhysicsLog();
- void CloseLog();
// members
std::ofstream LogFile; // zapis parametrow fizycznych
double LastUpdatedTime = 0.0; // czas od ostatniego logu
diff --git a/widgets/trainingcard.cpp b/widgets/trainingcard.cpp
index d4d11e5b3..27fb0965d 100644
--- a/widgets/trainingcard.cpp
+++ b/widgets/trainingcard.cpp
@@ -1,6 +1,7 @@
#include "stdafx.h"
#include "widgets/trainingcard.h"
#include "simulation/simulation.h"
+#include "utilities/utilities.h"
#ifdef __linux__
#include
@@ -46,12 +47,11 @@ void trainingcard_panel::clear()
void trainingcard_panel::save_thread_func()
{
- std::tm *tm = std::localtime(&(*start_time_wall));
- std::string date = std::to_string(tm->tm_year + 1900) + "-" + std::to_string(tm->tm_mon + 1) + "-" + std::to_string(tm->tm_mday);
- std::string from = std::to_string(tm->tm_hour) + ":" + std::to_string(tm->tm_min);
- std::time_t now = std::time(nullptr);
- tm = std::localtime(&now);
- std::string to = std::to_string(tm->tm_hour) + ":" + std::to_string(tm->tm_min);
+ std::tm tm = local_tm(*start_time_wall);
+ std::string date = std::to_string(tm.tm_year + 1900) + "-" + std::to_string(tm.tm_mon + 1) + "-" + std::to_string(tm.tm_mday);
+ std::string from = std::to_string(tm.tm_hour) + ":" + std::to_string(tm.tm_min);
+ tm = local_tm(std::time(nullptr));
+ std::string to = std::to_string(tm.tm_hour) + ":" + std::to_string(tm.tm_min);
std::fstream temp("reports/" + recording_timestamp + ".html", std::ios_base::out | std::ios_base::binary);
std::fstream input("report_template.html", std::ios_base::in | std::ios_base::binary);
@@ -121,9 +121,9 @@ void trainingcard_panel::render_contents()
if (start_time_wall)
{
- std::tm *tm = std::localtime(&(*start_time_wall));
- std::string rep = "Czas rozpoczęcia: " + std::to_string(tm->tm_year + 1900) + "-" + std::to_string(tm->tm_mon + 1) + "-" + std::to_string(tm->tm_mday) + " " + std::to_string(tm->tm_hour) +
- ":" + std::to_string(tm->tm_min);
+ std::tm const tm = local_tm(*start_time_wall);
+ std::string rep = "Czas rozpoczęcia: " + std::to_string(tm.tm_year + 1900) + "-" + std::to_string(tm.tm_mon + 1) + "-" + std::to_string(tm.tm_mday) + " " + std::to_string(tm.tm_hour) +
+ ":" + std::to_string(tm.tm_min);
ImGui::TextUnformatted(rep.c_str());
}
@@ -159,8 +159,8 @@ void trainingcard_panel::render_contents()
if (ImGui::Button("Rozpocznij szkolenie"))
{
start_time_wall = std::time(nullptr);
- std::tm *tm = std::localtime(&(*start_time_wall));
- recording_timestamp = std::to_string(tm->tm_year + 1900) + std::to_string(tm->tm_mon + 1) + std::to_string(tm->tm_mday) + std::to_string(tm->tm_hour) + std::to_string(tm->tm_min) + "_" +
+ std::tm const tm = local_tm(*start_time_wall);
+ recording_timestamp = std::to_string(tm.tm_year + 1900) + std::to_string(tm.tm_mon + 1) + std::to_string(tm.tm_mday) + std::to_string(tm.tm_hour) + std::to_string(tm.tm_min) + "_" +
std::string(trainee_name.c_str()) + "_" + std::string(instructor_name.c_str());
int ret = StartRecording();
From f2f152e5d35a896c5cd43046579e5d23038ea3b3 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Mon, 28 Sep 2026 20:53:58 +0200
Subject: [PATCH 013/430] AI: don't cut the power for a brake already released
below 0.4 bar
When the AI takes power after a brake release, determine_consist_state()
marks the consist not Ready if any vehicle's distributor reports the lap
or application state (b_hld | b_on), whatever the speed, and the sanity
check in control_handles() then puts the master controller back to zero.
A distributor stays in the lap position until the brake pipe has fully
recharged, so a few seconds after a release, with 0.2-0.3 bar left in a
cylinder, one wagon of a train is enough to throw an EU07 or EP09 that
has just reached the 2nd-5th position back to zero; it starts again
moments later.
The check in motion was meant to be lenient (brake force over 10 kN),
but the distributor state was applied at any speed. In motion it now
counts only when the cylinder holds more than 0.4 bar, the UIC figure
already used a few lines below for a released brake. At a stand the
check is unchanged.
Measured in real time against master, two runs of each scenery (a 20 per
mille descent, flat and a 10 per mille climb with 32 consists each, and a
descent with 15 freight trains of other wagon types), with a 20 km/h
restriction one coach long: throttle-downs to zero in motion caused by
readiness drop from 13 to 1, 7 to 2, 0 to 0 and 13 to 6. Each of those
left has a wagon over 0.4 bar that is applying or lapped, or one still
releasing with more than 10 kN at walking pace. No coupler broke; signal
overruns, speeds in the restriction and rolling back on the climb
are the same as on master within run-to-run spread.
---
vehicle/Driver.cpp | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 9a6de8596..7e92c7c9e 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -5983,9 +5983,12 @@ TController::determine_consist_state() {
auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) };
if (Ready) {
// bo jak coś nie odhamowane, to dalej nie ma co sprawdzać
- if( TestFlagAny(vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on)
- || ( vehicle->Vel < 1.0 ? bp > 0.4 : // ensure the brakes are sufficiently released when starting to move
- vehicle->Fb * 0.001 > 10.0 ) ) { // once in motion we can make a more lenient check
+ auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) };
+ if( vehicle->Vel < 1.0 ?
+ isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move
+ // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor
+ // is still in the lap position while the brake pipe recharges
+ ( isbraking && bp > 0.4 ) || vehicle->Fb * 0.001 > 10.0 ) {
Ready = false;
}
// Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka...
From 4f2dfd93186f218f20c499ef20572b9fa5b30b83 Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Tue, 29 Sep 2026 09:47:51 +0200
Subject: [PATCH 014/430] Drop redundant comparisons with true/false
In the conditions this PR adds; no change in behaviour.
---
McZapkie/Oerlikon_ESt.cpp | 2 +-
vehicle/Driver.cpp | 6 +++---
vehicle/Driver.h | 2 +-
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp
index d8d5b3da8..8705000a4 100644
--- a/McZapkie/Oerlikon_ESt.cpp
+++ b/McZapkie/Oerlikon_ESt.cpp
@@ -327,7 +327,7 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c
double TNESt3::GetRapidRatio(double const Vel) const
{
// ESt3 has no rapid relay, and with disc brakes the rapid step stays engaged at all speeds
- if( ( PrzekRapid == nullptr ) || ( true == RapidStaly ) ) {
+ if( ( PrzekRapid == nullptr ) || RapidStaly ) {
return 1.0;
}
// a braking vehicle comes from above, so the step is still engaged down to the speed
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 09b607b69..d75500dbe 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -6672,7 +6672,7 @@ TController::determine_proximity_ranges() {
// na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody
// jeśli pociąg
if( is_train() ) {
- if( true == IsAtPassengerStop ) {
+ if( IsAtPassengerStop ) {
// a stop point keeps the margins its W4 parameters (head or middle of the consist,
// platform length) were set up against
fMinProximityDist = std::clamp( 5 + iVehicles, 10, 15 );
@@ -7342,7 +7342,7 @@ TController::pick_optimal_speed( double const Range ) {
is_car() ? -2.0 : -0.9,
is_car() ? 2.0 : 0.9 );
- if( ( true == is_train() )
+ if( is_train()
&& ( ( OrderCurrentGet() & Obey_train ) != 0 )
&& ( VelNext == 0.0 )
&& ( ActualProximityDist <= fMaxProximityDist )
@@ -7872,7 +7872,7 @@ TController::adjust_desired_speed_for_current_speed() {
-0.05 + fAccThreshold,
std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
// HACK: for cargo trains with high braking threshold ensure we cross that threshold
- if( true == IsCargoTrain
+ if( IsCargoTrain
&& fBrake_a0[0] > 0.2
&& speedestimate > holdlimit ) {
AccDesired -= std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 );
diff --git a/vehicle/Driver.h b/vehicle/Driver.h
index 0e65a4b94..fefa950ca 100644
--- a/vehicle/Driver.h
+++ b/vehicle/Driver.h
@@ -356,7 +356,7 @@ private:
// how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal,
// otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before
double stopping_margin() const {
- return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && ( false == IsAtPassengerStop ) ?
+ return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && !IsAtPassengerStop ?
fMinProximityDist + 3.5 :
0.5 * fMinProximityDist; }
void apply_independent_brake_only();
From 96be688d1374d33234869625394bbc039d78364b Mon Sep 17 00:00:00 2001
From: pwarszawski
Date: Wed, 30 Sep 2026 14:51:36 +0200
Subject: [PATCH 015/430] Send the reverser position, not the absolute
direction, when activating a cab
CabActivisation() passed DirAbsolute (DirActive * CabActive) as the value of the
"Direction" command, which every receiving vehicle stores as its own DirActive.
Every other sender passes DirActive. With the cab at the rear end (CabActive = -1)
the two have opposite signs, so the other units got their reverser flipped
against the controlling one.
It shows whenever a rear cab is activated after the reverser has been set:
- the AI takes over an occupied cab (TakeControl() calls CabActivisation(true)),
e.g. an EN57 inserted with reardriver and a starting velocity: the motor car
drives the train backwards;
- a vehicle without automatic cab activation (SA134) driven by the AI from the
start: the cab is activated by a driver hint after the reverser is set, and
the two units pull against each other.
Fixes #169.
---
McZapkie/Mover.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 83c918e24..68b889188 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -2901,7 +2901,7 @@ bool TMoverParameters::CabActivisation(bool const Enforce)
CabMaster = true;
SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection
SendCtrlToNext("CabActivisation", 1, CabActive);
- SendCtrlToNext("Direction", DirAbsolute, CabActive);
+ SendCtrlToNext("Direction", DirActive, CabActive);
if (InactiveCabFlag & activation::springbrakeoff)
{
SpringBrakeActivate(false);
From 39dd1c057f8f3293a82a0fb28bd9621cd8650b41 Mon Sep 17 00:00:00 2001
From: Hirek193
Date: Thu, 1 Oct 2026 01:17:21 +0200
Subject: [PATCH 016/430] fix(editor): stuck brush after clicks on UI; add
polygon area fill
---
application/editormode.cpp | 619 +++++++++++++++++++++++++++++++--
application/editormode.h | 26 +-
application/editoruilayer.cpp | 10 +
application/editoruilayer.h | 2 +
application/editoruipanels.cpp | 43 ++-
application/editoruipanels.h | 7 +-
6 files changed, 674 insertions(+), 33 deletions(-)
diff --git a/application/editormode.cpp b/application/editormode.cpp
index 46a8edadf..94b1424da 100644
--- a/application/editormode.cpp
+++ b/application/editormode.cpp
@@ -24,6 +24,8 @@ http://mozilla.org/MPL/2.0/.
#include "model/Model3d.h"
#include "utilities/Float3d.h"
#include "scene/scene.h"
+#include "utilities/parser.h"
+#include "utilities/utilities.h"
#include "imgui/imgui.h"
@@ -58,6 +60,14 @@ namespace
return state == GLFW_PRESS;
}
+ // true when the most recent left button press landed in the viewport rather than on an ImGui window.
+ // valid once ImGui has processed the press (i.e. from mode update onwards), so it's also used to
+ // discard deferred pick callbacks of a press that leaked past the application's UI filter
+ inline bool viewport_click()
+ {
+ return false == ImGui::GetIO().MouseDownOwned[0];
+ }
+
// tests whether the vertical line through (Px,Pz) passes over triangle abc; if so returns the
// surface height at that point through OutY. used by the "snap to ground" (END) feature.
inline bool triangle_height_at(glm::dvec3 const &a, glm::dvec3 const &b, glm::dvec3 const &c,
@@ -117,6 +127,158 @@ namespace
}
}
+ // world transform of a model instance, matching the renderer: translate * rotateY * rotateX * rotateZ * scale
+ glm::dmat4 instance_matrix(TAnimModel const &Model)
+ {
+ glm::dmat4 rootm(1.0);
+ rootm = glm::translate(rootm, Model.location());
+ glm::vec3 const angles = Model.Angles();
+ if (angles.y != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.y)), glm::dvec3(0.0, 1.0, 0.0));
+ if (angles.x != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.x)), glm::dvec3(1.0, 0.0, 0.0));
+ if (angles.z != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.z)), glm::dvec3(0.0, 0.0, 1.0));
+ return glm::scale(rootm, glm::dvec3(Model.Scale()));
+ }
+
+ // even-odd test of a point against a polygon outline projected onto the XZ plane
+ bool point_in_polygon_xz(std::vector const &Polygon, double const X, double const Z)
+ {
+ bool inside = false;
+ for (std::size_t i = 0, j = Polygon.size() - 1; i < Polygon.size(); j = i++)
+ {
+ auto const &a = Polygon[i];
+ auto const &b = Polygon[j];
+ if ((a.z > Z) != (b.z > Z) && X < (b.x - a.x) * (Z - a.z) / (b.z - a.z) + a.x)
+ inside = !inside;
+ }
+ return inside;
+ }
+
+ // area of a polygon outline projected onto the XZ plane (shoelace formula)
+ double polygon_area_xz(std::vector const &Polygon)
+ {
+ if (Polygon.size() < 3)
+ return 0.0;
+ double sum = 0.0;
+ for (std::size_t i = 0, j = Polygon.size() - 1; i < Polygon.size(); j = i++)
+ sum += Polygon[j].x * Polygon[i].z - Polygon[i].x * Polygon[j].z;
+ return std::abs(sum) * 0.5;
+ }
+
+ // short readable name of a node template (model file and texture), like the node bank shows it
+ std::string template_label(std::string const &Template)
+ {
+ cParser tokenizer(Template);
+ tokenizer.getTokens(9, false); // node, ranges, name, type, position, rotation
+ auto model{tokenizer.getToken(false)};
+ auto texture{tokenizer.getToken(false)};
+ replace_slashes(model);
+ erase_extension(model);
+ replace_slashes(texture);
+ return texture == "none" || texture.empty() ? model : model + " (" + texture + ")";
+ }
+
+ // world triangles bucketed on a uniform XZ grid, for many ground height queries over one area
+ class triangle_grid
+ {
+ public:
+ triangle_grid(std::vector Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max) : m_triangles(std::move(Triangles)), m_min(Min)
+ {
+ glm::dvec2 const extent = glm::max(Max - Min, glm::dvec2(1.0));
+ // ~8 m cells, coarser for big areas so large terrain triangles don't flood the grid
+ m_cellsize = std::max(8.0, std::max(extent.x, extent.y) / 128.0);
+ m_columns = static_cast(std::ceil(extent.x / m_cellsize)) + 1;
+ m_rows = static_cast(std::ceil(extent.y / m_cellsize)) + 1;
+ m_cells.resize(static_cast(m_columns) * m_rows);
+
+ for (std::uint32_t idx = 0; idx < m_triangles.size(); ++idx)
+ {
+ auto const &t = m_triangles[idx];
+ int const c0 = column(std::min({t[0].x, t[1].x, t[2].x}));
+ int const c1 = column(std::max({t[0].x, t[1].x, t[2].x}));
+ int const r0 = row(std::min({t[0].z, t[1].z, t[2].z}));
+ int const r1 = row(std::max({t[0].z, t[1].z, t[2].z}));
+ for (int r = r0; r <= r1; ++r)
+ for (int c = c0; c <= c1; ++c)
+ m_cells[static_cast(r) * m_columns + c].push_back(idx);
+ }
+ }
+
+ // highest surface at (X,Z) that isn't above Ceiling. returns: true if there is one
+ bool height_at(double const X, double const Z, double const Ceiling, double &OutY) const
+ {
+ bool found = false;
+ for (auto const idx : m_cells[static_cast(row(Z)) * m_columns + column(X)])
+ {
+ auto const &t = m_triangles[idx];
+ double y;
+ if (triangle_height_at(t[0], t[1], t[2], X, Z, y) && y <= Ceiling && (!found || y > OutY))
+ {
+ OutY = y;
+ found = true;
+ }
+ }
+ return found;
+ }
+
+ private:
+ int column(double const X) const
+ {
+ return std::clamp(static_cast(std::floor((X - m_min.x) / m_cellsize)), 0, m_columns - 1);
+ }
+ int row(double const Z) const
+ {
+ return std::clamp(static_cast(std::floor((Z - m_min.y) / m_cellsize)), 0, m_rows - 1);
+ }
+
+ std::vector m_triangles;
+ std::vector> m_cells;
+ glm::dvec2 m_min;
+ double m_cellsize{8.0};
+ int m_columns{1};
+ int m_rows{1};
+ };
+
+ // appends triangles of a shape node which overlap specified XZ rectangle
+ void gather_shape_triangles(scene::shape_node const &Shape, glm::dvec2 const &Min, glm::dvec2 const &Max, std::vector &Out)
+ {
+ auto const &data = Shape.data();
+ if (data.area.radius >= 0.0f)
+ {
+ double const r = data.area.radius;
+ if (data.area.center.x + r < Min.x || data.area.center.x - r > Max.x || data.area.center.z + r < Min.y || data.area.center.z - r > Max.y)
+ return;
+ }
+
+ auto const add = [&](glm::dvec3 const &a, glm::dvec3 const &b, glm::dvec3 const &c) {
+ if (std::max({a.x, b.x, c.x}) < Min.x || std::min({a.x, b.x, c.x}) > Max.x || std::max({a.z, b.z, c.z}) < Min.y || std::min({a.z, b.z, c.z}) > Max.y)
+ return;
+ Out.push_back({a, b, c});
+ };
+
+ if (false == data.vertices.empty())
+ {
+ for (std::size_t i = 0; i + 2 < data.vertices.size(); i += 3)
+ add(data.vertices[i].position, data.vertices[i + 1].position, data.vertices[i + 2].position);
+ return;
+ }
+ // once the shape is uploaded its world-space source is released; the renderer keeps an origin-relative copy
+ if (data.geometry.bank == 0 && data.geometry.chunk == 0)
+ return;
+ auto const &verts = GfxRenderer->Vertices(data.geometry);
+ auto const &indices = GfxRenderer->Indices(data.geometry);
+ auto const to_world = [&](gfx::basic_vertex const &v) { return data.origin + glm::dvec3(v.position); };
+ if (false == indices.empty())
+ {
+ for (std::size_t i = 0; i + 2 < indices.size(); i += 3)
+ add(to_world(verts[indices[i]]), to_world(verts[indices[i + 1]]), to_world(verts[indices[i + 2]]));
+ }
+ else
+ {
+ for (std::size_t i = 0; i + 2 < verts.size(); i += 3)
+ add(to_world(verts[i]), to_world(verts[i + 1]), to_world(verts[i + 2]));
+ }
+ }
+
}
bool editor_mode::editormode_input::init()
@@ -306,32 +468,38 @@ void editor_mode::handle_brush_mouse_hold(int Action, int Button)
GfxRenderer->Pick_Node_Callback(
[this, mode, rotation_mode, fixed_rotation_value, Action, Button](scene::basic_node * /*node*/) {
+ // picks are resolved a few frames later; drop the ones queued before the button went up,
+ // or for a press that turned out to belong to the UI
+ if (!mouseHold || !viewport_click())
+ return;
+
const std::string *src = ui()->get_active_node_template();
if (!src)
return;
std::string name = "editor_";
- glm::dvec3 newPos = clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position());
- double distance = glm::distance(newPos, oldPos);
- if (distance < ui()->getSpacing())
+ // spacing is measured in world space: the mouse offset is camera-relative and the camera may move mid-stroke
+ glm::dvec3 const newPos = Camera.Pos + clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position());
+ if (m_brush_has_last && glm::distance(newPos, oldPos) < ui()->getSpacing())
return;
- TAnimModel *cloned = simulation::State.create_model(*src, name, Camera.Pos + newPos);
+ TAnimModel *cloned = simulation::State.create_model(*src, name, newPos);
oldPos = newPos;
+ m_brush_has_last = true;
if (!cloned)
return;
std::string new_name = "editor_" + cloned->uuid.to_string();
cloned->m_name = new_name;
-
+ apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value);
+
std::string as_text;
cloned->export_as_text(as_text);
push_snapshot(cloned, EditorSnapshot::Action::Add, as_text);
m_node = cloned;
- apply_rotation_for_new_node(m_node, rotation_mode, fixed_rotation_value);
ui()->set_node(m_node);
});
}
@@ -439,6 +607,9 @@ void editor_mode::nullify_history_pointers(scene::basic_node *node)
if (s.node_ptr == node)
s.node_ptr = nullptr;
}
+
+ // deleted nodes also drop out of the "undo last fill" set
+ m_fill_last.erase(std::remove(m_fill_last.begin(), m_fill_last.end(), node), m_fill_last.end());
}
void editor_mode::undo_last()
@@ -626,6 +797,19 @@ bool editor_mode::update()
Application.set_cursor(GLFW_CURSOR_NORMAL);
}
+ // same for the left button (brush / sculpt / click placement). the UI filter in the application
+ // uses io.WantCaptureMouse from the previous frame, so a press on a panel the cursor has just
+ // moved onto can leak into the viewport, and its release is then swallowed by the UI; the brush
+ // would keep painting with the button up. by now ImGui has processed this frame's input, so
+ // MouseDown is the real button state and MouseDownOwned tells whether the press hit the UI.
+ // (pick callbacks queued by such a press are discarded separately, see viewport_click())
+ if (mouseHold && (!ImGui::GetIO().MouseDown[0] || !viewport_click()))
+ {
+ mouseHold = false;
+ m_dragging = false;
+ m_input.mouse.button(GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE);
+ }
+
// fixed step render time routines (50 Hz)
fTime50Hz += deltarealtime; // accumulate even when paused to keep frame reads stable
while (fTime50Hz >= 1.0 / 50.0)
@@ -708,6 +892,13 @@ bool editor_mode::update()
// --- ImGuizmo: in-viewport transform gizmo for the selected node ---
render_gizmo();
+ // --- area fill: outline overlay and settings, while the mode is active ---
+ if (ui()->mode() == nodebank_panel::FILL)
+ {
+ draw_area_fill_outline();
+ render_area_fill();
+ }
+
// --- ImGui: Editor Settings & History windows ---
if(m_settings_open)
render_settings();
@@ -1097,18 +1288,8 @@ void editor_mode::capture_terrain()
return;
}
- // instance world transform, matching the renderer: translate * rotateY * rotateX * rotateZ * scale
- glm::dmat4 rootm(1.0);
- rootm = glm::translate(rootm, model->location());
- glm::vec3 const angles = model->Angles();
- if (angles.y != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.y)), glm::dvec3(0.0, 1.0, 0.0));
- if (angles.x != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.x)), glm::dvec3(1.0, 0.0, 0.0));
- if (angles.z != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.z)), glm::dvec3(0.0, 0.0, 1.0));
- glm::vec3 const scale = model->Scale();
- rootm = glm::scale(rootm, glm::dvec3(scale));
-
std::vector tris;
- gather_submodel_triangles(model->pModel->Root, rootm, tris);
+ gather_submodel_triangles(model->pModel->Root, instance_matrix(*model), tris);
if (tris.empty())
{
WriteLog("Editor: selected model has no readable geometry to capture", logtype::generic);
@@ -1174,6 +1355,366 @@ void editor_mode::capture_terrain()
simulation::State.delete_model(model);
}
+void editor_mode::add_area_fill_point()
+{
+ // like the other placement tools, the point comes from the depth buffer under the cursor
+ // (ground geometry only), relative to the camera
+ glm::dvec3 const offset = GfxRenderer->Mouse_Position();
+ if (glm::length(offset) < 1e-3)
+ return; // no ground under the cursor (yet)
+
+ m_fill_points.push_back(Camera.Pos + offset);
+}
+
+void editor_mode::undo_last_area_fill()
+{
+ // nullify_history_pointers() removes deleted nodes from m_fill_last, so work on a copy
+ auto const created = std::move(m_fill_last);
+ m_fill_last.clear();
+
+ for (TAnimModel *model : created)
+ {
+ if (model == nullptr)
+ continue;
+ if (m_node == model)
+ {
+ m_node = nullptr;
+ ui()->set_node(nullptr);
+ }
+ nullify_history_pointers(model);
+ remove_from_hierarchy(model);
+ simulation::State.delete_model(model);
+ }
+ m_fill_status = "Removed " + std::to_string(created.size()) + " objects of the last fill";
+}
+
+void editor_mode::run_area_fill()
+{
+ // limits keeping a single click from freezing the editor for too long
+ std::size_t constexpr max_objects = 20000;
+ // large model instances (e.g. terrain tiles) are treated as ground, smaller ones (houses, trees) are not
+ float constexpr terrain_model_radius = 50.0f;
+ // ground is searched up to this far above the height interpolated from the outline points,
+ // so hills inside the outline are found but bridges or roofs high above it are not
+ double constexpr height_tolerance = 50.0;
+
+ if (m_fill_points.size() < 3)
+ {
+ m_fill_status = "Outline needs at least 3 points";
+ return;
+ }
+
+ // model package
+ std::vector package;
+ if (m_fill_package == 0)
+ package = m_fill_custom;
+ else
+ package = ui()->nodebank_group_templates(static_cast(m_fill_package - 1));
+ package.erase(std::remove_if(package.begin(), package.end(), [](std::string const &Template) { return Template.empty(); }), package.end());
+ if (package.empty())
+ {
+ m_fill_status = "Selected model package is empty";
+ return;
+ }
+
+ // area bounds
+ glm::dvec2 bmin(std::numeric_limits::max());
+ glm::dvec2 bmax(-std::numeric_limits::max());
+ for (auto const &p : m_fill_points)
+ {
+ bmin = glm::min(bmin, glm::dvec2(p.x, p.z));
+ bmax = glm::max(bmax, glm::dvec2(p.x, p.z));
+ }
+ double const area = polygon_area_xz(m_fill_points);
+ auto const target = static_cast(std::min(std::round(area / 10000.0 * std::max(0.0f, m_fill_density)), max_objects));
+ if (target == 0)
+ {
+ m_fill_status = "Density too low for this area, nothing to place";
+ return;
+ }
+
+ // scatter points: random samples inside the outline, rejecting the ones closer than the minimal spacing
+ // to an already accepted point (checked on a hashed grid with cell size == spacing)
+ double const spacing = std::max(0.0f, m_fill_min_spacing);
+ std::unordered_map> occupancy;
+ auto const cell_key = [](std::int64_t const X, std::int64_t const Z) { return (X << 32) ^ (Z & 0xffffffff); };
+ std::vector points;
+ points.reserve(target);
+ for (std::size_t attempt = 0; attempt < target * 30 && points.size() < target; ++attempt)
+ {
+ glm::dvec2 const p(LocalRandom(bmin.x, bmax.x), LocalRandom(bmin.y, bmax.y));
+ if (false == point_in_polygon_xz(m_fill_points, p.x, p.y))
+ continue;
+ if (spacing > 0.0)
+ {
+ auto const cx = static_cast(std::floor(p.x / spacing));
+ auto const cz = static_cast(std::floor(p.y / spacing));
+ bool free = true;
+ for (std::int64_t dz = -1; dz <= 1 && free; ++dz)
+ for (std::int64_t dx = -1; dx <= 1 && free; ++dx)
+ {
+ auto const lookup = occupancy.find(cell_key(cx + dx, cz + dz));
+ if (lookup == occupancy.end())
+ continue;
+ for (auto const idx : lookup->second)
+ if (glm::distance(points[idx], p) < spacing)
+ {
+ free = false;
+ break;
+ }
+ }
+ if (!free)
+ continue;
+ occupancy[cell_key(cx, cz)].push_back(points.size());
+ }
+ points.push_back(p);
+ }
+
+ // ground geometry within the area. shapes hold the (legacy) terrain, large instances the terrain tiles
+ std::vector triangles;
+ glm::dvec2 const center = (bmin + bmax) * 0.5;
+ float const radius = static_cast(glm::length(bmax - bmin) * 0.5);
+ auto const sections = simulation::Region->sections(glm::dvec3(center.x, 0.0, center.y), radius); // copy, the result is a scratchpad
+ for (auto *section : sections)
+ {
+ for (auto const &shape : section->m_shapes)
+ gather_shape_triangles(shape, bmin, bmax, triangles);
+ for (auto &cell : section->m_cells)
+ {
+ double const r = cell.m_area.radius;
+ if (cell.m_area.center.x + r < bmin.x || cell.m_area.center.x - r > bmax.x || cell.m_area.center.z + r < bmin.y || cell.m_area.center.z - r > bmax.y)
+ continue;
+ for (auto const &shape : cell.m_shapesopaque)
+ gather_shape_triangles(shape, bmin, bmax, triangles);
+ if (false == m_fill_models_as_ground)
+ continue;
+ for (auto *instance : cell.m_instancesopaque)
+ {
+ if (instance == nullptr || instance->Model() == nullptr || instance->radius() < terrain_model_radius)
+ continue;
+ std::vector modeltriangles;
+ gather_submodel_triangles(instance->Model()->Root, instance_matrix(*instance), modeltriangles);
+ for (auto const &t : modeltriangles)
+ if (std::max({t[0].x, t[1].x, t[2].x}) >= bmin.x && std::min({t[0].x, t[1].x, t[2].x}) <= bmax.x && std::max({t[0].z, t[1].z, t[2].z}) >= bmin.y &&
+ std::min({t[0].z, t[1].z, t[2].z}) <= bmax.y)
+ triangles.push_back(t);
+ }
+ }
+ }
+ triangle_grid const ground(std::move(triangles), bmin, bmax);
+ auto const terrains = active_terrains();
+
+ auto const rotation_mode = m_fill_random_rotation ? functions_panel::RANDOM : ui()->rot_mode();
+ auto const fixed_rotation_value = ui()->rot_val();
+ float const scalemin = std::max(0.01f, std::min(m_fill_scale_min, m_fill_scale_max));
+ float const scalemax = std::max(0.01f, std::max(m_fill_scale_min, m_fill_scale_max));
+
+ std::vector created;
+ created.reserve(points.size());
+ std::size_t unsupported = 0;
+ for (auto const &p : points)
+ {
+ // reference height: the outline points, weighted by inverse squared distance
+ double weights = 0.0, reference = 0.0;
+ for (auto const &v : m_fill_points)
+ {
+ double const w = 1.0 / std::max(1e-6, glm::length2(glm::dvec2(v.x, v.z) - p));
+ weights += w;
+ reference += w * v.y;
+ }
+ reference /= weights;
+ double const ceiling = reference + height_tolerance;
+
+ double y = -std::numeric_limits::max();
+ bool found = ground.height_at(p.x, p.y, ceiling, y);
+ for (editor_terrain *terrain : terrains)
+ {
+ if (!terrain->contains(p.x, p.y))
+ continue;
+ double const h = terrain->height_at(p.x, p.y);
+ if (h <= ceiling && (!found || h > y))
+ {
+ y = h;
+ found = true;
+ }
+ }
+ if (!found)
+ {
+ y = reference;
+ ++unsupported;
+ }
+
+ glm::dvec3 const location(p.x, y, p.y);
+ if (!simulation::Region->point_inside(location))
+ continue;
+
+ auto const &src = package[package.size() > 1 ? std::min(package.size() - 1, static_cast(LocalRandom(0.0, static_cast(package.size())))) : 0];
+ TAnimModel *cloned = simulation::State.create_model(src, "editor_", location);
+ if (!cloned)
+ continue;
+ cloned->m_name = "editor_" + cloned->uuid.to_string();
+ apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value);
+ if (scalemin != 1.0f || scalemax != 1.0f)
+ cloned->Scale(static_cast(LocalRandom(scalemin, scalemax)));
+ created.push_back(cloned);
+ }
+
+ // a new fill replaces the "last fill" undo set; the previous objects stay in the scene
+ m_fill_last = std::move(created);
+
+ m_fill_status = "Placed " + std::to_string(m_fill_last.size()) + " of " + std::to_string(target) + " objects";
+ if (points.size() < target)
+ m_fill_status += " (limited by min. spacing)";
+ if (unsupported > 0)
+ m_fill_status += ", " + std::to_string(unsupported) + " without ground found (height interpolated)";
+ WriteLog("Editor: area fill - " + m_fill_status, logtype::generic);
+}
+
+void editor_mode::draw_area_fill_outline() const
+{
+ if (m_fill_points.empty())
+ return;
+
+ // same camera-relative view and clean perspective the transform gizmo uses
+ ImGuiIO const &io = ImGui::GetIO();
+ glm::mat4 const view = GfxRenderer->Camera_View_Matrix();
+ glm::dvec3 const camerapos = GfxRenderer->Camera_Position();
+ float const fovy = glm::radians(Global.FieldOfView / Global.ZoomFactor);
+ float const aspect = io.DisplaySize.y > 0.0f ? io.DisplaySize.x / io.DisplaySize.y : 1.0f;
+ glm::mat4 const viewprojection = glm::perspective(fovy, aspect, 0.1f, 10000.0f) * view;
+
+ auto const to_clip = [&](glm::dvec3 const &Point) { return viewprojection * glm::vec4(glm::vec3(Point - camerapos), 1.0f); };
+ auto const to_screen = [&](glm::vec4 const &Clip) {
+ return ImVec2((Clip.x / Clip.w * 0.5f + 0.5f) * io.DisplaySize.x, (0.5f - Clip.y / Clip.w * 0.5f) * io.DisplaySize.y);
+ };
+ float constexpr nearw = 0.1f;
+
+ ImDrawList *drawlist = ImGui::GetBackgroundDrawList();
+ ImU32 const edgecolor = IM_COL32(255, 200, 40, 230);
+ ImU32 const closingcolor = IM_COL32(255, 200, 40, 110);
+
+ std::size_t const count = m_fill_points.size();
+ for (std::size_t i = 0; i < count; ++i)
+ {
+ bool const closing = (i + 1 == count);
+ if (closing && count < 3)
+ break;
+ glm::vec4 a = to_clip(m_fill_points[i]);
+ glm::vec4 b = to_clip(m_fill_points[(i + 1) % count]);
+ // clip the edge against the near plane, so points behind the camera don't flip across the screen
+ if (a.w < nearw && b.w < nearw)
+ continue;
+ if (a.w < nearw)
+ a = glm::mix(a, b, (nearw - a.w) / (b.w - a.w));
+ else if (b.w < nearw)
+ b = glm::mix(b, a, (nearw - b.w) / (a.w - b.w));
+ drawlist->AddLine(to_screen(a), to_screen(b), closing ? closingcolor : edgecolor, 2.0f);
+ }
+ for (std::size_t i = 0; i < count; ++i)
+ {
+ glm::vec4 const c = to_clip(m_fill_points[i]);
+ if (c.w < nearw)
+ continue;
+ drawlist->AddCircleFilled(to_screen(c), i == 0 ? 6.0f : 4.0f, i == 0 ? IM_COL32(255, 90, 40, 255) : edgecolor);
+ }
+}
+
+void editor_mode::render_area_fill()
+{
+ ImGui::Begin("Area fill", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing);
+
+ ImGui::TextUnformatted("LMB: add outline point, Backspace: remove last point");
+ double const area = polygon_area_xz(m_fill_points);
+ ImGui::Text("Points: %zu Area: %.0f m2 (%.2f ha)", m_fill_points.size(), area, area / 10000.0);
+ if (ImGui::Button("Remove last point") && !m_fill_points.empty())
+ m_fill_points.pop_back();
+ ImGui::SameLine();
+ if (ImGui::Button("Clear outline"))
+ m_fill_points.clear();
+
+ ImGui::Separator();
+
+ // model package: a node bank group, or a custom set assembled from node bank templates
+ auto const groups = ui()->nodebank_groups();
+ m_fill_package = std::clamp(m_fill_package, 0, static_cast(groups.size()));
+ std::string const current = m_fill_package == 0 ? std::string("Custom set") : groups[m_fill_package - 1];
+ ImGui::SetNextItemWidth(250.0f);
+ if (ImGui::BeginCombo("Model package", current.c_str()))
+ {
+ if (ImGui::Selectable("Custom set", m_fill_package == 0))
+ m_fill_package = 0;
+ for (int i = 0; i < static_cast(groups.size()); ++i)
+ {
+ auto const label = groups[i] + "##fillgroup" + std::to_string(i);
+ if (ImGui::Selectable(label.c_str(), m_fill_package == i + 1))
+ m_fill_package = i + 1;
+ }
+ ImGui::EndCombo();
+ }
+
+ if (m_fill_package == 0)
+ {
+ ImGui::BeginChild("fill_custom_set", ImVec2(350.0f, 110.0f), true);
+ for (int i = 0; i < static_cast(m_fill_custom.size()); ++i)
+ {
+ auto const label = template_label(m_fill_custom[i]) + "##fillcustom" + std::to_string(i);
+ if (ImGui::Selectable(label.c_str(), m_fill_custom_idx == i))
+ m_fill_custom_idx = i;
+ }
+ ImGui::EndChild();
+ if (ImGui::Button("Add selected template"))
+ {
+ // the node bank selection, not a random pick from the brush set
+ auto const *src = ui()->get_active_node_template(true);
+ if (src && !src->empty())
+ m_fill_custom.push_back(*src);
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Remove") && m_fill_custom_idx >= 0 && m_fill_custom_idx < static_cast(m_fill_custom.size()))
+ {
+ m_fill_custom.erase(m_fill_custom.begin() + m_fill_custom_idx);
+ m_fill_custom_idx = -1;
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Clear set"))
+ {
+ m_fill_custom.clear();
+ m_fill_custom_idx = -1;
+ }
+ }
+ else
+ {
+ ImGui::Text("Templates in group: %zu", ui()->nodebank_group_templates(static_cast(m_fill_package - 1)).size());
+ }
+
+ ImGui::Separator();
+
+ ImGui::SetNextItemWidth(120.0f);
+ ImGui::InputFloat("Density (objects/ha)", &m_fill_density, 10.0f, 100.0f, "%.1f");
+ m_fill_density = std::max(0.0f, m_fill_density);
+ ImGui::SetNextItemWidth(120.0f);
+ ImGui::InputFloat("Min. spacing (m)", &m_fill_min_spacing, 0.5f, 2.0f, "%.1f");
+ m_fill_min_spacing = std::max(0.0f, m_fill_min_spacing);
+ ImGui::SetNextItemWidth(200.0f);
+ ImGui::DragFloatRange2("Scale", &m_fill_scale_min, &m_fill_scale_max, 0.01f, 0.1f, 5.0f, "min %.2f", "max %.2f");
+ ImGui::Checkbox("Random rotation (off: Functions panel setting)", &m_fill_random_rotation);
+ ImGui::Checkbox("Large models count as ground (terrain tiles)", &m_fill_models_as_ground);
+
+ ImGui::Text("Estimated objects: %.0f", std::round(area / 10000.0 * m_fill_density));
+
+ if (ImGui::Button("Fill area"))
+ run_area_fill();
+ ImGui::SameLine();
+ std::string const undolabel = "Undo last fill (" + std::to_string(m_fill_last.size()) + ")";
+ if (ImGui::Button(undolabel.c_str()) && !m_fill_last.empty())
+ undo_last_area_fill();
+
+ if (!m_fill_status.empty())
+ ImGui::TextUnformatted(m_fill_status.c_str());
+
+ ImGui::End();
+}
+
void editor_mode::render_gizmo()
{
// the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse
@@ -1381,6 +1922,7 @@ void editor_mode::exit()
g_redo.clear();
m_history.clear();
+ m_fill_last.clear();
// drop selection so a stale/dangling node pointer isn't used on the next editor session
m_node = nullptr;
@@ -1496,6 +2038,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
}
break;
+ case GLFW_KEY_BACKSPACE:
+ // area fill: remove the last outline point
+ if (is_press(Action) && ui()->mode() == nodebank_panel::FILL && !m_fill_points.empty())
+ m_fill_points.pop_back();
+ break;
+
case GLFW_KEY_F:
if (is_press(Action))
{
@@ -1565,11 +2113,30 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
if (is_press(Action))
{
mouseHold = true;
- m_node = nullptr;
+ m_brush_has_last = false; // every brush stroke starts with a placement
- // delegate node picking behaviour depending on current panel mode
+ // in area fill mode the left button only adds outline points, it doesn't touch the selection
+ if (mode == nodebank_panel::FILL)
+ {
+ GfxRenderer->Pick_Node_Callback([this](scene::basic_node * /*node*/) {
+ if (viewport_click())
+ add_area_fill_point();
+ });
+ m_input.mouse.button(Button, Action);
+ return;
+ }
+
+ // delegate node picking behaviour depending on current panel mode.
+ // NOTE: the pick is resolved a few frames later, often after the button was already released,
+ // so the callback mustn't depend on the button still being held
GfxRenderer->Pick_Node_Callback(
[this, mode, rotation_mode, fixed_rotation_value](scene::basic_node *node) {
+ // the press turned out to be meant for the UI
+ if (!viewport_click())
+ return;
+
+ m_node = nullptr;
+
// ignore picks that are beyond allowed placement distance
if (node) {
double const dist = glm::distance(node->location(), glm::dvec3{Global.pCamera.Pos});
@@ -1578,9 +2145,6 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
}
if (mode == nodebank_panel::MODIFY)
{
- if (!m_dragging)
- return;
-
m_node = node;
ui()->set_node(m_node);
}
@@ -1607,19 +2171,16 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
if (!cloned)
return;
- // record addition for undo
- std::string as_text;
std::string new_name = "editor_" + cloned->uuid.to_string();
-
cloned->m_name = new_name;
+ apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value);
+
+ // record addition for undo (after rotation, so a redo recreates the same thing)
+ std::string as_text;
cloned->export_as_text(as_text);
push_snapshot(cloned, EditorSnapshot::Action::Add, as_text);
- if (!m_dragging)
- return;
-
m_node = cloned;
- apply_rotation_for_new_node(m_node, rotation_mode, fixed_rotation_value);
ui()->set_node(m_node);
}
});
diff --git a/application/editormode.h b/application/editormode.h
index 29b1ad690..413b4225a 100644
--- a/application/editormode.h
+++ b/application/editormode.h
@@ -19,6 +19,10 @@ http://mozilla.org/MPL/2.0/.
#include "editor/editorTerrainStreamer.hpp"
#include
+#include
+#include
+
+class TAnimModel;
class editor_mode : public application_mode
{
@@ -122,7 +126,8 @@ class editor_mode : public application_mode
scene::basic_node *m_node{nullptr}; // currently selected scene node
bool m_takesnapshot{true}; // helper, hints whether snapshot of selected node(s) should be taken before modification
bool m_dragging = false;
- glm::dvec3 oldPos;
+ glm::dvec3 oldPos; // world position of the last brush placement
+ bool m_brush_has_last{false}; // false at the start of a brush stroke, so the first placement ignores spacing
bool mouseHold{false};
float kMaxPlacementDistance = 200.0f;
static bool m_change_history;
@@ -196,6 +201,25 @@ class editor_mode : public application_mode
void render_change_history();
void render_settings();
+ // area fill: scatters models from a package over a polygon outlined in the viewport
+ void render_area_fill();
+ void draw_area_fill_outline() const;
+ void add_area_fill_point();
+ void run_area_fill();
+ void undo_last_area_fill();
+ std::vector m_fill_points; // outline vertices (world space) in click order
+ std::vector m_fill_last; // instances created by the most recent fill, for "Undo last fill"
+ std::vector m_fill_custom; // user-assembled package of node templates
+ int m_fill_custom_idx{-1};
+ int m_fill_package{0}; // 0 = custom set, N = nodebank group N-1
+ float m_fill_density{200.0f}; // objects per hectare
+ float m_fill_min_spacing{2.0f}; // minimal distance between placed objects (m)
+ bool m_fill_random_rotation{true}; // random yaw; otherwise the Functions panel rotation settings apply
+ float m_fill_scale_min{1.0f};
+ float m_fill_scale_max{1.0f};
+ bool m_fill_models_as_ground{true}; // large model instances (terrain tiles) count as ground
+ std::string m_fill_status; // result of the last fill, shown in the panel
+
// ImGuizmo-based transform gizmo for the selected node
enum class gizmo_operation { translate, rotate, scale };
void render_gizmo();
diff --git a/application/editoruilayer.cpp b/application/editoruilayer.cpp
index d87dd8fab..b00b1e516 100644
--- a/application/editoruilayer.cpp
+++ b/application/editoruilayer.cpp
@@ -55,6 +55,16 @@ void editor_ui::toggleBrushSettings(bool isVisible)
m_brushobjects.is_open = isVisible;
}
+std::vector editor_ui::nodebank_groups() const
+{
+ return m_nodebankpanel.group_names();
+}
+
+std::vector editor_ui::nodebank_group_templates(std::size_t const Group) const
+{
+ return m_nodebankpanel.group_templates(Group);
+}
+
void editor_ui::set_node(scene::basic_node *Node)
{
m_node = Node;
diff --git a/application/editoruilayer.h b/application/editoruilayer.h
index ad3d5447b..57d75466b 100644
--- a/application/editoruilayer.h
+++ b/application/editoruilayer.h
@@ -37,6 +37,8 @@ class editor_ui : public ui_layer
nodebank_panel::edit_mode mode();
float getSpacing();
void toggleBrushSettings(bool isVisible);
+ std::vector nodebank_groups() const;
+ std::vector nodebank_group_templates(std::size_t const Group) const;
private:
// members
diff --git a/application/editoruipanels.cpp b/application/editoruipanels.cpp
index cbfe0ae71..80eec0ba5 100644
--- a/application/editoruipanels.cpp
+++ b/application/editoruipanels.cpp
@@ -434,13 +434,13 @@ void brush_object_list::render()
{
Objects.erase(Objects.begin() + idx);
}
- if (ImGui::Button("Remove all") && idx >= 0 && idx < Objects.size())
+ if (ImGui::Button("Remove all"))
{
Objects.clear();
}
}
- ImGui::End();
}
+ ImGui::End();
}
nodebank_panel::nodebank_panel(std::string const &Name, bool const Isopen) : ui_panel(Name, Isopen)
@@ -535,6 +535,8 @@ void nodebank_panel::render()
ImGui::SameLine();
ImGui::RadioButton("Copy to bank", (int *)&mode, COPY);
ImGui::SameLine();
+ ImGui::RadioButton("Area fill", (int *)&mode, FILL);
+ ImGui::SameLine();
if (ImGui::Button("Reload Nodebank"))
{
nodebank_reload();
@@ -598,6 +600,43 @@ const std::string *nodebank_panel::get_active_template()
return m_selectedtemplate.get();
}
+std::vector nodebank_panel::group_names() const
+{
+ std::vector names;
+ for (auto const &entry : m_nodebank)
+ {
+ if (entry.second->empty())
+ names.emplace_back(entry.first);
+ else if (names.empty())
+ names.emplace_back("(ungrouped)"); // templates listed before the first header
+ }
+ return names;
+}
+
+std::vector nodebank_panel::group_templates(std::size_t const Group) const
+{
+ std::vector templates;
+ std::size_t group{0};
+ bool started{false};
+ for (auto const &entry : m_nodebank)
+ {
+ if (entry.second->empty())
+ {
+ // header: opens the next group, unless it's the very first entry
+ if (started)
+ ++group;
+ started = true;
+ continue;
+ }
+ started = true;
+ if (group == Group)
+ templates.emplace_back(*entry.second);
+ else if (group > Group)
+ break;
+ }
+ return templates;
+}
+
std::string nodebank_panel::generate_node_label(std::string Input) const
{
diff --git a/application/editoruipanels.h b/application/editoruipanels.h
index 41da71735..50e8bf99c 100644
--- a/application/editoruipanels.h
+++ b/application/editoruipanels.h
@@ -81,7 +81,8 @@ class nodebank_panel : public ui_panel
MODIFY,
COPY,
ADD,
- BRUSH
+ BRUSH,
+ FILL
};
edit_mode mode = MODIFY;
@@ -90,6 +91,10 @@ class nodebank_panel : public ui_panel
void render() override;
void add_template(const std::string &desc);
const std::string *get_active_template();
+ // nodebank groups (collapsing headers), in file order; entries listed before the first header form an unnamed group
+ std::vector group_names() const;
+ // node templates of the group with specified index (as returned by group_names())
+ std::vector group_templates(std::size_t const Group) const;
private:
// methods:
From f9deee5cfdd63db40ace5c555fdec13cf61cb24e Mon Sep 17 00:00:00 2001
From: Hirek193
Date: Thu, 1 Oct 2026 02:03:49 +0200
Subject: [PATCH 017/430] fix(editor): stuck brush after clicks on UI; add
polygon area fill (#191)
---
application/editormode.cpp | 619 +++++++++++++++++++++++++++++++--
application/editormode.h | 26 +-
application/editoruilayer.cpp | 10 +
application/editoruilayer.h | 2 +
application/editoruipanels.cpp | 43 ++-
application/editoruipanels.h | 7 +-
6 files changed, 674 insertions(+), 33 deletions(-)
diff --git a/application/editormode.cpp b/application/editormode.cpp
index 46a8edadf..94b1424da 100644
--- a/application/editormode.cpp
+++ b/application/editormode.cpp
@@ -24,6 +24,8 @@ http://mozilla.org/MPL/2.0/.
#include "model/Model3d.h"
#include "utilities/Float3d.h"
#include "scene/scene.h"
+#include "utilities/parser.h"
+#include "utilities/utilities.h"
#include "imgui/imgui.h"
@@ -58,6 +60,14 @@ namespace
return state == GLFW_PRESS;
}
+ // true when the most recent left button press landed in the viewport rather than on an ImGui window.
+ // valid once ImGui has processed the press (i.e. from mode update onwards), so it's also used to
+ // discard deferred pick callbacks of a press that leaked past the application's UI filter
+ inline bool viewport_click()
+ {
+ return false == ImGui::GetIO().MouseDownOwned[0];
+ }
+
// tests whether the vertical line through (Px,Pz) passes over triangle abc; if so returns the
// surface height at that point through OutY. used by the "snap to ground" (END) feature.
inline bool triangle_height_at(glm::dvec3 const &a, glm::dvec3 const &b, glm::dvec3 const &c,
@@ -117,6 +127,158 @@ namespace
}
}
+ // world transform of a model instance, matching the renderer: translate * rotateY * rotateX * rotateZ * scale
+ glm::dmat4 instance_matrix(TAnimModel const &Model)
+ {
+ glm::dmat4 rootm(1.0);
+ rootm = glm::translate(rootm, Model.location());
+ glm::vec3 const angles = Model.Angles();
+ if (angles.y != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.y)), glm::dvec3(0.0, 1.0, 0.0));
+ if (angles.x != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.x)), glm::dvec3(1.0, 0.0, 0.0));
+ if (angles.z != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.z)), glm::dvec3(0.0, 0.0, 1.0));
+ return glm::scale(rootm, glm::dvec3(Model.Scale()));
+ }
+
+ // even-odd test of a point against a polygon outline projected onto the XZ plane
+ bool point_in_polygon_xz(std::vector const &Polygon, double const X, double const Z)
+ {
+ bool inside = false;
+ for (std::size_t i = 0, j = Polygon.size() - 1; i < Polygon.size(); j = i++)
+ {
+ auto const &a = Polygon[i];
+ auto const &b = Polygon[j];
+ if ((a.z > Z) != (b.z > Z) && X < (b.x - a.x) * (Z - a.z) / (b.z - a.z) + a.x)
+ inside = !inside;
+ }
+ return inside;
+ }
+
+ // area of a polygon outline projected onto the XZ plane (shoelace formula)
+ double polygon_area_xz(std::vector const &Polygon)
+ {
+ if (Polygon.size() < 3)
+ return 0.0;
+ double sum = 0.0;
+ for (std::size_t i = 0, j = Polygon.size() - 1; i < Polygon.size(); j = i++)
+ sum += Polygon[j].x * Polygon[i].z - Polygon[i].x * Polygon[j].z;
+ return std::abs(sum) * 0.5;
+ }
+
+ // short readable name of a node template (model file and texture), like the node bank shows it
+ std::string template_label(std::string const &Template)
+ {
+ cParser tokenizer(Template);
+ tokenizer.getTokens(9, false); // node, ranges, name, type, position, rotation
+ auto model{tokenizer.getToken(false)};
+ auto texture{tokenizer.getToken(false)};
+ replace_slashes(model);
+ erase_extension(model);
+ replace_slashes(texture);
+ return texture == "none" || texture.empty() ? model : model + " (" + texture + ")";
+ }
+
+ // world triangles bucketed on a uniform XZ grid, for many ground height queries over one area
+ class triangle_grid
+ {
+ public:
+ triangle_grid(std::vector Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max) : m_triangles(std::move(Triangles)), m_min(Min)
+ {
+ glm::dvec2 const extent = glm::max(Max - Min, glm::dvec2(1.0));
+ // ~8 m cells, coarser for big areas so large terrain triangles don't flood the grid
+ m_cellsize = std::max(8.0, std::max(extent.x, extent.y) / 128.0);
+ m_columns = static_cast(std::ceil(extent.x / m_cellsize)) + 1;
+ m_rows = static_cast(std::ceil(extent.y / m_cellsize)) + 1;
+ m_cells.resize(static_cast(m_columns) * m_rows);
+
+ for (std::uint32_t idx = 0; idx < m_triangles.size(); ++idx)
+ {
+ auto const &t = m_triangles[idx];
+ int const c0 = column(std::min({t[0].x, t[1].x, t[2].x}));
+ int const c1 = column(std::max({t[0].x, t[1].x, t[2].x}));
+ int const r0 = row(std::min({t[0].z, t[1].z, t[2].z}));
+ int const r1 = row(std::max({t[0].z, t[1].z, t[2].z}));
+ for (int r = r0; r <= r1; ++r)
+ for (int c = c0; c <= c1; ++c)
+ m_cells[static_cast(r) * m_columns + c].push_back(idx);
+ }
+ }
+
+ // highest surface at (X,Z) that isn't above Ceiling. returns: true if there is one
+ bool height_at(double const X, double const Z, double const Ceiling, double &OutY) const
+ {
+ bool found = false;
+ for (auto const idx : m_cells[static_cast(row(Z)) * m_columns + column(X)])
+ {
+ auto const &t = m_triangles[idx];
+ double y;
+ if (triangle_height_at(t[0], t[1], t[2], X, Z, y) && y <= Ceiling && (!found || y > OutY))
+ {
+ OutY = y;
+ found = true;
+ }
+ }
+ return found;
+ }
+
+ private:
+ int column(double const X) const
+ {
+ return std::clamp(static_cast(std::floor((X - m_min.x) / m_cellsize)), 0, m_columns - 1);
+ }
+ int row(double const Z) const
+ {
+ return std::clamp(static_cast(std::floor((Z - m_min.y) / m_cellsize)), 0, m_rows - 1);
+ }
+
+ std::vector m_triangles;
+ std::vector> m_cells;
+ glm::dvec2 m_min;
+ double m_cellsize{8.0};
+ int m_columns{1};
+ int m_rows{1};
+ };
+
+ // appends triangles of a shape node which overlap specified XZ rectangle
+ void gather_shape_triangles(scene::shape_node const &Shape, glm::dvec2 const &Min, glm::dvec2 const &Max, std::vector &Out)
+ {
+ auto const &data = Shape.data();
+ if (data.area.radius >= 0.0f)
+ {
+ double const r = data.area.radius;
+ if (data.area.center.x + r < Min.x || data.area.center.x - r > Max.x || data.area.center.z + r < Min.y || data.area.center.z - r > Max.y)
+ return;
+ }
+
+ auto const add = [&](glm::dvec3 const &a, glm::dvec3 const &b, glm::dvec3 const &c) {
+ if (std::max({a.x, b.x, c.x}) < Min.x || std::min({a.x, b.x, c.x}) > Max.x || std::max({a.z, b.z, c.z}) < Min.y || std::min({a.z, b.z, c.z}) > Max.y)
+ return;
+ Out.push_back({a, b, c});
+ };
+
+ if (false == data.vertices.empty())
+ {
+ for (std::size_t i = 0; i + 2 < data.vertices.size(); i += 3)
+ add(data.vertices[i].position, data.vertices[i + 1].position, data.vertices[i + 2].position);
+ return;
+ }
+ // once the shape is uploaded its world-space source is released; the renderer keeps an origin-relative copy
+ if (data.geometry.bank == 0 && data.geometry.chunk == 0)
+ return;
+ auto const &verts = GfxRenderer->Vertices(data.geometry);
+ auto const &indices = GfxRenderer->Indices(data.geometry);
+ auto const to_world = [&](gfx::basic_vertex const &v) { return data.origin + glm::dvec3(v.position); };
+ if (false == indices.empty())
+ {
+ for (std::size_t i = 0; i + 2 < indices.size(); i += 3)
+ add(to_world(verts[indices[i]]), to_world(verts[indices[i + 1]]), to_world(verts[indices[i + 2]]));
+ }
+ else
+ {
+ for (std::size_t i = 0; i + 2 < verts.size(); i += 3)
+ add(to_world(verts[i]), to_world(verts[i + 1]), to_world(verts[i + 2]));
+ }
+ }
+
}
bool editor_mode::editormode_input::init()
@@ -306,32 +468,38 @@ void editor_mode::handle_brush_mouse_hold(int Action, int Button)
GfxRenderer->Pick_Node_Callback(
[this, mode, rotation_mode, fixed_rotation_value, Action, Button](scene::basic_node * /*node*/) {
+ // picks are resolved a few frames later; drop the ones queued before the button went up,
+ // or for a press that turned out to belong to the UI
+ if (!mouseHold || !viewport_click())
+ return;
+
const std::string *src = ui()->get_active_node_template();
if (!src)
return;
std::string name = "editor_";
- glm::dvec3 newPos = clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position());
- double distance = glm::distance(newPos, oldPos);
- if (distance < ui()->getSpacing())
+ // spacing is measured in world space: the mouse offset is camera-relative and the camera may move mid-stroke
+ glm::dvec3 const newPos = Camera.Pos + clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position());
+ if (m_brush_has_last && glm::distance(newPos, oldPos) < ui()->getSpacing())
return;
- TAnimModel *cloned = simulation::State.create_model(*src, name, Camera.Pos + newPos);
+ TAnimModel *cloned = simulation::State.create_model(*src, name, newPos);
oldPos = newPos;
+ m_brush_has_last = true;
if (!cloned)
return;
std::string new_name = "editor_" + cloned->uuid.to_string();
cloned->m_name = new_name;
-
+ apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value);
+
std::string as_text;
cloned->export_as_text(as_text);
push_snapshot(cloned, EditorSnapshot::Action::Add, as_text);
m_node = cloned;
- apply_rotation_for_new_node(m_node, rotation_mode, fixed_rotation_value);
ui()->set_node(m_node);
});
}
@@ -439,6 +607,9 @@ void editor_mode::nullify_history_pointers(scene::basic_node *node)
if (s.node_ptr == node)
s.node_ptr = nullptr;
}
+
+ // deleted nodes also drop out of the "undo last fill" set
+ m_fill_last.erase(std::remove(m_fill_last.begin(), m_fill_last.end(), node), m_fill_last.end());
}
void editor_mode::undo_last()
@@ -626,6 +797,19 @@ bool editor_mode::update()
Application.set_cursor(GLFW_CURSOR_NORMAL);
}
+ // same for the left button (brush / sculpt / click placement). the UI filter in the application
+ // uses io.WantCaptureMouse from the previous frame, so a press on a panel the cursor has just
+ // moved onto can leak into the viewport, and its release is then swallowed by the UI; the brush
+ // would keep painting with the button up. by now ImGui has processed this frame's input, so
+ // MouseDown is the real button state and MouseDownOwned tells whether the press hit the UI.
+ // (pick callbacks queued by such a press are discarded separately, see viewport_click())
+ if (mouseHold && (!ImGui::GetIO().MouseDown[0] || !viewport_click()))
+ {
+ mouseHold = false;
+ m_dragging = false;
+ m_input.mouse.button(GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE);
+ }
+
// fixed step render time routines (50 Hz)
fTime50Hz += deltarealtime; // accumulate even when paused to keep frame reads stable
while (fTime50Hz >= 1.0 / 50.0)
@@ -708,6 +892,13 @@ bool editor_mode::update()
// --- ImGuizmo: in-viewport transform gizmo for the selected node ---
render_gizmo();
+ // --- area fill: outline overlay and settings, while the mode is active ---
+ if (ui()->mode() == nodebank_panel::FILL)
+ {
+ draw_area_fill_outline();
+ render_area_fill();
+ }
+
// --- ImGui: Editor Settings & History windows ---
if(m_settings_open)
render_settings();
@@ -1097,18 +1288,8 @@ void editor_mode::capture_terrain()
return;
}
- // instance world transform, matching the renderer: translate * rotateY * rotateX * rotateZ * scale
- glm::dmat4 rootm(1.0);
- rootm = glm::translate(rootm, model->location());
- glm::vec3 const angles = model->Angles();
- if (angles.y != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.y)), glm::dvec3(0.0, 1.0, 0.0));
- if (angles.x != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.x)), glm::dvec3(1.0, 0.0, 0.0));
- if (angles.z != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.z)), glm::dvec3(0.0, 0.0, 1.0));
- glm::vec3 const scale = model->Scale();
- rootm = glm::scale(rootm, glm::dvec3(scale));
-
std::vector tris;
- gather_submodel_triangles(model->pModel->Root, rootm, tris);
+ gather_submodel_triangles(model->pModel->Root, instance_matrix(*model), tris);
if (tris.empty())
{
WriteLog("Editor: selected model has no readable geometry to capture", logtype::generic);
@@ -1174,6 +1355,366 @@ void editor_mode::capture_terrain()
simulation::State.delete_model(model);
}
+void editor_mode::add_area_fill_point()
+{
+ // like the other placement tools, the point comes from the depth buffer under the cursor
+ // (ground geometry only), relative to the camera
+ glm::dvec3 const offset = GfxRenderer->Mouse_Position();
+ if (glm::length(offset) < 1e-3)
+ return; // no ground under the cursor (yet)
+
+ m_fill_points.push_back(Camera.Pos + offset);
+}
+
+void editor_mode::undo_last_area_fill()
+{
+ // nullify_history_pointers() removes deleted nodes from m_fill_last, so work on a copy
+ auto const created = std::move(m_fill_last);
+ m_fill_last.clear();
+
+ for (TAnimModel *model : created)
+ {
+ if (model == nullptr)
+ continue;
+ if (m_node == model)
+ {
+ m_node = nullptr;
+ ui()->set_node(nullptr);
+ }
+ nullify_history_pointers(model);
+ remove_from_hierarchy(model);
+ simulation::State.delete_model(model);
+ }
+ m_fill_status = "Removed " + std::to_string(created.size()) + " objects of the last fill";
+}
+
+void editor_mode::run_area_fill()
+{
+ // limits keeping a single click from freezing the editor for too long
+ std::size_t constexpr max_objects = 20000;
+ // large model instances (e.g. terrain tiles) are treated as ground, smaller ones (houses, trees) are not
+ float constexpr terrain_model_radius = 50.0f;
+ // ground is searched up to this far above the height interpolated from the outline points,
+ // so hills inside the outline are found but bridges or roofs high above it are not
+ double constexpr height_tolerance = 50.0;
+
+ if (m_fill_points.size() < 3)
+ {
+ m_fill_status = "Outline needs at least 3 points";
+ return;
+ }
+
+ // model package
+ std::vector package;
+ if (m_fill_package == 0)
+ package = m_fill_custom;
+ else
+ package = ui()->nodebank_group_templates(static_cast(m_fill_package - 1));
+ package.erase(std::remove_if(package.begin(), package.end(), [](std::string const &Template) { return Template.empty(); }), package.end());
+ if (package.empty())
+ {
+ m_fill_status = "Selected model package is empty";
+ return;
+ }
+
+ // area bounds
+ glm::dvec2 bmin(std::numeric_limits::max());
+ glm::dvec2 bmax(-std::numeric_limits::max());
+ for (auto const &p : m_fill_points)
+ {
+ bmin = glm::min(bmin, glm::dvec2(p.x, p.z));
+ bmax = glm::max(bmax, glm::dvec2(p.x, p.z));
+ }
+ double const area = polygon_area_xz(m_fill_points);
+ auto const target = static_cast(std::min(std::round(area / 10000.0 * std::max(0.0f, m_fill_density)), max_objects));
+ if (target == 0)
+ {
+ m_fill_status = "Density too low for this area, nothing to place";
+ return;
+ }
+
+ // scatter points: random samples inside the outline, rejecting the ones closer than the minimal spacing
+ // to an already accepted point (checked on a hashed grid with cell size == spacing)
+ double const spacing = std::max(0.0f, m_fill_min_spacing);
+ std::unordered_map> occupancy;
+ auto const cell_key = [](std::int64_t const X, std::int64_t const Z) { return (X << 32) ^ (Z & 0xffffffff); };
+ std::vector points;
+ points.reserve(target);
+ for (std::size_t attempt = 0; attempt < target * 30 && points.size() < target; ++attempt)
+ {
+ glm::dvec2 const p(LocalRandom(bmin.x, bmax.x), LocalRandom(bmin.y, bmax.y));
+ if (false == point_in_polygon_xz(m_fill_points, p.x, p.y))
+ continue;
+ if (spacing > 0.0)
+ {
+ auto const cx = static_cast(std::floor(p.x / spacing));
+ auto const cz = static_cast(std::floor(p.y / spacing));
+ bool free = true;
+ for (std::int64_t dz = -1; dz <= 1 && free; ++dz)
+ for (std::int64_t dx = -1; dx <= 1 && free; ++dx)
+ {
+ auto const lookup = occupancy.find(cell_key(cx + dx, cz + dz));
+ if (lookup == occupancy.end())
+ continue;
+ for (auto const idx : lookup->second)
+ if (glm::distance(points[idx], p) < spacing)
+ {
+ free = false;
+ break;
+ }
+ }
+ if (!free)
+ continue;
+ occupancy[cell_key(cx, cz)].push_back(points.size());
+ }
+ points.push_back(p);
+ }
+
+ // ground geometry within the area. shapes hold the (legacy) terrain, large instances the terrain tiles
+ std::vector triangles;
+ glm::dvec2 const center = (bmin + bmax) * 0.5;
+ float const radius = static_cast(glm::length(bmax - bmin) * 0.5);
+ auto const sections = simulation::Region->sections(glm::dvec3(center.x, 0.0, center.y), radius); // copy, the result is a scratchpad
+ for (auto *section : sections)
+ {
+ for (auto const &shape : section->m_shapes)
+ gather_shape_triangles(shape, bmin, bmax, triangles);
+ for (auto &cell : section->m_cells)
+ {
+ double const r = cell.m_area.radius;
+ if (cell.m_area.center.x + r < bmin.x || cell.m_area.center.x - r > bmax.x || cell.m_area.center.z + r < bmin.y || cell.m_area.center.z - r > bmax.y)
+ continue;
+ for (auto const &shape : cell.m_shapesopaque)
+ gather_shape_triangles(shape, bmin, bmax, triangles);
+ if (false == m_fill_models_as_ground)
+ continue;
+ for (auto *instance : cell.m_instancesopaque)
+ {
+ if (instance == nullptr || instance->Model() == nullptr || instance->radius() < terrain_model_radius)
+ continue;
+ std::vector modeltriangles;
+ gather_submodel_triangles(instance->Model()->Root, instance_matrix(*instance), modeltriangles);
+ for (auto const &t : modeltriangles)
+ if (std::max({t[0].x, t[1].x, t[2].x}) >= bmin.x && std::min({t[0].x, t[1].x, t[2].x}) <= bmax.x && std::max({t[0].z, t[1].z, t[2].z}) >= bmin.y &&
+ std::min({t[0].z, t[1].z, t[2].z}) <= bmax.y)
+ triangles.push_back(t);
+ }
+ }
+ }
+ triangle_grid const ground(std::move(triangles), bmin, bmax);
+ auto const terrains = active_terrains();
+
+ auto const rotation_mode = m_fill_random_rotation ? functions_panel::RANDOM : ui()->rot_mode();
+ auto const fixed_rotation_value = ui()->rot_val();
+ float const scalemin = std::max(0.01f, std::min(m_fill_scale_min, m_fill_scale_max));
+ float const scalemax = std::max(0.01f, std::max(m_fill_scale_min, m_fill_scale_max));
+
+ std::vector created;
+ created.reserve(points.size());
+ std::size_t unsupported = 0;
+ for (auto const &p : points)
+ {
+ // reference height: the outline points, weighted by inverse squared distance
+ double weights = 0.0, reference = 0.0;
+ for (auto const &v : m_fill_points)
+ {
+ double const w = 1.0 / std::max(1e-6, glm::length2(glm::dvec2(v.x, v.z) - p));
+ weights += w;
+ reference += w * v.y;
+ }
+ reference /= weights;
+ double const ceiling = reference + height_tolerance;
+
+ double y = -std::numeric_limits::max();
+ bool found = ground.height_at(p.x, p.y, ceiling, y);
+ for (editor_terrain *terrain : terrains)
+ {
+ if (!terrain->contains(p.x, p.y))
+ continue;
+ double const h = terrain->height_at(p.x, p.y);
+ if (h <= ceiling && (!found || h > y))
+ {
+ y = h;
+ found = true;
+ }
+ }
+ if (!found)
+ {
+ y = reference;
+ ++unsupported;
+ }
+
+ glm::dvec3 const location(p.x, y, p.y);
+ if (!simulation::Region->point_inside(location))
+ continue;
+
+ auto const &src = package[package.size() > 1 ? std::min(package.size() - 1, static_cast(LocalRandom(0.0, static_cast(package.size())))) : 0];
+ TAnimModel *cloned = simulation::State.create_model(src, "editor_", location);
+ if (!cloned)
+ continue;
+ cloned->m_name = "editor_" + cloned->uuid.to_string();
+ apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value);
+ if (scalemin != 1.0f || scalemax != 1.0f)
+ cloned->Scale(static_cast(LocalRandom(scalemin, scalemax)));
+ created.push_back(cloned);
+ }
+
+ // a new fill replaces the "last fill" undo set; the previous objects stay in the scene
+ m_fill_last = std::move(created);
+
+ m_fill_status = "Placed " + std::to_string(m_fill_last.size()) + " of " + std::to_string(target) + " objects";
+ if (points.size() < target)
+ m_fill_status += " (limited by min. spacing)";
+ if (unsupported > 0)
+ m_fill_status += ", " + std::to_string(unsupported) + " without ground found (height interpolated)";
+ WriteLog("Editor: area fill - " + m_fill_status, logtype::generic);
+}
+
+void editor_mode::draw_area_fill_outline() const
+{
+ if (m_fill_points.empty())
+ return;
+
+ // same camera-relative view and clean perspective the transform gizmo uses
+ ImGuiIO const &io = ImGui::GetIO();
+ glm::mat4 const view = GfxRenderer->Camera_View_Matrix();
+ glm::dvec3 const camerapos = GfxRenderer->Camera_Position();
+ float const fovy = glm::radians(Global.FieldOfView / Global.ZoomFactor);
+ float const aspect = io.DisplaySize.y > 0.0f ? io.DisplaySize.x / io.DisplaySize.y : 1.0f;
+ glm::mat4 const viewprojection = glm::perspective(fovy, aspect, 0.1f, 10000.0f) * view;
+
+ auto const to_clip = [&](glm::dvec3 const &Point) { return viewprojection * glm::vec4(glm::vec3(Point - camerapos), 1.0f); };
+ auto const to_screen = [&](glm::vec4 const &Clip) {
+ return ImVec2((Clip.x / Clip.w * 0.5f + 0.5f) * io.DisplaySize.x, (0.5f - Clip.y / Clip.w * 0.5f) * io.DisplaySize.y);
+ };
+ float constexpr nearw = 0.1f;
+
+ ImDrawList *drawlist = ImGui::GetBackgroundDrawList();
+ ImU32 const edgecolor = IM_COL32(255, 200, 40, 230);
+ ImU32 const closingcolor = IM_COL32(255, 200, 40, 110);
+
+ std::size_t const count = m_fill_points.size();
+ for (std::size_t i = 0; i < count; ++i)
+ {
+ bool const closing = (i + 1 == count);
+ if (closing && count < 3)
+ break;
+ glm::vec4 a = to_clip(m_fill_points[i]);
+ glm::vec4 b = to_clip(m_fill_points[(i + 1) % count]);
+ // clip the edge against the near plane, so points behind the camera don't flip across the screen
+ if (a.w < nearw && b.w < nearw)
+ continue;
+ if (a.w < nearw)
+ a = glm::mix(a, b, (nearw - a.w) / (b.w - a.w));
+ else if (b.w < nearw)
+ b = glm::mix(b, a, (nearw - b.w) / (a.w - b.w));
+ drawlist->AddLine(to_screen(a), to_screen(b), closing ? closingcolor : edgecolor, 2.0f);
+ }
+ for (std::size_t i = 0; i < count; ++i)
+ {
+ glm::vec4 const c = to_clip(m_fill_points[i]);
+ if (c.w < nearw)
+ continue;
+ drawlist->AddCircleFilled(to_screen(c), i == 0 ? 6.0f : 4.0f, i == 0 ? IM_COL32(255, 90, 40, 255) : edgecolor);
+ }
+}
+
+void editor_mode::render_area_fill()
+{
+ ImGui::Begin("Area fill", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing);
+
+ ImGui::TextUnformatted("LMB: add outline point, Backspace: remove last point");
+ double const area = polygon_area_xz(m_fill_points);
+ ImGui::Text("Points: %zu Area: %.0f m2 (%.2f ha)", m_fill_points.size(), area, area / 10000.0);
+ if (ImGui::Button("Remove last point") && !m_fill_points.empty())
+ m_fill_points.pop_back();
+ ImGui::SameLine();
+ if (ImGui::Button("Clear outline"))
+ m_fill_points.clear();
+
+ ImGui::Separator();
+
+ // model package: a node bank group, or a custom set assembled from node bank templates
+ auto const groups = ui()->nodebank_groups();
+ m_fill_package = std::clamp(m_fill_package, 0, static_cast(groups.size()));
+ std::string const current = m_fill_package == 0 ? std::string("Custom set") : groups[m_fill_package - 1];
+ ImGui::SetNextItemWidth(250.0f);
+ if (ImGui::BeginCombo("Model package", current.c_str()))
+ {
+ if (ImGui::Selectable("Custom set", m_fill_package == 0))
+ m_fill_package = 0;
+ for (int i = 0; i < static_cast(groups.size()); ++i)
+ {
+ auto const label = groups[i] + "##fillgroup" + std::to_string(i);
+ if (ImGui::Selectable(label.c_str(), m_fill_package == i + 1))
+ m_fill_package = i + 1;
+ }
+ ImGui::EndCombo();
+ }
+
+ if (m_fill_package == 0)
+ {
+ ImGui::BeginChild("fill_custom_set", ImVec2(350.0f, 110.0f), true);
+ for (int i = 0; i < static_cast(m_fill_custom.size()); ++i)
+ {
+ auto const label = template_label(m_fill_custom[i]) + "##fillcustom" + std::to_string(i);
+ if (ImGui::Selectable(label.c_str(), m_fill_custom_idx == i))
+ m_fill_custom_idx = i;
+ }
+ ImGui::EndChild();
+ if (ImGui::Button("Add selected template"))
+ {
+ // the node bank selection, not a random pick from the brush set
+ auto const *src = ui()->get_active_node_template(true);
+ if (src && !src->empty())
+ m_fill_custom.push_back(*src);
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Remove") && m_fill_custom_idx >= 0 && m_fill_custom_idx < static_cast(m_fill_custom.size()))
+ {
+ m_fill_custom.erase(m_fill_custom.begin() + m_fill_custom_idx);
+ m_fill_custom_idx = -1;
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Clear set"))
+ {
+ m_fill_custom.clear();
+ m_fill_custom_idx = -1;
+ }
+ }
+ else
+ {
+ ImGui::Text("Templates in group: %zu", ui()->nodebank_group_templates(static_cast(m_fill_package - 1)).size());
+ }
+
+ ImGui::Separator();
+
+ ImGui::SetNextItemWidth(120.0f);
+ ImGui::InputFloat("Density (objects/ha)", &m_fill_density, 10.0f, 100.0f, "%.1f");
+ m_fill_density = std::max(0.0f, m_fill_density);
+ ImGui::SetNextItemWidth(120.0f);
+ ImGui::InputFloat("Min. spacing (m)", &m_fill_min_spacing, 0.5f, 2.0f, "%.1f");
+ m_fill_min_spacing = std::max(0.0f, m_fill_min_spacing);
+ ImGui::SetNextItemWidth(200.0f);
+ ImGui::DragFloatRange2("Scale", &m_fill_scale_min, &m_fill_scale_max, 0.01f, 0.1f, 5.0f, "min %.2f", "max %.2f");
+ ImGui::Checkbox("Random rotation (off: Functions panel setting)", &m_fill_random_rotation);
+ ImGui::Checkbox("Large models count as ground (terrain tiles)", &m_fill_models_as_ground);
+
+ ImGui::Text("Estimated objects: %.0f", std::round(area / 10000.0 * m_fill_density));
+
+ if (ImGui::Button("Fill area"))
+ run_area_fill();
+ ImGui::SameLine();
+ std::string const undolabel = "Undo last fill (" + std::to_string(m_fill_last.size()) + ")";
+ if (ImGui::Button(undolabel.c_str()) && !m_fill_last.empty())
+ undo_last_area_fill();
+
+ if (!m_fill_status.empty())
+ ImGui::TextUnformatted(m_fill_status.c_str());
+
+ ImGui::End();
+}
+
void editor_mode::render_gizmo()
{
// the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse
@@ -1381,6 +1922,7 @@ void editor_mode::exit()
g_redo.clear();
m_history.clear();
+ m_fill_last.clear();
// drop selection so a stale/dangling node pointer isn't used on the next editor session
m_node = nullptr;
@@ -1496,6 +2038,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
}
break;
+ case GLFW_KEY_BACKSPACE:
+ // area fill: remove the last outline point
+ if (is_press(Action) && ui()->mode() == nodebank_panel::FILL && !m_fill_points.empty())
+ m_fill_points.pop_back();
+ break;
+
case GLFW_KEY_F:
if (is_press(Action))
{
@@ -1565,11 +2113,30 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
if (is_press(Action))
{
mouseHold = true;
- m_node = nullptr;
+ m_brush_has_last = false; // every brush stroke starts with a placement
- // delegate node picking behaviour depending on current panel mode
+ // in area fill mode the left button only adds outline points, it doesn't touch the selection
+ if (mode == nodebank_panel::FILL)
+ {
+ GfxRenderer->Pick_Node_Callback([this](scene::basic_node * /*node*/) {
+ if (viewport_click())
+ add_area_fill_point();
+ });
+ m_input.mouse.button(Button, Action);
+ return;
+ }
+
+ // delegate node picking behaviour depending on current panel mode.
+ // NOTE: the pick is resolved a few frames later, often after the button was already released,
+ // so the callback mustn't depend on the button still being held
GfxRenderer->Pick_Node_Callback(
[this, mode, rotation_mode, fixed_rotation_value](scene::basic_node *node) {
+ // the press turned out to be meant for the UI
+ if (!viewport_click())
+ return;
+
+ m_node = nullptr;
+
// ignore picks that are beyond allowed placement distance
if (node) {
double const dist = glm::distance(node->location(), glm::dvec3{Global.pCamera.Pos});
@@ -1578,9 +2145,6 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
}
if (mode == nodebank_panel::MODIFY)
{
- if (!m_dragging)
- return;
-
m_node = node;
ui()->set_node(m_node);
}
@@ -1607,19 +2171,16 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
if (!cloned)
return;
- // record addition for undo
- std::string as_text;
std::string new_name = "editor_" + cloned->uuid.to_string();
-
cloned->m_name = new_name;
+ apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value);
+
+ // record addition for undo (after rotation, so a redo recreates the same thing)
+ std::string as_text;
cloned->export_as_text(as_text);
push_snapshot(cloned, EditorSnapshot::Action::Add, as_text);
- if (!m_dragging)
- return;
-
m_node = cloned;
- apply_rotation_for_new_node(m_node, rotation_mode, fixed_rotation_value);
ui()->set_node(m_node);
}
});
diff --git a/application/editormode.h b/application/editormode.h
index 29b1ad690..413b4225a 100644
--- a/application/editormode.h
+++ b/application/editormode.h
@@ -19,6 +19,10 @@ http://mozilla.org/MPL/2.0/.
#include "editor/editorTerrainStreamer.hpp"
#include
+#include
+#include
+
+class TAnimModel;
class editor_mode : public application_mode
{
@@ -122,7 +126,8 @@ class editor_mode : public application_mode
scene::basic_node *m_node{nullptr}; // currently selected scene node
bool m_takesnapshot{true}; // helper, hints whether snapshot of selected node(s) should be taken before modification
bool m_dragging = false;
- glm::dvec3 oldPos;
+ glm::dvec3 oldPos; // world position of the last brush placement
+ bool m_brush_has_last{false}; // false at the start of a brush stroke, so the first placement ignores spacing
bool mouseHold{false};
float kMaxPlacementDistance = 200.0f;
static bool m_change_history;
@@ -196,6 +201,25 @@ class editor_mode : public application_mode
void render_change_history();
void render_settings();
+ // area fill: scatters models from a package over a polygon outlined in the viewport
+ void render_area_fill();
+ void draw_area_fill_outline() const;
+ void add_area_fill_point();
+ void run_area_fill();
+ void undo_last_area_fill();
+ std::vector m_fill_points; // outline vertices (world space) in click order
+ std::vector m_fill_last; // instances created by the most recent fill, for "Undo last fill"
+ std::vector m_fill_custom; // user-assembled package of node templates
+ int m_fill_custom_idx{-1};
+ int m_fill_package{0}; // 0 = custom set, N = nodebank group N-1
+ float m_fill_density{200.0f}; // objects per hectare
+ float m_fill_min_spacing{2.0f}; // minimal distance between placed objects (m)
+ bool m_fill_random_rotation{true}; // random yaw; otherwise the Functions panel rotation settings apply
+ float m_fill_scale_min{1.0f};
+ float m_fill_scale_max{1.0f};
+ bool m_fill_models_as_ground{true}; // large model instances (terrain tiles) count as ground
+ std::string m_fill_status; // result of the last fill, shown in the panel
+
// ImGuizmo-based transform gizmo for the selected node
enum class gizmo_operation { translate, rotate, scale };
void render_gizmo();
diff --git a/application/editoruilayer.cpp b/application/editoruilayer.cpp
index d87dd8fab..b00b1e516 100644
--- a/application/editoruilayer.cpp
+++ b/application/editoruilayer.cpp
@@ -55,6 +55,16 @@ void editor_ui::toggleBrushSettings(bool isVisible)
m_brushobjects.is_open = isVisible;
}
+std::vector editor_ui::nodebank_groups() const
+{
+ return m_nodebankpanel.group_names();
+}
+
+std::vector editor_ui::nodebank_group_templates(std::size_t const Group) const
+{
+ return m_nodebankpanel.group_templates(Group);
+}
+
void editor_ui::set_node(scene::basic_node *Node)
{
m_node = Node;
diff --git a/application/editoruilayer.h b/application/editoruilayer.h
index ad3d5447b..57d75466b 100644
--- a/application/editoruilayer.h
+++ b/application/editoruilayer.h
@@ -37,6 +37,8 @@ class editor_ui : public ui_layer
nodebank_panel::edit_mode mode();
float getSpacing();
void toggleBrushSettings(bool isVisible);
+ std::vector nodebank_groups() const;
+ std::vector nodebank_group_templates(std::size_t const Group) const;
private:
// members
diff --git a/application/editoruipanels.cpp b/application/editoruipanels.cpp
index cbfe0ae71..80eec0ba5 100644
--- a/application/editoruipanels.cpp
+++ b/application/editoruipanels.cpp
@@ -434,13 +434,13 @@ void brush_object_list::render()
{
Objects.erase(Objects.begin() + idx);
}
- if (ImGui::Button("Remove all") && idx >= 0 && idx < Objects.size())
+ if (ImGui::Button("Remove all"))
{
Objects.clear();
}
}
- ImGui::End();
}
+ ImGui::End();
}
nodebank_panel::nodebank_panel(std::string const &Name, bool const Isopen) : ui_panel(Name, Isopen)
@@ -535,6 +535,8 @@ void nodebank_panel::render()
ImGui::SameLine();
ImGui::RadioButton("Copy to bank", (int *)&mode, COPY);
ImGui::SameLine();
+ ImGui::RadioButton("Area fill", (int *)&mode, FILL);
+ ImGui::SameLine();
if (ImGui::Button("Reload Nodebank"))
{
nodebank_reload();
@@ -598,6 +600,43 @@ const std::string *nodebank_panel::get_active_template()
return m_selectedtemplate.get();
}
+std::vector nodebank_panel::group_names() const
+{
+ std::vector names;
+ for (auto const &entry : m_nodebank)
+ {
+ if (entry.second->empty())
+ names.emplace_back(entry.first);
+ else if (names.empty())
+ names.emplace_back("(ungrouped)"); // templates listed before the first header
+ }
+ return names;
+}
+
+std::vector nodebank_panel::group_templates(std::size_t const Group) const
+{
+ std::vector templates;
+ std::size_t group{0};
+ bool started{false};
+ for (auto const &entry : m_nodebank)
+ {
+ if (entry.second->empty())
+ {
+ // header: opens the next group, unless it's the very first entry
+ if (started)
+ ++group;
+ started = true;
+ continue;
+ }
+ started = true;
+ if (group == Group)
+ templates.emplace_back(*entry.second);
+ else if (group > Group)
+ break;
+ }
+ return templates;
+}
+
std::string nodebank_panel::generate_node_label(std::string Input) const
{
diff --git a/application/editoruipanels.h b/application/editoruipanels.h
index 41da71735..50e8bf99c 100644
--- a/application/editoruipanels.h
+++ b/application/editoruipanels.h
@@ -81,7 +81,8 @@ class nodebank_panel : public ui_panel
MODIFY,
COPY,
ADD,
- BRUSH
+ BRUSH,
+ FILL
};
edit_mode mode = MODIFY;
@@ -90,6 +91,10 @@ class nodebank_panel : public ui_panel
void render() override;
void add_template(const std::string &desc);
const std::string *get_active_template();
+ // nodebank groups (collapsing headers), in file order; entries listed before the first header form an unnamed group
+ std::vector group_names() const;
+ // node templates of the group with specified index (as returned by group_names())
+ std::vector group_templates(std::size_t const Group) const;
private:
// methods:
From 99c5a0090b63d931db62fe8b801493e447f0a681 Mon Sep 17 00:00:00 2001
From: jakubg1 <24206305+jakubg1@users.noreply.github.com>
Date: Thu, 1 Oct 2026 02:10:21 +0200
Subject: [PATCH 018/430] Remove brake position check from
`TController::PrepareEngine()`
The function would flag the consist as not ready (`iEngineActive` set to `false`) when the brake handle was at a cutoff position. Since this is what the brake lever is exactly starting at in the EW58 train, the train when asked to move the brake lever to operating position would not listen since the `control_tractive_and_braking_force()` function which is supposed to do that is gated behind the readiness flag in the `TController::Update()` function.
This makes sure EW58 trains can be driven by AI once again instead of being stuck.
I don't really know why the brake position check was there, since it would fail only if:
- There is a brake handle
- The brake handle is in the cutoff position
- The brake handle is NOT in the operating position
The third check seems redundant but curiously there is one case where this matters and it's... MHZ_EN57. Its operating and cutoff positions are both defined as `0`, which might be a hack, since the actual cutoff position in the MHZ_EN57 handle is meant to be `6`.
---
vehicle/Driver.cpp | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)
diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp
index 9dfd6731b..6f3c41003 100644
--- a/vehicle/Driver.cpp
+++ b/vehicle/Driver.cpp
@@ -2857,10 +2857,7 @@ bool TController::PrepareEngine()
&& false == IsAnyLineBreakerOpen
&& ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled )
&& ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled )
- && ( mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0 )
- && ( static_cast(mvOccupied->fBrakeCtrlPos) == static_cast(mvOccupied->Handle->GetPos(bh_RP))
- || static_cast(mvOccupied->fBrakeCtrlPos) != static_cast(mvOccupied->Handle->GetPos(bh_NP))
- || mvOccupied->BrakeHandle == TBrakeHandle::NoHandle );
+ && ( mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0 );
}
if( true == isready ) {
From 403a6d1f9f6ed080a01da23218a21fcd8cca1894 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Thu, 1 Oct 2026 07:58:28 +0200
Subject: [PATCH 019/430] fix: yet other sonar sast fixes
---
McZapkie/Mover.cpp | 19 ++++++++-----------
rendering/opengl33renderer.cpp | 8 ++++----
rendering/openglrenderer.cpp | 8 ++++----
simulation/simulationenvironment.cpp | 6 +++---
4 files changed, 19 insertions(+), 22 deletions(-)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 68b889188..61bdc17a7 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -2408,7 +2408,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed)
{
++MainCtrlPos;
OK = true;
- if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1 && MainCtrlActualPos != MainCtrlPos)
+ if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos)
{
DecScndCtrl(2);
SpeedCtrlUnit.IsActive = false;
@@ -2591,7 +2591,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed)
{
MainCtrlPos--;
OK = true;
- if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1 && MainCtrlActualPos != MainCtrlPos)
+ if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos)
{
DecScndCtrl(2);
SpeedCtrlUnit.IsActive = false;
@@ -2780,7 +2780,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed)
if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0)
{
SpeedCtrlValue = Vel;
- if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1)
+ if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1)
{
MainCtrlActualPos = MainCtrlPos;
}
@@ -4586,14 +4586,11 @@ void TMoverParameters::UpdatePipePressure(double dt)
auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable};
- if (true == RadioStopFlag || true == AlarmChainFlag || (true == EIMCtrlEmergency && LocalBrakePosA >= 1.0) || SecuritySystem.is_braking() ||
- (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive)
- /*
- // NOTE: disabled because 32 is 'load destroyed' flag, what does this have to do with emergency brake?
- // (if it's supposed to be broken coupler, such event sets alarmchainflag instead when appropriate)
- || ( true == TestFlag( EngDmgFlag, 32 ) )
- */
- || (0 == CabActive && InactiveCabFlag & activation::emergencybrake) || (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive))
+ // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with
+ // the emergency brake (a broken coupler sets AlarmChainFlag instead)
+ if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || SecuritySystem.is_braking() ||
+ (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) ||
+ (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0))
{
EmergencyValveFlow = PF(0, PipePress, 0.15) * dt;
}
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index b99378162..06fad0cdb 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -81,9 +81,9 @@ bool opengl33_renderer::Init(GLFWwindow *Window)
}
// rgb value for 5780 kelvin
- Global.DayLight.diffuse[0] = 255.0f / 255.0f;
- Global.DayLight.diffuse[1] = 242.0f / 255.0f;
- Global.DayLight.diffuse[2] = 231.0f / 255.0f;
+ Global.DayLight.diffuse[0] = 1.0f; // 255 / 255
+ Global.DayLight.diffuse[1] = 0.9490196f; // 242 / 255
+ Global.DayLight.diffuse[2] = 0.9058824f; // 231 / 255
Global.DayLight.is_directional = true;
m_sunlight.id = opengl33_renderer::sunlight;
@@ -1956,7 +1956,7 @@ bool opengl33_renderer::Render(world_environment *Environment)
// moon
{
Bind_Texture(0, m_moontexture);
- glm::vec3 mooncolor(255.0f / 255.0f, 242.0f / 255.0f, 231.0f / 255.0f);
+ glm::vec3 mooncolor(1.0f, 0.9490196f, 0.9058824f);
glm::vec4 color(mooncolor.r, mooncolor.g, mooncolor.b,
// fade the moon if it's near the sun in the sky, especially during the day
std::max(0.f, 1.0 - 0.5 * Global.fLuminance - 0.65 * std::max(0.f, glm::dot(Environment->m_sun.getDirection(), Environment->m_moon.getDirection()))) * fogfactor);
diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp
index 6f06e9b33..dcbd1df2c 100644
--- a/rendering/openglrenderer.cpp
+++ b/rendering/openglrenderer.cpp
@@ -88,9 +88,9 @@ opengl_renderer::Init( GLFWwindow *Window ) {
::glEnable( opengl_renderer::sunlight );
// rgb value for 5780 kelvin
- Global.DayLight.diffuse[ 0 ] = 255.0f / 255.0f;
- Global.DayLight.diffuse[ 1 ] = 242.0f / 255.0f;
- Global.DayLight.diffuse[ 2 ] = 231.0f / 255.0f;
+ Global.DayLight.diffuse[0] = 1.0f; // 255 / 255
+ Global.DayLight.diffuse[1] = 0.9490196f; // 242 / 255
+ Global.DayLight.diffuse[2] = 0.9058824f; // 231 / 255
Global.DayLight.is_directional = true;
m_sunlight.id = opengl_renderer::sunlight;
// ::glLightf( opengl_renderer::sunlight, GL_SPOT_CUTOFF, 90.0f );
@@ -1603,7 +1603,7 @@ opengl_renderer::Render( world_environment *Environment ) {
if (!m_isATI)
{
Bind_Texture( m_moontexture );
- glm::vec3 mooncolor( 255.0f / 255.0f, 242.0f / 255.0f, 231.0f / 255.0f );
+ glm::vec3 mooncolor(1.0f, 0.9490196f, 0.9058824f);
::glColor4f(
mooncolor.r, mooncolor.g, mooncolor.b,
// fade the moon if it's near the sun in the sky, especially during the day
diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp
index 9837e0e85..b96cea20d 100644
--- a/simulation/simulationenvironment.cpp
+++ b/simulation/simulationenvironment.cpp
@@ -140,7 +140,7 @@ world_environment::update() {
m_lightintensity = moonlightlevel;
// if the moon is up, it overrides the twilight
twilightfactor = 0.0f;
- keylightcolor = glm::vec3( 255.0f / 255.0f, 242.0f / 255.0f, 202.0f / 255.0f );
+ keylightcolor = glm::vec3( 1.0f, 0.9490196f, 0.7921569f );
}
else {
// regular situation with sun as the key light
@@ -152,8 +152,8 @@ world_environment::update() {
// include 'golden hour' effect in twilight lighting
float const duskfactor = 1.25f - std::clamp( Global.SunAngle, 0.0f, 18.0f ) / 18.0f;
keylightcolor = glm::mix(
- glm::vec3( 255.0f / 255.0f, 242.0f / 255.0f, 231.0f / 255.0f ),
- glm::vec3( 235.0f / 255.0f, 120.0f / 255.0f, 36.0f / 255.0f ),
+ glm::vec3( 1.0f, 0.9490196f, 0.9058824f ), // 255, 242, 231 / 255
+ glm::vec3( 0.9215686f, 0.4705882f, 0.1411765f ), // 235, 120, 36 / 255
duskfactor );
}
// ...retrieve current sky colour and brightness...
From f05b58b0e9995991e841c6562f36f8585d761af7 Mon Sep 17 00:00:00 2001
From: jerrrrycho
Date: Thu, 1 Oct 2026 08:01:23 +0200
Subject: [PATCH 020/430] Revert "fix: yet other sonar sast fixes"
This reverts commit 403a6d1f9f6ed080a01da23218a21fcd8cca1894.
---
McZapkie/Mover.cpp | 19 +++++++++++--------
rendering/opengl33renderer.cpp | 8 ++++----
rendering/openglrenderer.cpp | 8 ++++----
simulation/simulationenvironment.cpp | 6 +++---
4 files changed, 22 insertions(+), 19 deletions(-)
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 61bdc17a7..68b889188 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -2408,7 +2408,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed)
{
++MainCtrlPos;
OK = true;
- if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos)
+ if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1 && MainCtrlActualPos != MainCtrlPos)
{
DecScndCtrl(2);
SpeedCtrlUnit.IsActive = false;
@@ -2591,7 +2591,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed)
{
MainCtrlPos--;
OK = true;
- if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos)
+ if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1 && MainCtrlActualPos != MainCtrlPos)
{
DecScndCtrl(2);
SpeedCtrlUnit.IsActive = false;
@@ -2780,7 +2780,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed)
if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0)
{
SpeedCtrlValue = Vel;
- if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1)
+ if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1)
{
MainCtrlActualPos = MainCtrlPos;
}
@@ -4586,11 +4586,14 @@ void TMoverParameters::UpdatePipePressure(double dt)
auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable};
- // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with
- // the emergency brake (a broken coupler sets AlarmChainFlag instead)
- if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || SecuritySystem.is_braking() ||
- (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) ||
- (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0))
+ if (true == RadioStopFlag || true == AlarmChainFlag || (true == EIMCtrlEmergency && LocalBrakePosA >= 1.0) || SecuritySystem.is_braking() ||
+ (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive)
+ /*
+ // NOTE: disabled because 32 is 'load destroyed' flag, what does this have to do with emergency brake?
+ // (if it's supposed to be broken coupler, such event sets alarmchainflag instead when appropriate)
+ || ( true == TestFlag( EngDmgFlag, 32 ) )
+ */
+ || (0 == CabActive && InactiveCabFlag & activation::emergencybrake) || (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive))
{
EmergencyValveFlow = PF(0, PipePress, 0.15) * dt;
}
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index 06fad0cdb..b99378162 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -81,9 +81,9 @@ bool opengl33_renderer::Init(GLFWwindow *Window)
}
// rgb value for 5780 kelvin
- Global.DayLight.diffuse[0] = 1.0f; // 255 / 255
- Global.DayLight.diffuse[1] = 0.9490196f; // 242 / 255
- Global.DayLight.diffuse[2] = 0.9058824f; // 231 / 255
+ Global.DayLight.diffuse[0] = 255.0f / 255.0f;
+ Global.DayLight.diffuse[1] = 242.0f / 255.0f;
+ Global.DayLight.diffuse[2] = 231.0f / 255.0f;
Global.DayLight.is_directional = true;
m_sunlight.id = opengl33_renderer::sunlight;
@@ -1956,7 +1956,7 @@ bool opengl33_renderer::Render(world_environment *Environment)
// moon
{
Bind_Texture(0, m_moontexture);
- glm::vec3 mooncolor(1.0f, 0.9490196f, 0.9058824f);
+ glm::vec3 mooncolor(255.0f / 255.0f, 242.0f / 255.0f, 231.0f / 255.0f);
glm::vec4 color(mooncolor.r, mooncolor.g, mooncolor.b,
// fade the moon if it's near the sun in the sky, especially during the day
std::max(0.f, 1.0 - 0.5 * Global.fLuminance - 0.65 * std::max(0.f, glm::dot(Environment->m_sun.getDirection(), Environment->m_moon.getDirection()))) * fogfactor);
diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp
index dcbd1df2c..6f06e9b33 100644
--- a/rendering/openglrenderer.cpp
+++ b/rendering/openglrenderer.cpp
@@ -88,9 +88,9 @@ opengl_renderer::Init( GLFWwindow *Window ) {
::glEnable( opengl_renderer::sunlight );
// rgb value for 5780 kelvin
- Global.DayLight.diffuse[0] = 1.0f; // 255 / 255
- Global.DayLight.diffuse[1] = 0.9490196f; // 242 / 255
- Global.DayLight.diffuse[2] = 0.9058824f; // 231 / 255
+ Global.DayLight.diffuse[ 0 ] = 255.0f / 255.0f;
+ Global.DayLight.diffuse[ 1 ] = 242.0f / 255.0f;
+ Global.DayLight.diffuse[ 2 ] = 231.0f / 255.0f;
Global.DayLight.is_directional = true;
m_sunlight.id = opengl_renderer::sunlight;
// ::glLightf( opengl_renderer::sunlight, GL_SPOT_CUTOFF, 90.0f );
@@ -1603,7 +1603,7 @@ opengl_renderer::Render( world_environment *Environment ) {
if (!m_isATI)
{
Bind_Texture( m_moontexture );
- glm::vec3 mooncolor(1.0f, 0.9490196f, 0.9058824f);
+ glm::vec3 mooncolor( 255.0f / 255.0f, 242.0f / 255.0f, 231.0f / 255.0f );
::glColor4f(
mooncolor.r, mooncolor.g, mooncolor.b,
// fade the moon if it's near the sun in the sky, especially during the day
diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp
index b96cea20d..9837e0e85 100644
--- a/simulation/simulationenvironment.cpp
+++ b/simulation/simulationenvironment.cpp
@@ -140,7 +140,7 @@ world_environment::update() {
m_lightintensity = moonlightlevel;
// if the moon is up, it overrides the twilight
twilightfactor = 0.0f;
- keylightcolor = glm::vec3( 1.0f, 0.9490196f, 0.7921569f );
+ keylightcolor = glm::vec3( 255.0f / 255.0f, 242.0f / 255.0f, 202.0f / 255.0f );
}
else {
// regular situation with sun as the key light
@@ -152,8 +152,8 @@ world_environment::update() {
// include 'golden hour' effect in twilight lighting
float const duskfactor = 1.25f - std::clamp( Global.SunAngle, 0.0f, 18.0f ) / 18.0f;
keylightcolor = glm::mix(
- glm::vec3( 1.0f, 0.9490196f, 0.9058824f ), // 255, 242, 231 / 255
- glm::vec3( 0.9215686f, 0.4705882f, 0.1411765f ), // 235, 120, 36 / 255
+ glm::vec3( 255.0f / 255.0f, 242.0f / 255.0f, 231.0f / 255.0f ),
+ glm::vec3( 235.0f / 255.0f, 120.0f / 255.0f, 36.0f / 255.0f ),
duskfactor );
}
// ...retrieve current sky colour and brightness...
From 20f536f05e68acb9e3a9fe1140cbd310b29cded2 Mon Sep 17 00:00:00 2001
From: Hirek193
Date: Thu, 1 Oct 2026 11:51:41 +0200
Subject: [PATCH 021/430] fix(instancing): keep batches correct after load-time
classification
---
model/AnimModel.cpp | 5 +
rendering/opengl33geometrybank.cpp | 35 +++++--
rendering/opengl33renderer.cpp | 156 ++++++++++++++++++++---------
rendering/opengl33renderer.h | 7 +-
scene/scene.cpp | 26 ++---
5 files changed, 158 insertions(+), 71 deletions(-)
diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp
index bc2d6e844..d5d856e0c 100644
--- a/model/AnimModel.cpp
+++ b/model/AnimModel.cpp
@@ -478,6 +478,9 @@ std::shared_ptr TAnimModel::AddContainer(std::string const &Name
auto tmp = std::make_shared();
tmp->Init(tsb);
m_animlist.push_back(tmp);
+ // containers are added by events after the instance was loaded and bucketed;
+ // the instanced path skips RaAnimate(), so this instance has to be drawn on its own
+ m_instanceable = false;
return tmp;
}
return nullptr;
@@ -688,6 +691,8 @@ std::optional> > TAnimModel::L
void TAnimModel::SkinSet( int const Index, material_handle const Material ) {
m_materialdata.replacable_skins[ std::clamp( Index, 1, 4 ) ] = Material;
+ // the instance stays in the bucket of its old skin set, where it would get the textures of the batch
+ m_instanceable = false;
}
void TAnimModel::AnimUpdate(double dt)
diff --git a/rendering/opengl33geometrybank.cpp b/rendering/opengl33geometrybank.cpp
index 91c9a8dd8..506d22f1e 100644
--- a/rendering/opengl33geometrybank.cpp
+++ b/rendering/opengl33geometrybank.cpp
@@ -215,13 +215,34 @@ opengl33_vaogeometrybank::draw_instanced_( gfx::geometry_handle const &Geometry,
GLsizei const inst_count = static_cast(InstanceCount);
if( chunkrecord.index_count > 0 ) {
- m_vao->bind();
- ::glDrawElementsInstancedBaseVertex(
- chunk.type,
- chunkrecord.index_count, GL_UNSIGNED_INT,
- reinterpret_cast( chunkrecord.index_offset * sizeof( gfx::basic_index ) ),
- inst_count,
- chunkrecord.vertex_offset );
+ // GLES 3.0 context doesn't provide the base vertex variant, same fallbacks as in draw_()
+ if( glDrawElementsInstancedBaseVertex ) {
+ m_vao->bind();
+ ::glDrawElementsInstancedBaseVertex(
+ chunk.type,
+ chunkrecord.index_count, GL_UNSIGNED_INT,
+ reinterpret_cast( chunkrecord.index_offset * sizeof( gfx::basic_index ) ),
+ inst_count,
+ chunkrecord.vertex_offset );
+ }
+ else if( glDrawElementsInstancedBaseVertexOES ) {
+ m_vao->bind();
+ ::glDrawElementsInstancedBaseVertexOES(
+ chunk.type,
+ chunkrecord.index_count, GL_UNSIGNED_INT,
+ reinterpret_cast( chunkrecord.index_offset * sizeof( gfx::basic_index ) ),
+ inst_count,
+ chunkrecord.vertex_offset );
+ }
+ else {
+ setup_attrib( chunkrecord.vertex_offset );
+ m_vao->bind();
+ ::glDrawElementsInstanced(
+ chunk.type,
+ chunkrecord.index_count, GL_UNSIGNED_INT,
+ reinterpret_cast( chunkrecord.index_offset * sizeof( gfx::basic_index ) ),
+ inst_count );
+ }
}
else {
m_vao->bind();
diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp
index b99378162..352d9632e 100644
--- a/rendering/opengl33renderer.cpp
+++ b/rendering/opengl33renderer.cpp
@@ -2382,8 +2382,11 @@ void opengl33_renderer::Render(scene::basic_region *Region)
m_sectionqueue.clear();
m_cellqueue.clear();
- // discard last pass's accumulated instance buckets before this pass starts
- m_frame_instance_buckets.clear();
+ // discard last pass's accumulated instance buckets before this pass starts.
+ // the vectors themselves are kept, so their allocations get reused by the following passes
+ for( auto &bucket : m_frame_instance_buckets ) {
+ bucket.second.clear();
+ }
// build a list of region sections to render
glm::vec3 const cameraposition{m_renderpass.pass_camera.position()};
auto const camerax = static_cast(std::floor(cameraposition.x / scene::EU07_SECTIONSIZE + scene::EU07_REGIONSIDESECTIONCOUNT / 2));
@@ -2802,10 +2805,11 @@ void opengl33_renderer::Render(cell_sequence::iterator First, cell_sequence::ite
// still happens inside Render_Instanced(), so correctness is unchanged -- only
// the number of calls and glBufferSubData round-trips drops sharply.
// (For pickscenery/pickcontrols modes the map stays empty, so this is a no-op.)
- for( auto const &bucket : m_frame_instance_buckets ) {
+ for( auto &bucket : m_frame_instance_buckets ) {
+ if( bucket.second.empty() ) { continue; }
Render_Instanced( bucket.first.pModel, bucket.second );
+ bucket.second.clear();
}
- m_frame_instance_buckets.clear();
}
void opengl33_renderer::Draw_Geometry(std::vector::iterator begin, std::vector::iterator end)
@@ -3024,13 +3028,13 @@ void opengl33_renderer::Render_Instanced( TModel3d *Model, std::vector::max();
+ float farthest_distancesquared = 0.f;
material_data const *batch_material { nullptr };
for( auto *Instance : Instances ) {
if( Instance == nullptr ) { continue; }
+ // instances which lost their instanceable status after being bucketed (animation or skin
+ // assigned by an event) are drawn by the per-node path
+ if( false == Instance->m_instanceable ) { continue; }
if( false == Instance->m_visible ) { continue; }
if( false == m_renderpass.pass_camera.visible( Instance->m_area ) ) { continue; }
@@ -3077,6 +3085,7 @@ void opengl33_renderer::Render_Instanced( TModel3d *Model, std::vectorm_framestamp = m_framestamp;
closest_distancesquared = std::min( closest_distancesquared, static_cast(distancesquared) );
+ farthest_distancesquared = std::max( farthest_distancesquared, static_cast(distancesquared) );
// Build the camera-relative root modelview for this instance:
// mv = view * translate(instance_pos - camera_pos) * rotate(instance_angles) * scale(m_scale)
@@ -3095,55 +3104,106 @@ void opengl33_renderer::Render_Instanced( TModel3d *Model, std::vector( distancesquared ), mv );
}
- if( m_instance_modelviews.empty() ) { return; }
+ if( m_instance_survivors.empty() ) { return; }
+
+ // LOD: a submodel is drawn only while fSquareDist lies inside its [fSquareMinDist, fSquareMaxDist)
+ // range, so the distinct range bounds split distance into bands with constant LOD. The bucket
+ // collects instances from every visible cell, so a single fSquareDist for all of them would draw
+ // far instances at the LOD of the nearest one. When some bound falls inside the distance span of
+ // the survivors they're sorted near-to-far and drawn one band at a time, like Render_Sleepers().
+ m_instance_lodbounds.clear();
+ m_instance_lodpending.clear();
+ m_instance_lodpending.push_back( Model->Root );
+ while( false == m_instance_lodpending.empty() ) {
+ auto const *submodel = m_instance_lodpending.back();
+ m_instance_lodpending.pop_back();
+ if( submodel == nullptr ) { continue; }
+ if( ( submodel->fSquareMinDist > closest_distancesquared ) && ( submodel->fSquareMinDist <= farthest_distancesquared ) ) {
+ m_instance_lodbounds.emplace_back( submodel->fSquareMinDist );
+ }
+ if( ( submodel->fSquareMaxDist > closest_distancesquared ) && ( submodel->fSquareMaxDist <= farthest_distancesquared ) ) {
+ m_instance_lodbounds.emplace_back( submodel->fSquareMaxDist );
+ }
+ m_instance_lodpending.push_back( submodel->Child );
+ m_instance_lodpending.push_back( submodel->Next );
+ }
+ if( false == m_instance_lodbounds.empty() ) {
+ std::sort( m_instance_lodbounds.begin(), m_instance_lodbounds.end() );
+ m_instance_lodbounds.erase( std::unique( m_instance_lodbounds.begin(), m_instance_lodbounds.end() ), m_instance_lodbounds.end() );
+ std::sort( m_instance_survivors.begin(), m_instance_survivors.end(),
+ []( std::pair const &Left, std::pair const &Right ) {
+ return Left.first < Right.first; } );
+ }
+ // contiguous copy of the (sorted) modelview matrices, for the UBO upload
+ m_instance_modelviews.clear();
+ m_instance_modelviews.reserve( m_instance_survivors.size() );
+ for( auto const &survivor : m_instance_survivors ) {
+ m_instance_modelviews.emplace_back( survivor.second );
+ }
+
+ auto alpha = ( batch_material != nullptr ? batch_material->textures_alpha : 0x30300030 );
+ alpha ^= 0x0F0F000F;
// 2. Walk the submodel tree once per sub-batch. The submodel-local matrix
// stack starts at identity; the per-instance camera transform comes from
// instance_modelview[gl_InstanceID] in the shader.
std::size_t const total = m_instance_modelviews.size();
- std::size_t offset_idx = 0;
- while( offset_idx < total ) {
- std::size_t const this_batch = std::min( total - offset_idx, gl::MAX_INSTANCES_PER_BATCH );
-
- // 2a. Upload N modelviews to instance_ubo[0..N-1].
- instance_ubo->update(
- reinterpret_cast( m_instance_modelviews.data() + offset_idx ),
- 0,
- static_cast( this_batch * sizeof( glm::mat4 ) ) );
-
- // 2b. Push identity onto the matrix stack so submodel transforms
- // accumulate from identity, not from camera/instance space.
- ::glPushMatrix();
- ::glLoadIdentity();
-
- // 2c. Configure the existing TModel3d/TSubModel render path. Setting
- // m_current_instance_count routes draw(handle) calls to draw_instanced.
- m_current_instance_count = this_batch;
-
- Model->Root->fSquareDist = closest_distancesquared; // shared global, used by submodel LOD
- auto alpha = ( batch_material != nullptr ? batch_material->textures_alpha : 0x30300030 );
- alpha ^= 0x0F0F000F;
- Model->Root->ReplacableSet( ( batch_material != nullptr ? batch_material->replacable_skins : nullptr ), alpha );
- Model->Root->pRoot = Model;
-
- Render( Model->Root );
-
- m_current_instance_count = 0;
-
- ::glPopMatrix();
-
- // 2d. Restore instance_modelview[0] to identity so subsequent
- // non-instanced draws continue to compute identity * modelview.
- {
- glm::mat4 const identity( 1.0f );
- instance_ubo->update( reinterpret_cast( &identity ), 0, sizeof( identity ) );
+ std::size_t band_start = 0;
+ while( band_start < total ) {
+ // the band ends at the first instance distance which reaches the next lod bound
+ // (without bounds inside the distance span the whole set forms a single band)
+ auto const upperbound = std::upper_bound( m_instance_lodbounds.begin(), m_instance_lodbounds.end(), m_instance_survivors[ band_start ].first );
+ float const band_limit = ( upperbound == m_instance_lodbounds.end() ? std::numeric_limits::max() : *upperbound );
+ std::size_t band_end = band_start;
+ while( ( band_end < total ) && ( m_instance_survivors[ band_end ].first < band_limit ) ) {
+ ++band_end;
}
+ // every distance in the band selects the same lod; the nearest one represents the band
+ float const band_distancesquared = ( m_instance_lodbounds.empty() ? closest_distancesquared : m_instance_survivors[ band_start ].first );
- offset_idx += this_batch;
- ++m_renderpass.draw_stats.instanced_drawcalls;
+ std::size_t offset_idx = band_start;
+ while( offset_idx < band_end ) {
+ std::size_t const this_batch = std::min( band_end - offset_idx, gl::MAX_INSTANCES_PER_BATCH );
+
+ // 2a. Upload N modelviews to instance_ubo[0..N-1].
+ instance_ubo->update(
+ reinterpret_cast( m_instance_modelviews.data() + offset_idx ),
+ 0,
+ static_cast( this_batch * sizeof( glm::mat4 ) ) );
+
+ // 2b. Push identity onto the matrix stack so submodel transforms
+ // accumulate from identity, not from camera/instance space.
+ ::glPushMatrix();
+ ::glLoadIdentity();
+
+ // 2c. Configure the existing TModel3d/TSubModel render path. Setting
+ // m_current_instance_count routes draw(handle) calls to draw_instanced.
+ m_current_instance_count = this_batch;
+
+ Model->Root->fSquareDist = band_distancesquared; // shared global, used by submodel LOD
+ Model->Root->ReplacableSet( ( batch_material != nullptr ? batch_material->replacable_skins : nullptr ), alpha );
+ Model->Root->pRoot = Model;
+
+ Render( Model->Root );
+
+ m_current_instance_count = 0;
+
+ ::glPopMatrix();
+
+ // 2d. Restore instance_modelview[0] to identity so subsequent
+ // non-instanced draws continue to compute identity * modelview.
+ {
+ glm::mat4 const identity( 1.0f );
+ instance_ubo->update( reinterpret_cast( &identity ), 0, sizeof( identity ) );
+ }
+
+ offset_idx += this_batch;
+ ++m_renderpass.draw_stats.instanced_drawcalls;
+ }
+ band_start = band_end;
}
m_renderpass.draw_stats.instances += static_cast( total );
diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h
index 6fda37c39..8e5c0b147 100644
--- a/rendering/opengl33renderer.h
+++ b/rendering/opengl33renderer.h
@@ -376,7 +376,7 @@ class opengl33_renderer : public gfx_renderer {
// cell's buckets are merged here keyed by (TModel3d*, skins), so that
// Render_Instanced() runs once per unique model across the whole pass instead
// of once per cell -- collapsing many tiny instanced draws into a few large
- // batches. Reused every pass; cleared at the top of Render(scene::basic_region*).
+ // batches. Reused every pass; the vectors are emptied (not freed) at the top of Render(scene::basic_region*).
scene::basic_cell::instance_bucket_map m_frame_instance_buckets;
renderpass_config m_colorpass; // parametrs of most recent color pass
std::array m_shadowpass; // parametrs of most recent shadowmap pass for each of csm stages
@@ -426,6 +426,11 @@ class opengl33_renderer : public gfx_renderer {
// reused across calls -- clear() retains capacity, so once it has grown to
// the largest batch seen, steady-state frames perform no allocation here.
std::vector m_instance_modelviews;
+ // further persistent scratch buffers for Render_Instanced(): culled instances paired with their
+ // squared distance, and the lod bounds of the drawn model which split them into lod bands
+ std::vector> m_instance_survivors;
+ std::vector m_instance_lodbounds;
+ std::vector