From 9c0a1eb8fdc5886ca5b823f406628854131e6015 Mon Sep 17 00:00:00 2001 From: Ryan Brue Date: Wed, 9 Sep 2026 12:29:31 -0500 Subject: [PATCH 1/5] Do not query metadata for files that cannot match a search pattern FileScannerUnix stats every entry it lists in order to read its size and modified time, but files whose name does not match the search pattern are never returned by next(). Skipping them before that call cuts the repository freshness scans at startup from 10832 stat calls to 345 for a RollerCoaster Tycoon Classic installation, and lets the load/save window list a directory's sub directories without querying every file in it. This matters on file systems where metadata operations are expensive: a stat costs ~60us on the FUSE file system Flatpak's document portal provides, against ~1.4us on local disk. Entries whose type readdir did not report are still queried, as they may be a directory that has to be recursed into. Used an LLM to find the issue, and generate the patch. Performed my own testing. Assisted-by: LLM Signed-off-by: Ryan Brue --- src/openrct2/core/FileScanner.cpp | 45 ++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/src/openrct2/core/FileScanner.cpp b/src/openrct2/core/FileScanner.cpp index 4532dc9748..cb91839ab4 100644 --- a/src/openrct2/core/FileScanner.cpp +++ b/src/openrct2/core/FileScanner.cpp @@ -24,6 +24,7 @@ #include "String.hpp" #include +#include #include #include #include @@ -148,17 +149,8 @@ public: virtual void getDirectoryChildren(std::vector& children, const std::string& path) = 0; -private: - void pushState(const std::string& directory) - { - DirectoryState newState; - newState.path = directory; - newState.index = -1; - getDirectoryChildren(newState.listing, directory); - _directoryStack.push(newState); - } - - bool patternMatch(const std::string& fileName) +protected: + bool patternMatch(const std::string& fileName) const { for (const auto& pattern : _patterns) { @@ -170,6 +162,16 @@ private: return false; } +private: + void pushState(const std::string& directory) + { + DirectoryState newState; + newState.path = directory; + newState.index = -1; + getDirectoryChildren(newState.listing, directory); + _directoryStack.push(newState); + } + static std::vector getPatterns(const std::string& delimitedPatterns) { std::vector patterns; @@ -328,7 +330,11 @@ public: const struct dirent* node = namelist[i]; if (!String::equals(node->d_name, ".") && !String::equals(node->d_name, "..")) { - children.push_back(createChild(path.c_str(), node)); + auto child = createChild(path.c_str(), node); + if (child.has_value()) + { + children.push_back(std::move(child.value())); + } } free(namelist[i]); } @@ -342,7 +348,7 @@ private: return 1; } - static DirectoryChild createChild(const utf8* directory, const struct dirent* node) + std::optional createChild(const utf8* directory, const struct dirent* node) const { DirectoryChild result; result.name = std::string(node->d_name); @@ -358,6 +364,19 @@ private: } else { + #ifndef __HAIKU__ + // Reading the size and modified time of a file costs a stat call each, which is + // expensive on file systems with a high per-operation cost, such as network shares or + // the FUSE file system that Flatpak's document portal provides. Files that cannot match + // the search pattern are never returned, so skip them before paying for that. Entries of + // an unknown type still have to be queried to find out whether they are a directory + // which has to be recursed into. + if (node->d_type == DT_REG && !patternMatch(result.name)) + { + return std::nullopt; + } + #endif + result.type = DirectoryChildType::file; // Get the full path of the file From 6e4431451f999f309d28a53961af5fb953a90aab Mon Sep 17 00:00:00 2001 From: Ryan Brue Date: Wed, 9 Sep 2026 12:29:44 -0500 Subject: [PATCH 2/5] Fix #21030, #26981: Resolve original game files from a cached listing Every image source of the form `$RCT2:OBJDATA/NAME.DAT` was resolved by probing that exact name, then the `.POB` name, and on failure by scanning the object directory recursively. Scanning it stats every entry, so on an RCT Classic installation -- a single flat `Assets` folder of 2708 lower case files, which never match the upper case names the shipped JSON objects ask for -- both probes missed and each object cost a scan of the whole folder. A park needs hundreds of those, and the cache holding the results is thread_local on threads that are destroyed together with the job pool, so the work was repeated on every park load and title sequence transition. Stat and open are ~45x more expensive on the FUSE file system Flatpak's document portal provides than on local disk, which is why this became unbearable there in particular. The RCT1/RCT2 data directories are now listed once into a case insensitive name index that IPlatformEnvironment::FindFile answers from, so resolving a name costs no file system operations at all. Reading a listing only needs the names, not the metadata, and the index is dropped when a base path changes. Loading test/tests/testdata/parks/bpb.sv6 with RCT Classic game data, measured with `openrct2-cli screenshot` (byte identical output before and after): before after document portal 54.5 s 0.45 s local disk 2.58 s 0.34 s Used an LLM to find the problem and generate the patch, and verified the speedup on my own. Assisted-by: LLM Signed-off-by: Ryan Brue --- src/openrct2/PlatformEnvironment.cpp | 139 ++++++++++++++++++++++++++- src/openrct2/object/ImageTable.cpp | 45 ++++----- 2 files changed, 155 insertions(+), 29 deletions(-) diff --git a/src/openrct2/PlatformEnvironment.cpp b/src/openrct2/PlatformEnvironment.cpp index 89d4243f6e..b0722537c7 100644 --- a/src/openrct2/PlatformEnvironment.cpp +++ b/src/openrct2/PlatformEnvironment.cpp @@ -14,10 +14,16 @@ #include "config/Config.h" #include "core/EnumUtils.hpp" #include "core/File.h" +#include "core/FileSystem.hpp" #include "core/Path.hpp" #include "core/String.hpp" #include "platform/Platform.h" +#include +#include +#include +#include + using namespace OpenRCT2; static constexpr const char* kDirectoryNamesRCT2[] = { @@ -80,11 +86,125 @@ static constexpr u8string_view kFileNames[] = { u8"contributors.md", // CONTRIBUTORS }; +/** + * Lower cases ASCII characters only, which matches how String::iequals compares strings. + */ +static u8string ToLowerAscii(u8string_view str) +{ + u8string result(str); + for (auto& c : result) + { + if (c >= 'A' && c <= 'Z') + c += 'a' - 'A'; + } + return result; +} + +/** + * Caches the file names of the original game data directories so that they can be looked up case + * insensitively without hitting the file system. + * + * The game refers to the original files by their MS-DOS era upper case names, while an actual + * installation may use any casing, so every look up has to consider all the names in a directory. + * Doing that per look up means listing a directory of a few thousand files hundreds of times while + * loading a park, which is ruinously slow on file systems with a high per-operation cost, such as + * the FUSE file system Flatpak's document portal provides. The original game data does not change + * while the game is running, so each directory only has to be listed once. + */ +class OriginalGameDataIndex +{ +private: + struct Entry + { + u8string path; + int32_t depth{}; + }; + + // Maps the lower cased name of a file to the file it was found as. + using Listing = std::unordered_map>; + + std::mutex _mutex; + std::map, std::less<>> _listings; + +public: + /** + * Returns the real path of the file with the given name inside the given directory or one of its + * sub directories, matching the name case insensitively. Returns an empty string if there is no + * such file. + */ + u8string FindFile(const u8string& directory, u8string_view fileName) + { + std::lock_guard guard(_mutex); + + const auto& listing = GetListing(directory); + if (!listing.has_value()) + { + // The directory could not be listed, fall back to querying the file system. + return Path::ResolveCasing(Path::Combine(directory, fileName)); + } + + auto it = listing->find(ToLowerAscii(fileName)); + if (it == listing->end()) + return {}; + + return it->second.path; + } + + void Clear() + { + std::lock_guard guard(_mutex); + _listings.clear(); + } + +private: + const std::optional& GetListing(const u8string& directory) + { + auto it = _listings.find(directory); + if (it != _listings.end()) + return it->second; + + return _listings.emplace(directory, ReadListing(directory)).first->second; + } + + static std::optional ReadListing(const u8string& directory) + { + std::error_code ec; + auto it = fs::recursive_directory_iterator(fs::u8path(directory), fs::directory_options::skip_permission_denied, ec); + if (ec) + return std::nullopt; + + Listing listing; + const auto end = fs::recursive_directory_iterator(); + for (; it != end; it.increment(ec)) + { + if (ec) + break; + + // Asks the directory entry rather than the file system, as the entry already knows the + // type of the file on the platforms that report it while listing a directory. + std::error_code typeEc; + if (it->is_directory(typeEc) || typeEc) + continue; + + const auto depth = it.depth(); + auto entry = Entry{ it->path().u8string(), depth }; + auto [entryIt, inserted] = listing.try_emplace(ToLowerAscii(it->path().filename().u8string()), entry); + + // Prefer the files closest to the root of the directory, files in sub directories are + // only meant to be used when there is none of that name next to the other game files. + if (!inserted && depth < entryIt->second.depth) + entryIt->second = std::move(entry); + } + return listing; + } +}; + class PlatformEnvironment final : public IPlatformEnvironment { private: u8string _basePath[kDirBaseCount]; RCT2Variant _rct2Variant = RCT2Variant::rct2Original; + mutable OriginalGameDataIndex _originalGameDataIndex; public: explicit PlatformEnvironment(DirBaseValues basePaths) @@ -175,7 +295,7 @@ public: } } - auto path = Path::ResolveCasing(Path::Combine(dataPath, fileName)); + auto path = ResolveOriginalGameDataPath(base, dataPath, fileName); if (base == DirBase::rct1 && did == DirId::data && !File::Exists(path)) { // Special case, handle RCT1 steam layout where some data files are under a CD root @@ -193,6 +313,7 @@ public: void SetBasePath(DirBase base, u8string_view path) override { _basePath[EnumValue(base)] = path; + _originalGameDataIndex.Clear(); if (base == DirBase::rct2) { @@ -209,6 +330,22 @@ public: } private: + /** + * Resolves the casing of a file inside one of the original game data directories, using the + * cached directory listings where possible. + */ + u8string ResolveOriginalGameDataPath(DirBase base, const u8string& dataPath, u8string_view fileName) const + { + const auto isOriginalGameData = base == DirBase::rct1 || base == DirBase::rct2; + const auto isPlainFileName = fileName.find_first_of("/\\") == u8string_view::npos; + if (!isOriginalGameData || !isPlainFileName || dataPath.empty()) + { + return Path::ResolveCasing(Path::Combine(dataPath, fileName)); + } + + return _originalGameDataIndex.FindFile(dataPath, fileName); + } + static DirBase GetDefaultBaseDirectory(PathId pathid) { switch (pathid) diff --git a/src/openrct2/object/ImageTable.cpp b/src/openrct2/object/ImageTable.cpp index 7742d19dad..f6a488cf28 100644 --- a/src/openrct2/object/ImageTable.cpp +++ b/src/openrct2/object/ImageTable.cpp @@ -14,8 +14,6 @@ #include "../OpenRCT2.h" #include "../PlatformEnvironment.h" #include "../SpriteIds.h" -#include "../core/File.h" -#include "../core/FileScanner.h" #include "../core/Guard.hpp" #include "../core/IStream.hpp" #include "../core/Json.hpp" @@ -381,42 +379,33 @@ namespace OpenRCT2 std::string ImageTable::FindLegacyObject(const std::string& name) { + // The original object files are looked up through the platform environment, which resolves + // their name case insensitively from a cached directory listing. Scanning the directory per + // look up instead is very slow on file systems with a high per-operation cost, and the game + // asks for hundreds of these files whenever it loads a park. const auto& env = GetContext()->GetPlatformEnvironment(); - auto objectsPath = env.GetDirectoryPath(DirBase::rct2, DirId::objects); - auto objectPath = Path::Combine(objectsPath, name); - if (File::Exists(objectPath)) + auto objectPath = env.FindFile(DirBase::rct2, DirId::objects, name); + if (!objectPath.empty()) { return objectPath; } - std::string altName = name; - auto rangeStart = name.find(".DAT"); - if (rangeStart != std::string::npos) + // RCT Classic ships the same objects with a .POB extension + auto extensionStart = name.find(".DAT"); + if (extensionStart != std::string::npos) { - altName.replace(rangeStart, 4, ".POB"); - } - objectPath = Path::Combine(objectsPath, altName); - if (File::Exists(objectPath)) - { - return objectPath; - } + auto altName = name; + altName.replace(extensionStart, 4, ".POB"); - if (!File::Exists(objectPath)) - { - // Search recursively for any file with the target name (case insensitive) - auto filter = Path::Combine(objectsPath, u8"*.dat;*.pob"); - auto scanner = Path::scanDirectory(filter, true); - while (scanner->next()) + objectPath = env.FindFile(DirBase::rct2, DirId::objects, altName); + if (!objectPath.empty()) { - auto currentName = Path::GetFileName(scanner->getPathRelative()); - if (String::iequals(currentName, name) || String::iequals(currentName, altName)) - { - objectPath = scanner->getPath(); - break; - } + return objectPath; } } - return objectPath; + + // Return the path the object was expected at, so that failing to open it can be reported + return Path::Combine(env.GetDirectoryPath(DirBase::rct2, DirId::objects), name); } ImageTable::~ImageTable() From 70f11d3b00b37b6cff18909aab08edd0333cd998 Mon Sep 17 00:00:00 2001 From: Gymnasiast Date: Sun, 11 Oct 2026 12:10:02 +0200 Subject: [PATCH 3/5] Use `tolower` in ToLowerAscii() --- src/openrct2/PlatformEnvironment.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/openrct2/PlatformEnvironment.cpp b/src/openrct2/PlatformEnvironment.cpp index b0722537c7..d7cf732f1e 100644 --- a/src/openrct2/PlatformEnvironment.cpp +++ b/src/openrct2/PlatformEnvironment.cpp @@ -94,8 +94,7 @@ static u8string ToLowerAscii(u8string_view str) u8string result(str); for (auto& c : result) { - if (c >= 'A' && c <= 'Z') - c += 'a' - 'A'; + c = tolower(c); } return result; } From 96be799e24958187032e247330eecc5ce70f42ad Mon Sep 17 00:00:00 2001 From: Gymnasiast Date: Sun, 11 Oct 2026 12:16:34 +0200 Subject: [PATCH 4/5] Fix code style --- src/openrct2/PlatformEnvironment.cpp | 22 +++++++++++----------- src/openrct2/object/ImageTable.cpp | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/openrct2/PlatformEnvironment.cpp b/src/openrct2/PlatformEnvironment.cpp index d7cf732f1e..b06fca4284 100644 --- a/src/openrct2/PlatformEnvironment.cpp +++ b/src/openrct2/PlatformEnvironment.cpp @@ -89,7 +89,7 @@ static constexpr u8string_view kFileNames[] = { /** * Lower cases ASCII characters only, which matches how String::iequals compares strings. */ -static u8string ToLowerAscii(u8string_view str) +static u8string toLowerAscii(const u8string_view str) { u8string result(str); for (auto& c : result) @@ -131,41 +131,41 @@ public: * sub directories, matching the name case insensitively. Returns an empty string if there is no * such file. */ - u8string FindFile(const u8string& directory, u8string_view fileName) + u8string findFile(const u8string& directory, u8string_view fileName) { std::lock_guard guard(_mutex); - const auto& listing = GetListing(directory); + const auto& listing = getListing(directory); if (!listing.has_value()) { // The directory could not be listed, fall back to querying the file system. return Path::ResolveCasing(Path::Combine(directory, fileName)); } - auto it = listing->find(ToLowerAscii(fileName)); + auto it = listing->find(toLowerAscii(fileName)); if (it == listing->end()) return {}; return it->second.path; } - void Clear() + void clear() { std::lock_guard guard(_mutex); _listings.clear(); } private: - const std::optional& GetListing(const u8string& directory) + const std::optional& getListing(const u8string& directory) { auto it = _listings.find(directory); if (it != _listings.end()) return it->second; - return _listings.emplace(directory, ReadListing(directory)).first->second; + return _listings.emplace(directory, readListing(directory)).first->second; } - static std::optional ReadListing(const u8string& directory) + static std::optional readListing(const u8string& directory) { std::error_code ec; auto it = fs::recursive_directory_iterator(fs::u8path(directory), fs::directory_options::skip_permission_denied, ec); @@ -187,7 +187,7 @@ private: const auto depth = it.depth(); auto entry = Entry{ it->path().u8string(), depth }; - auto [entryIt, inserted] = listing.try_emplace(ToLowerAscii(it->path().filename().u8string()), entry); + auto [entryIt, inserted] = listing.try_emplace(toLowerAscii(it->path().filename().u8string()), entry); // Prefer the files closest to the root of the directory, files in sub directories are // only meant to be used when there is none of that name next to the other game files. @@ -312,7 +312,7 @@ public: void SetBasePath(DirBase base, u8string_view path) override { _basePath[EnumValue(base)] = path; - _originalGameDataIndex.Clear(); + _originalGameDataIndex.clear(); if (base == DirBase::rct2) { @@ -342,7 +342,7 @@ private: return Path::ResolveCasing(Path::Combine(dataPath, fileName)); } - return _originalGameDataIndex.FindFile(dataPath, fileName); + return _originalGameDataIndex.findFile(dataPath, fileName); } static DirBase GetDefaultBaseDirectory(PathId pathid) diff --git a/src/openrct2/object/ImageTable.cpp b/src/openrct2/object/ImageTable.cpp index f6a488cf28..7291b63f55 100644 --- a/src/openrct2/object/ImageTable.cpp +++ b/src/openrct2/object/ImageTable.cpp @@ -395,7 +395,7 @@ namespace OpenRCT2 if (extensionStart != std::string::npos) { auto altName = name; - altName.replace(extensionStart, 4, ".POB"); + altName.replace(extensionStart + 1, 3, "POB"); objectPath = env.FindFile(DirBase::rct2, DirId::objects, altName); if (!objectPath.empty()) From 99c2f79898da57619e46b5116d05348c38f7748f Mon Sep 17 00:00:00 2001 From: Gymnasiast Date: Sun, 11 Oct 2026 12:21:28 +0200 Subject: [PATCH 5/5] Update changelog --- distribution/changelog.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/distribution/changelog.txt b/distribution/changelog.txt index c38bde4002..be41bc258e 100644 --- a/distribution/changelog.txt +++ b/distribution/changelog.txt @@ -1,6 +1,7 @@ 0.5.7 (in development) ------------------------------------------------------------------------ - Fix: [#16807] Error messages when trying to load regular JSON files as custom objects. +- Fix: [#21030, #26981] Slow object loading and index building when using RCT Classic or running from a Flatpak. - Fix: [#24524] Some build types (like AppImage) lack information about their specific build. - Fix: [#27264] Headless server crashes when loading a recolourable terrain surface.