diff --git a/distribution/changelog.txt b/distribution/changelog.txt index 9d9a212a30..f4aa3ecfa1 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. - Fix: [#27286] Headless servers no longer write chat logs. diff --git a/src/openrct2/PlatformEnvironment.cpp b/src/openrct2/PlatformEnvironment.cpp index 89d4243f6e..b06fca4284 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,124 @@ static constexpr u8string_view kFileNames[] = { u8"contributors.md", // CONTRIBUTORS }; +/** + * Lower cases ASCII characters only, which matches how String::iequals compares strings. + */ +static u8string toLowerAscii(const u8string_view str) +{ + u8string result(str); + for (auto& c : result) + { + c = tolower(c); + } + 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 +294,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 +312,7 @@ public: void SetBasePath(DirBase base, u8string_view path) override { _basePath[EnumValue(base)] = path; + _originalGameDataIndex.clear(); if (base == DirBase::rct2) { @@ -209,6 +329,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/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 diff --git a/src/openrct2/object/ImageTable.cpp b/src/openrct2/object/ImageTable.cpp index 7742d19dad..7291b63f55 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 + 1, 3, "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()