Files
OpenRCT2-Web/src/openrct2/object/ObjectRepository.cpp
T

950 lines
31 KiB
C++
Raw Normal View History

2017-06-01 21:55:10 +02:00
#pragma region Copyright (c) 2014-2017 OpenRCT2 Developers
/*****************************************************************************
* OpenRCT2, an open source clone of Roller Coaster Tycoon 2.
*
* OpenRCT2 is the work of many authors, a full list can be found in contributors.md
* For more information, visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* A full copy of the GNU General Public License can be found in licence.txt
*****************************************************************************/
#pragma endregion
2016-06-29 21:34:59 +01:00
#include <algorithm>
2017-03-29 20:49:32 +01:00
#include <chrono>
#include <memory>
2016-06-26 16:06:03 +01:00
#include <unordered_map>
#include <vector>
#include "../common.h"
2016-06-25 16:34:35 +01:00
#include "../core/Console.hpp"
2016-10-22 19:11:37 +01:00
#include "../core/FileScanner.h"
#include "../core/FileStream.hpp"
#include "../core/Guard.hpp"
#include "../core/IStream.hpp"
#include "../core/Memory.hpp"
2016-07-07 19:17:09 +01:00
#include "../core/MemoryStream.h"
2016-06-25 01:41:25 +01:00
#include "../core/Path.hpp"
#include "../core/String.hpp"
#include "../PlatformEnvironment.h"
#include "../rct12/SawyerChunkReader.h"
2017-02-05 15:45:23 +00:00
#include "../rct12/SawyerChunkWriter.h"
2016-12-14 12:13:52 +00:00
#include "../scenario/ScenarioRepository.h"
2016-06-25 12:30:20 +01:00
#include "Object.h"
#include "ObjectFactory.h"
2016-07-04 00:05:39 +01:00
#include "ObjectManager.h"
#include "ObjectRepository.h"
2016-06-30 21:55:18 +01:00
#include "RideObject.h"
2016-06-25 16:34:35 +01:00
#include "StexObject.h"
extern "C"
{
2017-02-18 15:45:10 +00:00
#include "../config/Config.h"
2016-06-25 16:34:35 +01:00
#include "../localisation/localisation.h"
#include "../object.h"
2016-07-04 00:05:39 +01:00
#include "../object_list.h"
#include "../platform/platform.h"
2016-06-26 23:30:44 +01:00
#include "../util/sawyercoding.h"
2016-10-23 01:12:17 +01:00
#include "../util/util.h"
}
2017-06-11 12:53:37 +01:00
using namespace OpenRCT2;
constexpr uint16 OBJECT_REPOSITORY_VERSION = 11;
#pragma pack(push, 1)
struct ObjectRepositoryHeader
{
uint16 Version;
uint16 LanguageId;
uint32 TotalFiles;
uint64 TotalFileSize;
uint32 FileDateModifiedChecksum;
uint32 PathChecksum;
uint32 NumItems;
};
assert_struct_size(ObjectRepositoryHeader, 28);
#pragma pack(pop)
2016-06-26 16:06:03 +01:00
struct ObjectEntryHash
{
size_t operator()(const rct_object_entry &entry) const
{
uint32 hash = 5381;
2017-01-04 22:17:08 +01:00
for (sint32 i = 0; i < 8; i++)
2016-06-26 16:06:03 +01:00
{
hash = ((hash << 5) + hash) + entry.name[i];
}
return hash;
}
};
2016-11-13 20:17:49 +01:00
2016-06-26 16:06:03 +01:00
struct ObjectEntryEqual
{
bool operator()(const rct_object_entry &lhs, const rct_object_entry &rhs) const
{
return memcmp(&lhs.name, &rhs.name, 8) == 0;
}
};
using ObjectEntryMap = std::unordered_map<rct_object_entry, size_t, ObjectEntryHash, ObjectEntryEqual>;
2016-07-04 00:05:39 +01:00
static void ReportMissingObject(const rct_object_entry * entry);
class ObjectRepository final : public IObjectRepository
{
const IPlatformEnvironment * _env = nullptr;
std::vector<ObjectRepositoryItem> _items;
2016-12-19 23:59:03 +01:00
QueryDirectoryResult _queryDirectoryResult = { 0 };
2016-06-26 16:06:03 +01:00
ObjectEntryMap _itemMap;
uint16 _languageId = 0;
sint32 _numConflicts = 0;
public:
ObjectRepository(IPlatformEnvironment * env) : _env(env)
{
}
~ObjectRepository() final
2016-06-25 14:44:04 +01:00
{
ClearItems();
}
void LoadOrConstruct() override
{
2016-06-25 01:41:25 +01:00
ClearItems();
Query();
if (!Load())
{
_languageId = gCurrentLanguage;
Scan();
Save();
}
2016-06-29 21:34:59 +01:00
// SortItems();
}
void Construct() override
{
_languageId = gCurrentLanguage;
Query();
Scan();
Save();
}
2016-11-04 09:44:13 +01:00
size_t GetNumObjects() const override
2016-06-28 23:24:49 +01:00
{
return _items.size();
}
const ObjectRepositoryItem * GetObjects() const override
{
return _items.data();
}
const ObjectRepositoryItem * FindObject(const utf8 * name) const override
2016-06-26 16:55:46 +01:00
{
rct_object_entry entry = { 0 };
utf8 entryName[9] = { ' ' };
String::Set(entryName, sizeof(entryName), name);
Memory::Copy<void>(entry.name, entryName, 8);
auto kvp = _itemMap.find(entry);
if (kvp != _itemMap.end())
{
return &_items[kvp->second];
}
return nullptr;
}
const ObjectRepositoryItem * FindObject(const rct_object_entry * objectEntry) const override final
{
2016-06-26 16:06:03 +01:00
auto kvp = _itemMap.find(*objectEntry);
if (kvp != _itemMap.end())
{
2016-06-26 16:06:03 +01:00
return &_items[kvp->second];
}
return nullptr;
}
2016-07-03 21:05:18 +01:00
Object * LoadObject(const ObjectRepositoryItem * ori) override
2016-06-25 16:34:35 +01:00
{
2016-07-16 14:17:36 +01:00
Guard::ArgumentNotNull(ori, GUARD_LINE);
2016-07-03 21:05:18 +01:00
Object * object = ObjectFactory::CreateObjectFromLegacyFile(ori->Path);
2016-06-25 16:34:35 +01:00
return object;
}
2016-07-04 00:05:39 +01:00
void RegisterLoadedObject(const ObjectRepositoryItem * ori, Object * object) override
{
ObjectRepositoryItem * item = &_items[ori->Id];
2016-07-16 14:17:36 +01:00
Guard::Assert(item->LoadedObject == nullptr, GUARD_LINE);
2016-07-04 00:05:39 +01:00
item->LoadedObject = object;
}
void UnregisterLoadedObject(const ObjectRepositoryItem * ori, Object * object) override
{
ObjectRepositoryItem * item = &_items[ori->Id];
if (item->LoadedObject == object)
{
item->LoadedObject = nullptr;
}
}
2016-06-26 23:30:44 +01:00
void AddObject(const rct_object_entry * objectEntry, const void * data, size_t dataSize) override
{
2016-07-09 15:24:00 +01:00
utf8 objectName[9];
object_entry_get_name_fixed(objectName, sizeof(objectName), objectEntry);
2016-06-26 23:30:44 +01:00
2016-07-09 14:52:56 +01:00
// Check that the object is loadable before writing it
Object * object = ObjectFactory::CreateObjectFromLegacyData(objectEntry, data, dataSize);
if (object == nullptr)
2016-06-26 23:30:44 +01:00
{
2016-07-09 15:02:05 +01:00
Console::Error::WriteLine("[%s] Unable to export object.", objectName);
2016-06-26 23:30:44 +01:00
}
2016-07-09 14:52:56 +01:00
else
2016-06-26 23:30:44 +01:00
{
2016-07-09 14:52:56 +01:00
utf8 path[MAX_PATH];
GetPathForNewObject(path, sizeof(path), objectName);
2016-07-10 16:34:54 +01:00
log_verbose("Adding object: [%s]", objectName);
2016-07-09 14:52:56 +01:00
try
{
SaveObject(path, objectEntry, data, dataSize);
ScanObject(path);
}
2016-11-30 23:32:47 +01:00
catch (const Exception &)
2016-07-09 14:52:56 +01:00
{
2016-07-10 16:34:54 +01:00
Console::Error::WriteLine("Failed saving object: [%s] to '%s'.", objectName, path);
2016-07-09 14:52:56 +01:00
}
2016-06-26 23:30:44 +01:00
}
}
2017-02-05 15:45:23 +00:00
void ExportPackedObject(IStream * stream) override
{
auto chunkReader = SawyerChunkReader(stream);
// Check if we already have this object
rct_object_entry entry = stream->ReadValue<rct_object_entry>();
if (FindObject(&entry) != nullptr)
{
chunkReader.SkipChunk();
}
else
{
// Read object and save to new file
std::shared_ptr<SawyerChunk> chunk = chunkReader.ReadChunk();
AddObject(&entry, chunk->GetData(), chunk->GetLength());
}
2017-02-05 15:45:23 +00:00
}
void WritePackedObjects(IStream * stream, std::vector<const ObjectRepositoryItem *> &objects) override
{
log_verbose("packing %u objects", objects.size());
for (const auto &object : objects)
{
Guard::ArgumentNotNull(object);
log_verbose("exporting object %.8s", object->ObjectEntry.name);
if (IsObjectCustom(object))
{
WritePackedObject(stream, &object->ObjectEntry);
}
else
{
log_warning("Refusing to pack vanilla/expansion object \"%s\"", object->ObjectEntry.name);
}
}
}
private:
2016-06-25 01:41:25 +01:00
void ClearItems()
{
for (uint32 i = 0; i < _items.size(); i++)
{
FreeItem(&_items[i]);
}
_items.clear();
2016-06-26 16:06:03 +01:00
_itemMap.clear();
2016-06-25 01:41:25 +01:00
}
void Query()
{
_queryDirectoryResult = { 0 };
const std::string &rct2Path = _env->GetDirectoryPath(DIRBASE::RCT2, DIRID::OBJECT);
const std::string &openrct2Path = _env->GetDirectoryPath(DIRBASE::USER, DIRID::OBJECT);
QueryDirectory(&_queryDirectoryResult, rct2Path);
QueryDirectory(&_queryDirectoryResult, openrct2Path);
}
void QueryDirectory(QueryDirectoryResult * result, const std::string &directory)
2016-06-25 01:41:25 +01:00
{
2016-06-28 00:16:35 +01:00
utf8 pattern[MAX_PATH];
String::Set(pattern, sizeof(pattern), directory.c_str());
2016-06-28 00:16:35 +01:00
Path::Append(pattern, sizeof(pattern), "*.dat");
2016-10-23 01:12:17 +01:00
Path::QueryDirectory(result, pattern);
2016-06-25 01:41:25 +01:00
}
void Scan()
{
2016-06-27 21:04:08 +01:00
Console::WriteLine("Scanning %lu objects...", _queryDirectoryResult.TotalFiles);
_numConflicts = 0;
2016-06-26 22:38:33 +01:00
2017-03-29 20:49:32 +01:00
auto startTime = std::chrono::high_resolution_clock::now();
2016-06-26 22:38:33 +01:00
2016-12-08 11:42:21 +00:00
const std::string &rct2Path = _env->GetDirectoryPath(DIRBASE::RCT2, DIRID::OBJECT);
2016-12-12 02:06:20 +00:00
const std::string &openrct2Path = _env->GetDirectoryPath(DIRBASE::USER, DIRID::OBJECT);
ScanDirectory(rct2Path);
ScanDirectory(openrct2Path);
2016-06-26 22:38:33 +01:00
2017-03-29 20:49:32 +01:00
auto endTime = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> duration = endTime - startTime;
Console::WriteLine("Scanning complete in %.2f seconds.", duration.count());
if (_numConflicts > 0)
{
Console::WriteLine("%d object conflicts found.", _numConflicts);
}
2016-06-25 01:41:25 +01:00
}
void ScanDirectory(const std::string &directory)
{
2016-06-28 00:16:35 +01:00
utf8 pattern[MAX_PATH];
String::Set(pattern, sizeof(pattern), directory.c_str());
2016-06-28 00:16:35 +01:00
Path::Append(pattern, sizeof(pattern), "*.dat");
2016-10-22 19:10:16 +01:00
IFileScanner * scanner = Path::ScanDirectory(pattern, true);
while (scanner->Next())
{
2016-10-22 19:10:16 +01:00
const utf8 * enumPath = scanner->GetPath();
2016-06-28 00:16:35 +01:00
ScanObject(enumPath);
}
2016-10-22 19:10:16 +01:00
delete scanner;
}
void ScanObject(const utf8 * path)
2016-06-25 01:41:25 +01:00
{
2016-06-25 12:30:20 +01:00
Object * object = ObjectFactory::CreateObjectFromLegacyFile(path);
if (object != nullptr)
2016-06-25 01:41:25 +01:00
{
2016-06-25 14:44:04 +01:00
ObjectRepositoryItem item = { 0 };
2016-06-29 21:34:59 +01:00
item.ObjectEntry = *object->GetObjectEntry();
2016-06-25 14:44:04 +01:00
item.Path = String::Duplicate(path);
item.Name = String::Duplicate(object->GetName());
2016-06-29 22:15:38 +01:00
object->SetRepositoryItem(&item);
2016-06-26 16:06:03 +01:00
AddItem(&item);
delete object;
2016-06-25 01:41:25 +01:00
}
}
bool Load()
{
2016-12-08 11:42:21 +00:00
const std::string &path = _env->GetFilePath(PATHID::CACHE_OBJECTS);
try
{
auto fs = FileStream(path, FILE_MODE_OPEN);
auto header = fs.ReadValue<ObjectRepositoryHeader>();
if (header.Version == OBJECT_REPOSITORY_VERSION &&
header.LanguageId == gCurrentLanguage &&
header.TotalFiles == _queryDirectoryResult.TotalFiles &&
header.TotalFileSize == _queryDirectoryResult.TotalFileSize &&
header.FileDateModifiedChecksum == _queryDirectoryResult.FileDateModifiedChecksum &&
header.PathChecksum == _queryDirectoryResult.PathChecksum)
{
// Header matches, so the index is not out of date
2016-07-07 19:17:09 +01:00
// Buffer the rest of file into memory to speed up item reading
size_t dataSize = (size_t)(fs.GetLength() - fs.GetPosition());
void * data = fs.ReadArray<uint8>(dataSize);
2017-02-05 02:40:16 +00:00
auto ms = MemoryStream(data, dataSize, MEMORY_ACCESS::READ | MEMORY_ACCESS::OWNER);
2016-07-07 19:17:09 +01:00
// Read items
for (uint32 i = 0; i < header.NumItems; i++)
{
2016-07-07 19:17:09 +01:00
ObjectRepositoryItem item = ReadItem(&ms);
2016-06-26 16:06:03 +01:00
AddItem(&item);
}
return true;
}
2016-06-26 22:38:33 +01:00
Console::WriteLine("Object repository is out of date.");
return false;
}
2016-11-30 23:32:47 +01:00
catch (const IOException &)
{
return false;
}
}
void Save() const
{
2016-12-08 11:42:21 +00:00
const std::string &path = _env->GetFilePath(PATHID::CACHE_OBJECTS);
try
{
auto fs = FileStream(path, FILE_MODE_WRITE);
// Write header
ObjectRepositoryHeader header;
header.Version = OBJECT_REPOSITORY_VERSION;
header.LanguageId = _languageId;
header.TotalFiles = _queryDirectoryResult.TotalFiles;
header.TotalFileSize = _queryDirectoryResult.TotalFileSize;
header.FileDateModifiedChecksum = _queryDirectoryResult.FileDateModifiedChecksum;
header.PathChecksum = _queryDirectoryResult.PathChecksum;
2016-08-27 23:32:15 +01:00
header.NumItems = (uint32)_items.size();
fs.WriteValue(header);
// Write items
for (uint32 i = 0; i < header.NumItems; i++)
{
2016-06-25 14:44:04 +01:00
WriteItem(&fs, _items[i]);
}
}
2016-11-30 23:32:47 +01:00
catch (const IOException &)
{
log_error("Unable to write object repository index to '%s'.", path.c_str());
}
}
2016-06-29 21:34:59 +01:00
void SortItems()
{
std::sort(_items.begin(), _items.end(), [](const ObjectRepositoryItem &a,
const ObjectRepositoryItem &b) -> bool
{
return strcmp(a.Name, b.Name) < 0;
});
// Rebuild item map
_itemMap.clear();
for (size_t i = 0; i < _items.size(); i++)
{
rct_object_entry entry = _items[i].ObjectEntry;
_itemMap[entry] = i;
}
}
bool AddItem(ObjectRepositoryItem * item)
2016-06-26 16:06:03 +01:00
{
2016-06-29 21:34:59 +01:00
const ObjectRepositoryItem * conflict = FindObject(&item->ObjectEntry);
if (conflict == nullptr)
{
2016-07-04 00:05:39 +01:00
size_t index = _items.size();
item->Id = index;
_items.push_back(*item);
2016-06-29 21:34:59 +01:00
_itemMap[item->ObjectEntry] = index;
return true;
}
else
{
_numConflicts++;
2016-07-09 15:02:05 +01:00
Console::Error::WriteLine("Object conflict: '%s'", conflict->Path);
Console::Error::WriteLine(" : '%s'", item->Path);
return false;
}
2016-06-26 16:06:03 +01:00
}
static ObjectRepositoryItem ReadItem(IStream * stream)
{
ObjectRepositoryItem item = { 0 };
2016-06-29 21:34:59 +01:00
item.ObjectEntry = stream->ReadValue<rct_object_entry>();
item.Path = stream->ReadString();
item.Name = stream->ReadString();
switch (item.ObjectEntry.flags & 0x0F) {
case OBJECT_TYPE_RIDE:
item.RideFlags = stream->ReadValue<uint8>();
2017-01-04 22:17:08 +01:00
for (sint32 i = 0; i < 2; i++)
{
item.RideCategory[i] = stream->ReadValue<uint8>();
}
for (sint32 i = 0; i < MAX_RIDE_TYPES_PER_RIDE_ENTRY; i++)
{
item.RideType[i] = stream->ReadValue<uint8>();
}
item.RideGroupIndex = stream->ReadValue<uint8>();
break;
case OBJECT_TYPE_SCENERY_SETS:
item.NumThemeObjects = stream->ReadValue<uint16>();
2016-06-29 21:34:59 +01:00
item.ThemeObjects = Memory::AllocateArray<rct_object_entry>(item.NumThemeObjects);
for (uint16 i = 0; i < item.NumThemeObjects; i++)
{
2016-06-29 21:34:59 +01:00
item.ThemeObjects[i] = stream->ReadValue<rct_object_entry>();
}
break;
}
return item;
}
static void WriteItem(IStream * stream, const ObjectRepositoryItem &item)
{
stream->WriteValue(item.ObjectEntry);
stream->WriteString(item.Path);
stream->WriteString(item.Name);
switch (item.ObjectEntry.flags & 0x0F) {
case OBJECT_TYPE_RIDE:
stream->WriteValue<uint8>(item.RideFlags);
2017-01-04 22:17:08 +01:00
for (sint32 i = 0; i < 2; i++)
{
stream->WriteValue<uint8>(item.RideCategory[i]);
}
for (sint32 i = 0; i < MAX_RIDE_TYPES_PER_RIDE_ENTRY; i++)
{
stream->WriteValue<uint8>(item.RideType[i]);
}
stream->WriteValue<uint8>(item.RideGroupIndex);
break;
case OBJECT_TYPE_SCENERY_SETS:
stream->WriteValue<uint16>(item.NumThemeObjects);
for (uint16 i = 0; i < item.NumThemeObjects; i++)
{
2016-06-29 21:34:59 +01:00
stream->WriteValue<rct_object_entry>(item.ThemeObjects[i]);
}
break;
}
}
static void FreeItem(ObjectRepositoryItem * item)
{
2016-06-25 14:44:04 +01:00
Memory::Free(item->Path);
Memory::Free(item->Name);
item->Path = nullptr;
item->Name = nullptr;
2016-07-08 21:47:20 +01:00
uint8 objectType = item->ObjectEntry.flags & 0x0F;
switch (objectType) {
case OBJECT_TYPE_SCENERY_SETS:
Memory::Free(item->ThemeObjects);
item->ThemeObjects = nullptr;
break;
}
}
2016-07-11 19:09:16 +01:00
static void SaveObject(const utf8 * path,
const rct_object_entry * entry,
const void * data, size_t dataSize,
bool fixChecksum = true)
2016-06-26 23:30:44 +01:00
{
2016-07-11 19:09:16 +01:00
if (fixChecksum)
{
2016-09-07 12:39:29 +00:00
uint32 realChecksum = object_calculate_checksum(entry, data, dataSize);
2016-07-11 19:09:16 +01:00
if (realChecksum != entry->checksum)
{
2016-07-11 19:09:16 +01:00
char objectName[9];
object_entry_get_name_fixed(objectName, sizeof(objectName), entry);
log_verbose("[%s] Incorrect checksum, adding salt bytes...", objectName);
// Calculate the value of extra bytes that can be appended to the data so that the
// data is then valid for the object's checksum
size_t extraBytesCount = 0;
void * extraBytes = CalculateExtraBytesToFixChecksum(realChecksum, entry->checksum, &extraBytesCount);
// Create new data blob with appended bytes
size_t newDataSize = dataSize + extraBytesCount;
void * newData = Memory::Allocate<void>(newDataSize);
void * newDataSaltOffset = (void *)((uintptr_t)newData + dataSize);
Memory::Copy(newData, data, dataSize);
Memory::Copy(newDataSaltOffset, extraBytes, extraBytesCount);
2016-07-11 19:09:16 +01:00
try
{
2016-09-07 12:39:29 +00:00
uint32 newRealChecksum = object_calculate_checksum(entry, newData, newDataSize);
2016-07-11 19:09:16 +01:00
if (newRealChecksum != entry->checksum)
{
Console::Error::WriteLine("CalculateExtraBytesToFixChecksum failed to fix checksum.");
2016-07-11 19:09:16 +01:00
// Save old data form
SaveObject(path, entry, data, dataSize, false);
}
else
{
// Save new data form
SaveObject(path, entry, newData, newDataSize, false);
}
Memory::Free(newData);
Memory::Free(extraBytes);
}
2016-11-30 23:32:47 +01:00
catch (const Exception &)
2016-07-11 19:09:16 +01:00
{
Memory::Free(newData);
Memory::Free(extraBytes);
throw;
}
return;
}
}
2016-07-11 19:09:16 +01:00
// Encode data
uint8 objectType = entry->flags & 0x0F;
sawyercoding_chunk_header chunkHeader;
chunkHeader.encoding = object_entry_group_encoding[objectType];
2016-08-27 23:32:15 +01:00
chunkHeader.length = (uint32)dataSize;
2016-07-11 19:09:16 +01:00
uint8 * encodedDataBuffer = Memory::Allocate<uint8>(0x600000);
size_t encodedDataSize = sawyercoding_write_chunk_buffer(encodedDataBuffer, (uint8 *)data, chunkHeader);
// Save to file
try
{
auto fs = FileStream(path, FILE_MODE_WRITE);
fs.Write(entry, sizeof(rct_object_entry));
fs.Write(encodedDataBuffer, encodedDataSize);
Memory::Free(encodedDataBuffer);
}
2016-11-30 23:32:47 +01:00
catch (const Exception &)
{
Memory::Free(encodedDataBuffer);
throw;
}
2016-06-26 23:30:44 +01:00
}
2017-01-04 22:17:08 +01:00
static void * CalculateExtraBytesToFixChecksum(sint32 currentChecksum, sint32 targetChecksum, size_t * outSize)
{
// Allocate 11 extra bytes to manipulate the checksum
uint8 * salt = Memory::Allocate<uint8>(11);
if (outSize != nullptr) *outSize = 11;
// Next work out which bits need to be flipped to make the current checksum match the one in the file
// The bitwise rotation compensates for the rotation performed during the checksum calculation*/
2017-01-04 22:17:08 +01:00
sint32 bitsToFlip = targetChecksum ^ ((currentChecksum << 25) | (currentChecksum >> 7));
// Each set bit encountered during encoding flips one bit of the resulting checksum (so each bit of the checksum is an
// XOR of bits from the file). Here, we take each bit that should be flipped in the checksum and set one of the bits in
// the data that maps to it. 11 bytes is the minimum needed to touch every bit of the checksum - with less than that,
// you wouldn't always be able to make the checksum come out to the desired target
salt[0] = (bitsToFlip & 0x00000001) << 7;
salt[1] = ((bitsToFlip & 0x00200000) >> 14);
salt[2] = ((bitsToFlip & 0x000007F8) >> 3);
salt[3] = ((bitsToFlip & 0xFF000000) >> 24);
salt[4] = ((bitsToFlip & 0x00100000) >> 13);
salt[5] = (bitsToFlip & 0x00000004) >> 2;
salt[6] = 0;
salt[7] = ((bitsToFlip & 0x000FF000) >> 12);
salt[8] = (bitsToFlip & 0x00000002) >> 1;
salt[9] = (bitsToFlip & 0x00C00000) >> 22;
salt[10] = (bitsToFlip & 0x00000800) >> 11;
return salt;
}
void GetPathForNewObject(utf8 * buffer, size_t bufferSize, const char * name)
2016-06-26 23:30:44 +01:00
{
char normalisedName[9] = { 0 };
2017-01-04 22:17:08 +01:00
for (sint32 i = 0; i < 8; i++)
2016-06-26 23:30:44 +01:00
{
if (name[i] != ' ')
{
normalisedName[i] = toupper(name[i]);
}
else
{
normalisedName[i] = '\0';
}
}
2016-12-08 11:42:21 +00:00
const std::string &userObjPath = _env->GetDirectoryPath(DIRBASE::USER, DIRID::OBJECT);
String::Set(buffer, bufferSize, userObjPath.c_str());
2016-06-27 22:23:09 +01:00
platform_ensure_directory_exists(buffer);
Path::Append(buffer, bufferSize, normalisedName);
String::Append(buffer, bufferSize, ".DAT");
2016-06-26 23:30:44 +01:00
2016-07-09 14:13:46 +01:00
uint32 counter = 2;
2016-06-26 23:30:44 +01:00
for (; platform_file_exists(buffer);)
{
2016-06-27 22:23:09 +01:00
utf8 counterString[8];
snprintf(counterString, sizeof(counterString), "-%02X", counter);
2016-07-09 14:13:46 +01:00
counter++;
2016-06-27 22:23:09 +01:00
String::Set(buffer, bufferSize, userObjPath.c_str());
2016-06-27 22:23:09 +01:00
Path::Append(buffer, bufferSize, normalisedName);
String::Append(buffer, bufferSize, counterString);
String::Append(buffer, bufferSize, ".DAT");
2016-06-26 23:30:44 +01:00
}
}
2017-02-05 15:45:23 +00:00
void WritePackedObject(IStream * stream, const rct_object_entry * entry)
{
const ObjectRepositoryItem * item = FindObject(entry);
if (item == nullptr)
{
throw Exception(String::StdFormat("Unable to find object '%.8s'", entry->name));
}
// Read object data from file
auto fs = FileStream(item->Path, FILE_MODE_OPEN);
auto fileEntry = fs.ReadValue<rct_object_entry>();
if (!object_entry_compare(entry, &fileEntry))
{
throw Exception("Header found in object file does not match object to pack.");
}
auto chunkReader = SawyerChunkReader(&fs);
auto chunk = chunkReader.ReadChunk();
// Write object data to stream
auto chunkWriter = SawyerChunkWriter(stream);
stream->WriteValue(*entry);
chunkWriter.WriteChunk(chunk.get());
}
};
static ObjectRepository * _objectRepository = nullptr;
IObjectRepository * CreateObjectRepository(IPlatformEnvironment * env)
{
_objectRepository = new ObjectRepository(env);
return _objectRepository;
}
IObjectRepository * GetObjectRepository()
{
return _objectRepository;
}
2016-06-25 01:41:25 +01:00
2017-02-05 15:45:23 +00:00
bool IsObjectCustom(const ObjectRepositoryItem * object)
{
Guard::ArgumentNotNull(object);
// Validate the object is not one from base game or expansion pack
return !(object->ObjectEntry.flags & 0xF0);
}
2016-06-25 01:41:25 +01:00
extern "C"
{
const rct_object_entry * object_list_find(rct_object_entry * entry)
2016-06-26 16:55:46 +01:00
{
const rct_object_entry * result = nullptr;
auto objRepo = GetObjectRepository();
auto item = objRepo->FindObject(entry);
if (item != nullptr)
{
result = &item->ObjectEntry;
}
return result;
2016-06-26 16:55:46 +01:00
}
const rct_object_entry * object_list_find_by_name(const char * name)
2016-06-26 16:55:46 +01:00
{
const rct_object_entry * result = nullptr;
auto objRepo = GetObjectRepository();
auto item = objRepo->FindObject(name);
if (item != nullptr)
{
result = &item->ObjectEntry;
}
return result;
2016-06-26 16:55:46 +01:00
}
2016-06-25 01:41:25 +01:00
void object_list_load()
{
IObjectRepository * objectRepository = GetObjectRepository();
objectRepository->LoadOrConstruct();
2016-07-09 22:37:22 +01:00
IObjectManager * objectManager = GetObjectManager();
objectManager->UnloadAll();
2016-06-25 01:41:25 +01:00
}
2016-06-25 16:34:35 +01:00
2016-06-30 21:55:18 +01:00
void * object_repository_load_object(const rct_object_entry * objectEntry)
{
2016-07-03 21:05:18 +01:00
Object * object = nullptr;
2016-06-30 21:55:18 +01:00
IObjectRepository * objRepository = GetObjectRepository();
2016-07-03 21:05:18 +01:00
const ObjectRepositoryItem * ori = objRepository->FindObject(objectEntry);
if (ori != nullptr)
{
object = objRepository->LoadObject(ori);
if (object != nullptr)
{
object->Load();
}
}
2016-07-02 11:35:46 +01:00
return (void *)object;
2016-07-02 21:52:17 +01:00
}
2016-06-25 16:34:35 +01:00
void scenario_translate(scenario_index_entry * scenarioEntry, const rct_object_entry * stexObjectEntry)
{
rct_string_id localisedStringIds[3];
if (language_get_localised_scenario_strings(scenarioEntry->name, localisedStringIds))
{
if (localisedStringIds[0] != STR_NONE)
{
String::Set(scenarioEntry->name, sizeof(scenarioEntry->name), language_get_string(localisedStringIds[0]));
}
if (localisedStringIds[2] != STR_NONE)
{
String::Set(scenarioEntry->details, sizeof(scenarioEntry->details), language_get_string(localisedStringIds[2]));
}
}
else
{
// Checks for a scenario string object (possibly for localisation)
if ((stexObjectEntry->flags & 0xFF) != 255)
{
2016-07-03 21:05:18 +01:00
IObjectRepository * objectRepository = GetObjectRepository();
const ObjectRepositoryItem * ori = objectRepository->FindObject(stexObjectEntry);
if (ori != nullptr)
2016-06-25 16:34:35 +01:00
{
2016-07-03 21:05:18 +01:00
Object * object = objectRepository->LoadObject(ori);
if (object != nullptr)
{
StexObject * stexObject = static_cast<StexObject*>(object);
const utf8 * scenarioName = stexObject->GetScenarioName();
const utf8 * scenarioDetails = stexObject->GetScenarioDetails();
2016-06-25 16:34:35 +01:00
2016-07-03 21:05:18 +01:00
String::Set(scenarioEntry->name, sizeof(scenarioEntry->name), scenarioName);
String::Set(scenarioEntry->details, sizeof(scenarioEntry->details), scenarioDetails);
2016-06-25 16:34:35 +01:00
2016-07-03 21:05:18 +01:00
delete object;
}
2016-06-25 16:34:35 +01:00
}
}
}
}
2016-06-26 23:30:44 +01:00
2016-06-28 23:24:49 +01:00
size_t object_repository_get_items_count()
{
IObjectRepository * objectRepository = GetObjectRepository();
return objectRepository->GetNumObjects();
}
const ObjectRepositoryItem * object_repository_get_items()
{
IObjectRepository * objectRepository = GetObjectRepository();
return objectRepository->GetObjects();
}
2016-06-30 21:07:32 +01:00
const ObjectRepositoryItem * object_repository_find_object_by_entry(const rct_object_entry * entry)
{
IObjectRepository * objectRepository = GetObjectRepository();
return objectRepository->FindObject(entry);
}
2016-06-30 21:55:18 +01:00
2016-07-02 21:52:17 +01:00
const ObjectRepositoryItem * object_repository_find_object_by_name(const char * name)
{
IObjectRepository * objectRepository = GetObjectRepository();
return objectRepository->FindObject(name);
}
2016-06-30 21:55:18 +01:00
void object_delete(void * object)
{
2016-07-02 18:01:51 +01:00
if (object != nullptr)
{
2016-11-30 23:32:47 +01:00
Object * baseObject = static_cast<Object *>(object);
2016-07-02 18:01:51 +01:00
baseObject->Unload();
delete baseObject;
}
2016-06-30 21:55:18 +01:00
}
const utf8 * object_get_description(const void * object)
{
2016-11-30 23:32:47 +01:00
const Object * baseObject = static_cast<const Object *>(object);
2016-06-30 21:55:18 +01:00
switch (baseObject->GetObjectType()) {
case OBJECT_TYPE_RIDE:
{
const RideObject * rideObject = static_cast<const RideObject *>(baseObject);
return rideObject->GetDescription();
}
case OBJECT_TYPE_SCENARIO_TEXT:
{
const StexObject * stexObject = static_cast<const StexObject *>(baseObject);
return stexObject->GetScenarioDetails();
}
default:
return "";
}
}
2016-07-02 10:59:50 +01:00
2016-07-11 22:50:55 +01:00
const utf8 * object_get_capacity(const void * object)
{
2016-11-30 23:32:47 +01:00
const Object * baseObject = static_cast<const Object *>(object);
2016-07-11 22:50:55 +01:00
switch (baseObject->GetObjectType()) {
case OBJECT_TYPE_RIDE:
{
auto rideObject = static_cast<const RideObject *>(baseObject);
return rideObject->GetCapacity();
}
default:
return "";
}
}
2016-07-11 22:09:15 +01:00
void object_draw_preview(const void * object, rct_drawpixelinfo * dpi, sint32 width, sint32 height)
2016-07-02 10:59:50 +01:00
{
2016-11-30 23:32:47 +01:00
const Object * baseObject = static_cast<const Object *>(object);
2016-07-11 22:09:15 +01:00
baseObject->DrawPreview(dpi, width, height);
2016-07-02 10:59:50 +01:00
}
2016-07-02 22:13:37 +01:00
bool object_entry_compare(const rct_object_entry * a, const rct_object_entry * b)
{
// If an official object don't bother checking checksum
if ((a->flags & 0xF0) || (b->flags & 0xF0))
{
if ((a->flags & 0x0F) != (b->flags & 0x0F))
{
return 0;
}
2017-01-04 22:17:08 +01:00
sint32 match = memcmp(a->name, b->name, 8);
2016-07-02 22:13:37 +01:00
if (match)
{
return 0;
}
}
else
{
if (a->flags != b->flags)
{
return 0;
}
2017-01-04 22:17:08 +01:00
sint32 match = memcmp(a->name, b->name, 8);
2016-07-02 22:13:37 +01:00
if (match)
{
return 0;
}
if (a->checksum != b->checksum)
{
return 0;
}
}
return 1;
}
2017-01-04 22:17:08 +01:00
sint32 object_calculate_checksum(const rct_object_entry * entry, const void * data, size_t dataLength)
2016-07-02 22:13:37 +01:00
{
2016-12-28 19:31:56 +01:00
const uint8 * entryBytePtr = (uint8 *)entry;
2016-07-02 22:13:37 +01:00
uint32 checksum = 0xF369A75B;
checksum ^= entryBytePtr[0];
checksum = rol32(checksum, 11);
2017-01-04 22:17:08 +01:00
for (sint32 i = 4; i < 12; i++)
2016-07-02 22:13:37 +01:00
{
checksum ^= entryBytePtr[i];
checksum = rol32(checksum, 11);
}
2016-12-28 19:31:56 +01:00
uint8 * dataBytes = (uint8 *)data;
const size_t dataLength32 = dataLength - (dataLength & 31);
for (size_t i = 0; i < 32; i++)
{
for (size_t j = i; j < dataLength32; j += 32)
{
checksum ^= dataBytes[j];
}
checksum = rol32(checksum, 11);
}
for (size_t i = dataLength32; i < dataLength; i++)
2016-07-02 22:13:37 +01:00
{
checksum ^= dataBytes[i];
checksum = rol32(checksum, 11);
}
2017-01-04 22:17:08 +01:00
return (sint32)checksum;
2016-07-02 22:13:37 +01:00
}
2016-06-25 01:41:25 +01:00
}