diff --git a/src/ObjCompiling/Game/IW3/ObjCompilerIW3.cpp b/src/ObjCompiling/Game/IW3/ObjCompilerIW3.cpp index 69c47261..02e34655 100644 --- a/src/ObjCompiling/Game/IW3/ObjCompilerIW3.cpp +++ b/src/ObjCompiling/Game/IW3/ObjCompilerIW3.cpp @@ -11,7 +11,7 @@ namespace { void ConfigureCompilers(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); // No compilers yet } @@ -23,7 +23,7 @@ namespace ZoneAssetCreationStateContainer& zoneStates, IOutputPath& outDir) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); if (ImageIwdPostProcessor::AppliesToZoneDefinition(zoneDefinition)) collection.AddAssetPostProcessor(std::make_unique>(zoneDefinition, searchPath, zoneStates, outDir)); diff --git a/src/ObjCompiling/Game/IW4/ObjCompilerIW4.cpp b/src/ObjCompiling/Game/IW4/ObjCompilerIW4.cpp index ed6b6963..9990d794 100644 --- a/src/ObjCompiling/Game/IW4/ObjCompilerIW4.cpp +++ b/src/ObjCompiling/Game/IW4/ObjCompilerIW4.cpp @@ -11,7 +11,7 @@ namespace { void ConfigureCompilers(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); // No compilers yet } @@ -23,7 +23,7 @@ namespace ZoneAssetCreationStateContainer& zoneStates, IOutputPath& outDir) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); if (ImageIwdPostProcessor::AppliesToZoneDefinition(zoneDefinition)) collection.AddAssetPostProcessor(std::make_unique>(zoneDefinition, searchPath, zoneStates, outDir)); diff --git a/src/ObjCompiling/Game/IW5/ObjCompilerIW5.cpp b/src/ObjCompiling/Game/IW5/ObjCompilerIW5.cpp index e9faf12e..fe02ead8 100644 --- a/src/ObjCompiling/Game/IW5/ObjCompilerIW5.cpp +++ b/src/ObjCompiling/Game/IW5/ObjCompilerIW5.cpp @@ -11,7 +11,7 @@ namespace { void ConfigureCompilers(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); // No compilers yet } @@ -23,7 +23,7 @@ namespace ZoneAssetCreationStateContainer& zoneStates, IOutputPath& outDir) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); if (ImageIwdPostProcessor::AppliesToZoneDefinition(zoneDefinition)) collection.AddAssetPostProcessor(std::make_unique>(zoneDefinition, searchPath, zoneStates, outDir)); diff --git a/src/ObjCompiling/Game/T5/ObjCompilerT5.cpp b/src/ObjCompiling/Game/T5/ObjCompilerT5.cpp index e08a010f..3ca4d416 100644 --- a/src/ObjCompiling/Game/T5/ObjCompilerT5.cpp +++ b/src/ObjCompiling/Game/T5/ObjCompilerT5.cpp @@ -11,7 +11,7 @@ namespace { void ConfigureCompilers(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); // No compilers yet } @@ -23,7 +23,7 @@ namespace ZoneAssetCreationStateContainer& zoneStates, IOutputPath& outDir) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); if (ImageIwdPostProcessor::AppliesToZoneDefinition(zoneDefinition)) collection.AddAssetPostProcessor(std::make_unique>(zoneDefinition, searchPath, zoneStates, outDir)); diff --git a/src/ObjCompiling/Game/T6/ObjCompilerT6.cpp b/src/ObjCompiling/Game/T6/ObjCompilerT6.cpp index 5052d5ab..eae90387 100644 --- a/src/ObjCompiling/Game/T6/ObjCompilerT6.cpp +++ b/src/ObjCompiling/Game/T6/ObjCompilerT6.cpp @@ -17,7 +17,7 @@ namespace ISearchPath& searchPath, ZoneAssetCreationStateContainer& zoneStates) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); collection.AddAssetCreator(CreateKeyValuePairsCompiler(memory, zone, zoneDefinition.m_zone_definition, zoneStates)); } @@ -29,7 +29,7 @@ namespace ZoneAssetCreationStateContainer& zoneStates, IOutputPath& outDir) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); if (ImageIPakPostProcessor::AppliesToZoneDefinition(zoneDefinition)) collection.AddAssetPostProcessor(std::make_unique>(zoneDefinition, searchPath, zoneStates, outDir)); diff --git a/src/ObjLoading/Game/IW3/ObjLoaderIW3.cpp b/src/ObjLoading/Game/IW3/ObjLoaderIW3.cpp index 8658c73e..eeb2d3a8 100644 --- a/src/ObjLoading/Game/IW3/ObjLoaderIW3.cpp +++ b/src/ObjLoading/Game/IW3/ObjLoaderIW3.cpp @@ -21,7 +21,7 @@ namespace { void ConfigureDefaultCreators(AssetCreatorCollection& collection, Zone& zone) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); collection.AddDefaultAssetCreator(std::make_unique>(memory)); collection.AddDefaultAssetCreator(std::make_unique>(memory)); @@ -85,7 +85,7 @@ namespace void ConfigureLoaders(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); // collection.AddAssetCreator(std::make_unique(memory)); // collection.AddAssetCreator(std::make_unique(memory)); diff --git a/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.cpp b/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.cpp index 68d9ebe8..ade6a824 100644 --- a/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.cpp +++ b/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.cpp @@ -12,10 +12,10 @@ MenuConversionZoneState::MenuConversionZoneState() void MenuConversionZoneState::Inject(ZoneAssetCreationInjection& inject) { - auto* memory = inject.m_zone.GetMemory(); + auto& memory = inject.m_zone.Memory(); m_zone = &inject.m_zone; - m_supporting_data = memory->Alloc(); + m_supporting_data = memory.Alloc(); } Statement_s* MenuConversionZoneState::FindFunction(const std::string& functionName) @@ -43,10 +43,10 @@ size_t MenuConversionZoneState::AddStaticDvar(const std::string& dvarName) if (foundDvar != m_dvars_by_name.end()) return foundDvar->second; - auto* memory = m_zone->GetMemory(); - auto* staticDvar = memory->Alloc(); + auto& memory = m_zone->Memory(); + auto* staticDvar = memory.Alloc(); - staticDvar->dvarName = memory->Dup(dvarName.c_str()); + staticDvar->dvarName = memory.Dup(dvarName.c_str()); staticDvar->dvar = nullptr; const auto staticDvarIndex = m_static_dvars.size(); @@ -63,8 +63,8 @@ const char* MenuConversionZoneState::AddString(const std::string& str) if (foundString != m_strings_by_value.end()) return foundString->second; - auto* memory = m_zone->GetMemory(); - const auto* strDuped = memory->Dup(str.c_str()); + auto& memory = m_zone->Memory(); + const auto* strDuped = memory.Dup(str.c_str()); m_strings.push_back(strDuped); m_strings_by_value.emplace(std::make_pair(str, strDuped)); @@ -79,24 +79,24 @@ void MenuConversionZoneState::AddLoadedFile(std::string loadedFileName, std::vec void MenuConversionZoneState::FinalizeSupportingData() const { - auto* memory = m_zone->GetMemory(); + auto& memory = m_zone->Memory(); m_supporting_data->uifunctions.totalFunctions = static_cast(m_functions.size()); m_supporting_data->staticDvarList.numStaticDvars = static_cast(m_static_dvars.size()); m_supporting_data->uiStrings.totalStrings = static_cast(m_strings.size()); if (m_supporting_data->uifunctions.functions) - memory->Free(m_supporting_data->uifunctions.functions); + memory.Free(m_supporting_data->uifunctions.functions); if (m_supporting_data->staticDvarList.staticDvars) - memory->Free(m_supporting_data->staticDvarList.staticDvars); + memory.Free(m_supporting_data->staticDvarList.staticDvars); if (m_supporting_data->uiStrings.strings) - memory->Free(m_supporting_data->uiStrings.strings); + memory.Free(m_supporting_data->uiStrings.strings); if (!m_functions.empty()) { - m_supporting_data->uifunctions.functions = memory->Alloc(m_functions.size()); + m_supporting_data->uifunctions.functions = memory.Alloc(m_functions.size()); memcpy(m_supporting_data->uifunctions.functions, m_functions.data(), sizeof(void*) * m_functions.size()); } else @@ -104,7 +104,7 @@ void MenuConversionZoneState::FinalizeSupportingData() const if (!m_static_dvars.empty()) { - m_supporting_data->staticDvarList.staticDvars = memory->Alloc(m_static_dvars.size()); + m_supporting_data->staticDvarList.staticDvars = memory.Alloc(m_static_dvars.size()); memcpy(m_supporting_data->staticDvarList.staticDvars, m_static_dvars.data(), sizeof(void*) * m_static_dvars.size()); } else @@ -112,7 +112,7 @@ void MenuConversionZoneState::FinalizeSupportingData() const if (!m_strings.empty()) { - m_supporting_data->uiStrings.strings = memory->Alloc(m_strings.size()); + m_supporting_data->uiStrings.strings = memory.Alloc(m_strings.size()); memcpy(m_supporting_data->uiStrings.strings, m_strings.data(), sizeof(void*) * m_strings.size()); } else diff --git a/src/ObjLoading/Game/IW4/ObjLoaderIW4.cpp b/src/ObjLoading/Game/IW4/ObjLoaderIW4.cpp index d3fc0d40..c124a7f9 100644 --- a/src/ObjLoading/Game/IW4/ObjLoaderIW4.cpp +++ b/src/ObjLoading/Game/IW4/ObjLoaderIW4.cpp @@ -34,7 +34,7 @@ namespace { void ConfigureDefaultCreators(AssetCreatorCollection& collection, Zone& zone) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); collection.AddDefaultAssetCreator(std::make_unique>(memory)); collection.AddDefaultAssetCreator(std::make_unique>(memory)); @@ -118,7 +118,7 @@ namespace void ConfigureLoaders(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath, IGdtQueryable& gdt) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); collection.AddAssetCreator(std::make_unique(memory, searchPath, zone)); collection.AddAssetCreator(std::make_unique(memory, gdt, zone)); diff --git a/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.cpp b/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.cpp index 58234579..ef55af7c 100644 --- a/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.cpp +++ b/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.cpp @@ -12,10 +12,10 @@ MenuConversionZoneState::MenuConversionZoneState() void MenuConversionZoneState::Inject(ZoneAssetCreationInjection& inject) { - auto* memory = inject.m_zone.GetMemory(); + auto& memory = inject.m_zone.Memory(); m_zone = &inject.m_zone; - m_supporting_data = memory->Alloc(); + m_supporting_data = memory.Alloc(); } Statement_s* MenuConversionZoneState::FindFunction(const std::string& functionName) @@ -43,10 +43,10 @@ size_t MenuConversionZoneState::AddStaticDvar(const std::string& dvarName) if (foundDvar != m_dvars_by_name.end()) return foundDvar->second; - auto* memory = m_zone->GetMemory(); - auto* staticDvar = memory->Alloc(); + auto& memory = m_zone->Memory(); + auto* staticDvar = memory.Alloc(); - staticDvar->dvarName = memory->Dup(dvarName.c_str()); + staticDvar->dvarName = memory.Dup(dvarName.c_str()); staticDvar->dvar = nullptr; const auto staticDvarIndex = m_static_dvars.size(); @@ -63,8 +63,8 @@ const char* MenuConversionZoneState::AddString(const std::string& str) if (foundString != m_strings_by_value.end()) return foundString->second; - auto* memory = m_zone->GetMemory(); - const auto* strDuped = memory->Dup(str.c_str()); + auto& memory = m_zone->Memory(); + const auto* strDuped = memory.Dup(str.c_str()); m_strings.push_back(strDuped); m_strings_by_value.emplace(std::make_pair(str, strDuped)); @@ -79,24 +79,24 @@ void MenuConversionZoneState::AddLoadedFile(std::string loadedFileName, std::vec void MenuConversionZoneState::FinalizeSupportingData() const { - auto* memory = m_zone->GetMemory(); + auto& memory = m_zone->Memory(); m_supporting_data->uifunctions.totalFunctions = static_cast(m_functions.size()); m_supporting_data->staticDvarList.numStaticDvars = static_cast(m_static_dvars.size()); m_supporting_data->uiStrings.totalStrings = static_cast(m_strings.size()); if (m_supporting_data->uifunctions.functions) - memory->Free(m_supporting_data->uifunctions.functions); + memory.Free(m_supporting_data->uifunctions.functions); if (m_supporting_data->staticDvarList.staticDvars) - memory->Free(m_supporting_data->staticDvarList.staticDvars); + memory.Free(m_supporting_data->staticDvarList.staticDvars); if (m_supporting_data->uiStrings.strings) - memory->Free(m_supporting_data->uiStrings.strings); + memory.Free(m_supporting_data->uiStrings.strings); if (!m_functions.empty()) { - m_supporting_data->uifunctions.functions = memory->Alloc(m_functions.size()); + m_supporting_data->uifunctions.functions = memory.Alloc(m_functions.size()); memcpy(m_supporting_data->uifunctions.functions, m_functions.data(), sizeof(void*) * m_functions.size()); } else @@ -104,7 +104,7 @@ void MenuConversionZoneState::FinalizeSupportingData() const if (!m_static_dvars.empty()) { - m_supporting_data->staticDvarList.staticDvars = memory->Alloc(m_static_dvars.size()); + m_supporting_data->staticDvarList.staticDvars = memory.Alloc(m_static_dvars.size()); memcpy(m_supporting_data->staticDvarList.staticDvars, m_static_dvars.data(), sizeof(void*) * m_static_dvars.size()); } else @@ -112,7 +112,7 @@ void MenuConversionZoneState::FinalizeSupportingData() const if (!m_strings.empty()) { - m_supporting_data->uiStrings.strings = memory->Alloc(m_strings.size()); + m_supporting_data->uiStrings.strings = memory.Alloc(m_strings.size()); memcpy(m_supporting_data->uiStrings.strings, m_strings.data(), sizeof(void*) * m_strings.size()); } else diff --git a/src/ObjLoading/Game/IW5/ObjLoaderIW5.cpp b/src/ObjLoading/Game/IW5/ObjLoaderIW5.cpp index 49aad040..4755450f 100644 --- a/src/ObjLoading/Game/IW5/ObjLoaderIW5.cpp +++ b/src/ObjLoading/Game/IW5/ObjLoaderIW5.cpp @@ -29,7 +29,7 @@ namespace { void ConfigureDefaultCreators(AssetCreatorCollection& collection, Zone& zone) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); collection.AddDefaultAssetCreator(std::make_unique>(memory)); collection.AddDefaultAssetCreator(std::make_unique>(memory)); @@ -119,7 +119,7 @@ namespace void ConfigureLoaders(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath, IGdtQueryable& gdt) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); // collection.AddAssetCreator(std::make_unique(memory)); // collection.AddAssetCreator(std::make_unique(memory)); diff --git a/src/ObjLoading/Game/T5/ObjLoaderT5.cpp b/src/ObjLoading/Game/T5/ObjLoaderT5.cpp index 8f317d2c..1f4d8132 100644 --- a/src/ObjLoading/Game/T5/ObjLoaderT5.cpp +++ b/src/ObjLoading/Game/T5/ObjLoaderT5.cpp @@ -21,7 +21,7 @@ namespace { void ConfigureDefaultCreators(AssetCreatorCollection& collection, Zone& zone) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); collection.AddDefaultAssetCreator(std::make_unique>(memory)); collection.AddDefaultAssetCreator(std::make_unique>(memory)); @@ -97,7 +97,7 @@ namespace void ConfigureLoaders(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); // collection.AddAssetCreator(std::make_unique(memory)); // collection.AddAssetCreator(std::make_unique(memory)); diff --git a/src/ObjLoading/Game/T6/ObjLoaderT6.cpp b/src/ObjLoading/Game/T6/ObjLoaderT6.cpp index 9853b1ef..37afdf89 100644 --- a/src/ObjLoading/Game/T6/ObjLoaderT6.cpp +++ b/src/ObjLoading/Game/T6/ObjLoaderT6.cpp @@ -284,7 +284,7 @@ namespace T6 { void ConfigureDefaultCreators(AssetCreatorCollection& collection, Zone& zone) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); collection.AddDefaultAssetCreator(std::make_unique>(memory)); collection.AddDefaultAssetCreator(std::make_unique>(memory)); @@ -390,7 +390,7 @@ namespace T6 void ConfigureLoaders(AssetCreatorCollection& collection, Zone& zone, ISearchPath& searchPath, IGdtQueryable& gdt) { - auto& memory = *zone.GetMemory(); + auto& memory = zone.Memory(); collection.AddAssetCreator(CreateRawPhysPresetLoader(memory, searchPath, zone)); collection.AddAssetCreator(CreateGdtPhysPresetLoader(memory, searchPath, gdt, zone)); diff --git a/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.cpp b/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.cpp index 347febe4..2b1d9bc6 100644 --- a/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.cpp @@ -27,7 +27,7 @@ void CodeGenerator::SetupTemplates() m_template_mapping["assetstructtests"] = std::make_unique(); } -bool CodeGenerator::GenerateCodeForTemplate(RenderingContext* context, ICodeTemplate* codeTemplate) const +bool CodeGenerator::GenerateCodeForTemplate(const RenderingContext& context, ICodeTemplate* codeTemplate) const { for (const auto& codeFile : codeTemplate->GetFilesToRender(context)) { @@ -110,7 +110,7 @@ bool CodeGenerator::GenerateCode(IDataRepository* repository) for (auto* asset : assets) { auto context = RenderingContext::BuildContext(repository, asset); - if (!GenerateCodeForTemplate(context.get(), foundTemplate->second.get())) + if (!GenerateCodeForTemplate(*context, foundTemplate->second.get())) { std::cerr << std::format( "Failed to generate code for asset '{}' with preset '{}'\n", asset->m_definition->GetFullName(), foundTemplate->first); @@ -128,7 +128,7 @@ bool CodeGenerator::GenerateCode(IDataRepository* repository) return false; auto context = RenderingContext::BuildContext(repository, asset); - if (!GenerateCodeForTemplate(context.get(), foundTemplate->second.get())) + if (!GenerateCodeForTemplate(*context, foundTemplate->second.get())) return false; } } diff --git a/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.h b/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.h index b05bd382..c1b45b7d 100644 --- a/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.h +++ b/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.h @@ -17,7 +17,7 @@ public: private: void SetupTemplates(); - bool GenerateCodeForTemplate(RenderingContext* context, ICodeTemplate* codeTemplate) const; + bool GenerateCodeForTemplate(const RenderingContext& context, ICodeTemplate* codeTemplate) const; static bool GetAssetWithName(IDataRepository* repository, const std::string& name, StructureInformation*& asset); const ZoneCodeGeneratorArguments* m_args; diff --git a/src/ZoneCodeGeneratorLib/Generating/ICodeTemplate.h b/src/ZoneCodeGeneratorLib/Generating/ICodeTemplate.h index 833d9900..4c1c9992 100644 --- a/src/ZoneCodeGeneratorLib/Generating/ICodeTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/ICodeTemplate.h @@ -29,6 +29,6 @@ public: ICodeTemplate& operator=(const ICodeTemplate& other) = default; ICodeTemplate& operator=(ICodeTemplate&& other) noexcept = default; - virtual std::vector GetFilesToRender(RenderingContext* context) = 0; - virtual void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) = 0; + virtual std::vector GetFilesToRender(const RenderingContext& context) = 0; + virtual void RenderFile(std::ostream& stream, int fileTag, const RenderingContext& context) = 0; }; diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp index 1646dcbb..3237a9f6 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp @@ -2,18 +2,19 @@ #include "Domain/Computations/StructureComputations.h" #include "Internal/BaseTemplate.h" +#include "Utils/StringUtils.h" -#include -#include +#include +#include namespace { - static constexpr int TAG_SOURCE = 1; + constexpr int TAG_SOURCE = 1; class Template final : BaseTemplate { public: - Template(std::ostream& stream, RenderingContext* context) + Template(std::ostream& stream, const RenderingContext& context) : BaseTemplate(stream, context) { } @@ -26,21 +27,22 @@ namespace LINE("// Any changes will be discarded when regenerating.") LINE("// ====================================================================") LINE("") + LINEF("#include \"Game/{0}/{0}.h\"", m_env.m_game) + LINE("") LINE("#include ") LINE("#include ") LINE("#include ") - LINE("#include \"Game/" << m_env.m_game << "/" << m_env.m_game << ".h\"") LINE("") - LINE("using namespace " << m_env.m_game << ";") + LINEF("using namespace {0};", m_env.m_game) LINE("") - LINE("namespace game::" << m_env.m_game << "::xassets::asset_" << Lower(m_env.m_asset->m_definition->m_name)) + LINEF("namespace game::{0}::xassets::asset_{1}", m_env.m_game, Lower(m_env.m_asset->m_definition->m_name)) LINE("{") m_intendation++; if (m_env.m_asset->m_has_matching_cross_platform_structure) TestMethod(m_env.m_asset); - for (auto* structure : m_env.m_used_structures) + for (const auto* structure : m_env.m_used_structures) { StructureComputations computations(structure->m_info); if (!structure->m_info->m_definition->m_anonymous && !computations.IsAsset() && structure->m_info->m_has_matching_cross_platform_structure) @@ -52,10 +54,12 @@ namespace } private: - void TestMethod(StructureInformation* structure) + void TestMethod(const StructureInformation* structure) { - LINE("TEST_CASE(\"" << m_env.m_game << "::" << m_env.m_asset->m_definition->GetFullName() << ": Tests for " - << structure->m_definition->GetFullName() << "\", \"[assetstruct]\")") + LINEF("TEST_CASE(\"{0}::{1}: Tests for {2}\", \"[assetstruct]\")", + m_env.m_game, + m_env.m_asset->m_definition->GetFullName(), + structure->m_definition->GetFullName()) LINE("{") m_intendation++; @@ -63,44 +67,37 @@ namespace { if (!member->m_member->m_name.empty() && !member->m_member->m_type_declaration->m_has_custom_bit_size) { - LINE("REQUIRE(offsetof(" << structure->m_definition->GetFullName() << ", " << member->m_member->m_name - << ") == " << member->m_member->m_offset << ");") + LINEF("REQUIRE(offsetof({0}, {1}) == {2});", structure->m_definition->GetFullName(), member->m_member->m_name, member->m_member->m_offset) } } LINE("") - LINE("REQUIRE(" << structure->m_definition->GetSize() << "u == sizeof(" << structure->m_definition->GetFullName() << "));") - LINE("REQUIRE(" << structure->m_definition->GetAlignment() << "u == alignof(" << structure->m_definition->GetFullName() << "));") + LINEF("REQUIRE({0}u == sizeof({1}));", structure->m_definition->GetSize(), structure->m_definition->GetFullName()) + LINEF("REQUIRE({0}u == alignof({1}));", structure->m_definition->GetAlignment(), structure->m_definition->GetFullName()) m_intendation--; LINE("}") } }; } // namespace -std::vector AssetStructTestsTemplate::GetFilesToRender(RenderingContext* context) +std::vector AssetStructTestsTemplate::GetFilesToRender(const RenderingContext& context) { std::vector files; - auto assetName = context->m_asset->m_definition->m_name; - for (auto& c : assetName) - c = static_cast(tolower(c)); + auto assetName = context.m_asset->m_definition->m_name; + utils::MakeStringLowerCase(assetName); - { - std::ostringstream str; - str << assetName << '/' << assetName << "_struct_test.cpp"; - files.emplace_back(str.str(), TAG_SOURCE); - } + files.emplace_back(std::format("{0}/{0}_struct_test.cpp", assetName), TAG_SOURCE); return files; } -void AssetStructTestsTemplate::RenderFile(std::ostream& stream, const int fileTag, RenderingContext* context) +void AssetStructTestsTemplate::RenderFile(std::ostream& stream, const int fileTag, const RenderingContext& context) { Template t(stream, context); + assert(fileTag == TAG_SOURCE); if (fileTag == TAG_SOURCE) t.Source(); - else - std::cout << "Invalid tag in AssetStructTestsTemplate\n"; } diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.h index 3a0f1879..9713927a 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.h @@ -4,6 +4,6 @@ class AssetStructTestsTemplate final : public ICodeTemplate { public: - std::vector GetFilesToRender(RenderingContext* context) override; - void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) override; + std::vector GetFilesToRender(const RenderingContext& context) override; + void RenderFile(std::ostream& stream, int fileTag, const RenderingContext& context) override; }; diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.cpp index eb72f0fd..6513a060 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.cpp @@ -5,9 +5,9 @@ #include -BaseTemplate::BaseTemplate(std::ostream& stream, RenderingContext* context) +BaseTemplate::BaseTemplate(std::ostream& stream, const RenderingContext& context) : m_out(stream), - m_env(*context), + m_env(context), m_intendation(0u) { } diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.h index c95fd764..5818957d 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.h @@ -15,7 +15,7 @@ class BaseTemplate protected: static constexpr auto INTENDATION = " "; - BaseTemplate(std::ostream& stream, RenderingContext* context); + BaseTemplate(std::ostream& stream, const RenderingContext& context); void DoIntendation() const; @@ -41,7 +41,7 @@ protected: static std::string MakeEvaluation(const IEvaluation* evaluation); std::ostream& m_out; - RenderingContext& m_env; + const RenderingContext& m_env; unsigned m_intendation; private: diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.cpp index 8d3a4fb8..87181ba2 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.cpp @@ -6,7 +6,6 @@ #include "Utils/StringUtils.h" #include -#include #include namespace @@ -17,7 +16,7 @@ namespace class Template final : BaseTemplate { public: - Template(std::ostream& stream, RenderingContext* context) + Template(std::ostream& stream, const RenderingContext& context) : BaseTemplate(stream, context) { } @@ -32,12 +31,13 @@ namespace LINE("") LINE("#pragma once") LINE("") - LINE("#include \"Loading/AssetLoader.h\"") LINEF("#include \"Game/{0}/{0}.h\"", m_env.m_game) if (m_env.m_has_actions) { LINEF("#include \"Game/{0}/XAssets/{1}/{1}_actions.h\"", m_env.m_game, Lower(m_env.m_asset->m_definition->m_name)) } + LINE("#include \"Loading/AssetLoader.h\"") + LINE("") LINE("#include ") LINE("") LINEF("namespace {0}", m_env.m_game) @@ -47,32 +47,16 @@ namespace LINE("{") m_intendation++; - LINEF("XAssetInfo<{0}>* m_asset_info;", m_env.m_asset->m_definition->GetFullName()) - if (m_env.m_has_actions) - { - LINEF("Actions_{0} m_actions;", m_env.m_asset->m_definition->m_name) - } - LINE(VariableDecl(m_env.m_asset->m_definition)) - LINE(PointerVariableDecl(m_env.m_asset->m_definition)) - LINE("") - - // Variable Declarations: type varType; - for (const auto* type : m_env.m_used_types) - { - if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - LINE(VariableDecl(type->m_type)) - } - } - for (const auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) - { - LINE(PointerVariableDecl(type->m_type)) - } - } + m_intendation--; + LINE("public:") + m_intendation++; + PrintHeaderConstructor(); + PrintHeaderMainLoadMethodDeclaration(m_env.m_asset); LINE("") + m_intendation--; + LINE("private:") + m_intendation++; // Method Declarations for (const auto* type : m_env.m_used_types) @@ -100,11 +84,31 @@ namespace PrintHeaderTempPtrLoadMethodDeclaration(m_env.m_asset); PrintHeaderAssetLoadMethodDeclaration(m_env.m_asset); LINE("") - m_intendation--; - LINE("public:") - m_intendation++; - PrintHeaderConstructor(); - PrintHeaderMainLoadMethodDeclaration(m_env.m_asset); + + LINEF("XAssetInfo<{0}>* m_asset_info;", m_env.m_asset->m_definition->GetFullName()) + if (m_env.m_has_actions) + { + LINEF("Actions_{0} m_actions;", m_env.m_asset->m_definition->m_name) + } + LINE(VariableDecl(m_env.m_asset->m_definition)) + LINE(PointerVariableDecl(m_env.m_asset->m_definition)) + LINE("") + + // Variable Declarations: type varType; + for (const auto* type : m_env.m_used_types) + { + if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) + { + LINE(VariableDecl(type->m_type)) + } + } + for (const auto* type : m_env.m_used_types) + { + if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) + { + LINE(PointerVariableDecl(type->m_type)) + } + } m_intendation--; LINE("};") @@ -121,23 +125,29 @@ namespace LINE("// ====================================================================") LINE("") LINEF("#include \"{0}_load_db.h\"", Lower(m_env.m_asset->m_definition->m_name)) - LINEF("#include \"{0}_mark_db.h\"", Lower(m_env.m_asset->m_definition->m_name)) - LINE("#include ") - LINE("#include ") LINE("") + LINEF("#include \"{0}_mark_db.h\"", Lower(m_env.m_asset->m_definition->m_name)) if (!m_env.m_referenced_assets.empty()) { + LINE("") LINE("// Referenced Assets:") for (const auto* type : m_env.m_referenced_assets) { LINEF("#include \"../{0}/{0}_load_db.h\"", Lower(type->m_type->m_name)) } - LINE("") } + + LINE("") + LINE("#include ") + LINE("#include ") + + LINE("") LINEF("using namespace {0};", m_env.m_game) LINE("") PrintConstructorMethod(); + LINE("") + PrintMainLoadMethod(); for (const auto* type : m_env.m_used_types) { @@ -169,8 +179,6 @@ namespace PrintLoadPtrMethod(m_env.m_asset); LINE("") PrintLoadAssetMethod(m_env.m_asset); - LINE("") - PrintMainLoadMethod(); } private: @@ -236,7 +244,7 @@ namespace void PrintHeaderConstructor() const { - LINEF("{0}(Zone* zone, IZoneInputStream* stream);", LoaderClassName(m_env.m_asset)) + LINEF("{0}(Zone& zone, ZoneInputStream& stream);", LoaderClassName(m_env.m_asset)) } void PrintVariableInitialization(const DataDefinition* def) const @@ -251,7 +259,7 @@ namespace void PrintConstructorMethod() { - LINEF("{0}::{0}(Zone* zone, IZoneInputStream* stream)", LoaderClassName(m_env.m_asset)) + LINEF("{0}::{0}(Zone& zone, ZoneInputStream& stream)", LoaderClassName(m_env.m_asset)) m_intendation++; LINE_STARTF(": AssetLoader({0}::EnumEntry, zone, stream)", m_env.m_asset->m_asset_name) @@ -304,7 +312,7 @@ namespace } } - void PrintLoadPtrArrayMethod_PointerCheck(const DataDefinition* def, StructureInformation* info, const bool reusable) + void PrintLoadPtrArrayMethod_PointerCheck(const DataDefinition* def, const StructureInformation* info, const bool reusable) { LINEF("if (*{0})", MakeTypePtrVarName(def)) LINE("{") @@ -312,7 +320,7 @@ namespace if (info && StructureComputations(info).IsAsset()) { - LINEF("{0} loader(m_zone, m_stream);", LoaderClassName(info)) + LINEF("{0} loader(m_zone, *m_stream);", LoaderClassName(info)) LINEF("loader.Load({0});", MakeTypePtrVarName(def)) } else @@ -346,7 +354,7 @@ namespace LINE("}") } - void PrintLoadPtrArrayMethod(const DataDefinition* def, StructureInformation* info, const bool reusable) + void PrintLoadPtrArrayMethod(const DataDefinition* def, const StructureInformation* info, const bool reusable) { LINEF("void {0}::LoadPtrArray_{1}(const bool atStreamStart, const size_t count)", LoaderClassName(m_env.m_asset), MakeSafeTypeName(def)) LINE("{") @@ -362,7 +370,7 @@ namespace LINE("") LINEF("{0}** var = {1};", def->GetFullName(), MakeTypePtrVarName(def)) - LINE("for(size_t index = 0; index < count; index++)") + LINE("for (size_t index = 0; index < count; index++)") LINE("{") m_intendation++; @@ -392,7 +400,7 @@ namespace LINE("") LINEF("{0}* var = {1};", def->GetFullName(), MakeTypeVarName(def)) - LINE("for(size_t index = 0; index < count; index++)") + LINE("for (size_t index = 0; index < count; index++)") LINE("{") m_intendation++; @@ -414,7 +422,7 @@ namespace { if (loadType == MemberLoadType::SINGLE_POINTER) { - LINEF("{0} loader(m_zone, m_stream);", LoaderClassName(member->m_type)) + LINEF("{0} loader(m_zone, *m_stream);", LoaderClassName(member->m_type)) LINEF("loader.Load(&{0});", MakeMemberAccess(info, member, modifier)) } else if (loadType == MemberLoadType::POINTER_ARRAY) @@ -899,7 +907,7 @@ namespace } } - void LoadMember_ReferenceArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) + void LoadMember_ReferenceArray(const StructureInformation* info, const MemberInformation* member, const DeclarationModifierComputations& modifier) { auto first = true; for (const auto& entry : modifier.GetArrayEntries()) @@ -917,7 +925,7 @@ namespace } } - void LoadMember_Reference(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) + void LoadMember_Reference(const StructureInformation* info, const MemberInformation* member, const DeclarationModifierComputations& modifier) { if (modifier.IsDynamicArray()) { @@ -954,7 +962,7 @@ namespace } } - void LoadMember_Condition_Struct(StructureInformation* info, MemberInformation* member) + void LoadMember_Condition_Struct(const StructureInformation* info, const MemberInformation* member) { LINE("") if (member->m_condition) @@ -974,7 +982,7 @@ namespace } } - void LoadMember_Condition_Union(StructureInformation* info, MemberInformation* member) + void LoadMember_Condition_Union(const StructureInformation* info, const MemberInformation* member) { const MemberComputations computations(member); @@ -1042,7 +1050,7 @@ namespace } } - void PrintLoadMemberIfNeedsTreatment(StructureInformation* info, MemberInformation* member) + void PrintLoadMemberIfNeedsTreatment(const StructureInformation* info, const MemberInformation* member) { const MemberComputations computations(member); if (computations.ShouldIgnore()) @@ -1058,7 +1066,7 @@ namespace } } - void PrintLoadMethod(StructureInformation* info) + void PrintLoadMethod(const StructureInformation* info) { const StructureComputations computations(info); LINEF("void {0}::Load_{1}(const bool atStreamStart)", LoaderClassName(m_env.m_asset), info->m_definition->m_name) @@ -1122,7 +1130,7 @@ namespace LINE("}") } - void PrintLoadPtrMethod(StructureInformation* info) + void PrintLoadPtrMethod(const StructureInformation* info) { const bool inTemp = info->m_block && info->m_block->m_type == FastFileBlockType::TEMP; LINEF("void {0}::LoadPtr_{1}(const bool atStreamStart)", LoaderClassName(m_env.m_asset), MakeSafeTypeName(info->m_definition)) @@ -1265,7 +1273,7 @@ namespace LINEF("{0} marker(m_zone);", MarkerClassName(m_env.m_asset)) LINE("marker.Mark(*pAsset);") LINE("") - LINEF("auto* reallocatedAsset = m_zone->GetMemory()->Alloc<{0}>();", info->m_definition->GetFullName()) + LINEF("auto* reallocatedAsset = m_zone.Memory().Alloc<{0}>();", info->m_definition->GetFullName()) LINEF("std::memcpy(reallocatedAsset, *pAsset, sizeof({0}));", info->m_definition->GetFullName()) LINE("") LINEF("m_asset_info = reinterpret_cast*>(LinkAsset(AssetNameAccessor<{1}>()(**pAsset), reallocatedAsset, marker.GetDependencies(), " @@ -1306,11 +1314,11 @@ namespace }; } // namespace -std::vector ZoneLoadTemplate::GetFilesToRender(RenderingContext* context) +std::vector ZoneLoadTemplate::GetFilesToRender(const RenderingContext& context) { std::vector files; - auto assetName = context->m_asset->m_definition->m_name; + auto assetName = context.m_asset->m_definition->m_name; utils::MakeStringLowerCase(assetName); files.emplace_back(std::format("{0}/{0}_load_db.h", assetName), TAG_HEADER); @@ -1319,7 +1327,7 @@ std::vector ZoneLoadTemplate::GetFilesToRender(RenderingContex return files; } -void ZoneLoadTemplate::RenderFile(std::ostream& stream, const int fileTag, RenderingContext* context) +void ZoneLoadTemplate::RenderFile(std::ostream& stream, const int fileTag, const RenderingContext& context) { Template t(stream, context); diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.h index c205f328..f44aa382 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.h @@ -4,6 +4,6 @@ class ZoneLoadTemplate final : public ICodeTemplate { public: - std::vector GetFilesToRender(RenderingContext* context) override; - void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) override; + std::vector GetFilesToRender(const RenderingContext& context) override; + void RenderFile(std::ostream& stream, int fileTag, const RenderingContext& context) override; }; diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneMarkTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneMarkTemplate.cpp index 2dda0606..f3426a67 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneMarkTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneMarkTemplate.cpp @@ -6,7 +6,6 @@ #include "Utils/StringUtils.h" #include -#include #include namespace @@ -17,7 +16,7 @@ namespace class Template final : BaseTemplate { public: - Template(std::ostream& stream, RenderingContext* context) + Template(std::ostream& stream, const RenderingContext& context) : BaseTemplate(stream, context) { } @@ -32,8 +31,8 @@ namespace LINE("") LINE("#pragma once") LINE("") - LINE("#include \"Loading/AssetMarker.h\"") LINEF("#include \"Game/{0}/{0}.h\"", m_env.m_game) + LINE("#include \"Loading/AssetMarker.h\"") LINE("") LINE("#include ") LINE("") @@ -44,32 +43,18 @@ namespace LINE("{") m_intendation++; - LINE(VariableDecl(m_env.m_asset->m_definition)) - LINE(PointerVariableDecl(m_env.m_asset->m_definition)) - LINE("") - m_intendation--; LINE("public:") m_intendation++; - - // Variable Declarations: type varType; - for (const auto* type : m_env.m_used_types) - { - if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - LINE(VariableDecl(type->m_type)) - } - } - for (const auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) - { - LINE(PointerVariableDecl(type->m_type)) - } - } - + PrintHeaderConstructor(); + PrintHeaderMainMarkMethodDeclaration(m_env.m_asset); + PrintHeaderGetAssetInfoMethodDeclaration(m_env.m_asset); LINE("") + m_intendation--; + LINE("private:") + m_intendation++; + // Method Declarations for (const auto* type : m_env.m_used_types) { @@ -95,11 +80,28 @@ namespace } } PrintHeaderMarkMethodDeclaration(m_env.m_asset); + LINE("") - PrintHeaderGetAssetInfoMethodDeclaration(m_env.m_asset); + + LINE(VariableDecl(m_env.m_asset->m_definition)) + LINE(PointerVariableDecl(m_env.m_asset->m_definition)) LINE("") - PrintHeaderConstructor(); - PrintHeaderMainMarkMethodDeclaration(m_env.m_asset); + + // Variable Declarations: type varType; + for (const auto* type : m_env.m_used_types) + { + if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) + { + LINE(VariableDecl(type->m_type)) + } + } + for (const auto* type : m_env.m_used_types) + { + if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) + { + LINE(PointerVariableDecl(type->m_type)) + } + } m_intendation--; LINE("};") @@ -116,22 +118,26 @@ namespace LINE("// ====================================================================") LINE("") LINEF("#include \"{0}_mark_db.h\"", Lower(m_env.m_asset->m_definition->m_name)) - LINE("") - LINE("#include ") - LINE("") if (!m_env.m_referenced_assets.empty()) { + LINE("") LINE("// Referenced Assets:") for (const auto* type : m_env.m_referenced_assets) { LINEF("#include \"../{0}/{0}_mark_db.h\"", Lower(type->m_type->m_name)) } - LINE("") } + LINE("") + LINE("#include ") + LINE("") LINEF("using namespace {0};", m_env.m_game) LINE("") PrintConstructorMethod(); + LINE("") + PrintMainMarkMethod(); + LINE("") + PrintGetAssetInfoMethod(); for (const auto* type : m_env.m_used_types) { @@ -161,10 +167,6 @@ namespace } LINE("") PrintMarkMethod(m_env.m_asset); - LINE("") - PrintMainMarkMethod(); - LINE("") - PrintGetAssetInfoMethod(); } private: @@ -215,7 +217,7 @@ namespace void PrintHeaderConstructor() const { - LINEF("{0}(Zone* zone);", MarkerClassName(m_env.m_asset)) + LINEF("{0}(Zone& zone);", MarkerClassName(m_env.m_asset)) } void PrintHeaderMainMarkMethodDeclaration(const StructureInformation* info) const @@ -235,7 +237,7 @@ namespace void PrintConstructorMethod() { - LINEF("{0}::{0}(Zone* zone)", MarkerClassName(m_env.m_asset)) + LINEF("{0}::{0}(Zone& zone)", MarkerClassName(m_env.m_asset)) m_intendation++; LINEF(": AssetMarker({0}::EnumEntry, zone)", m_env.m_asset->m_asset_name) @@ -276,7 +278,7 @@ namespace } } - void PrintMarkPtrArrayMethod_PointerCheck(const DataDefinition* def, StructureInformation* info, const bool reusable) + void PrintMarkPtrArrayMethod_PointerCheck(const DataDefinition* def, const StructureInformation* info) { LINEF("if (*{0})", MakeTypePtrVarName(def)) LINE("{") @@ -295,7 +297,7 @@ namespace LINE("}") } - void PrintMarkPtrArrayMethod(const DataDefinition* def, StructureInformation* info, const bool reusable) + void PrintMarkPtrArrayMethod(const DataDefinition* def, const StructureInformation* info, const bool reusable) { LINEF("void {0}::MarkPtrArray_{1}(const size_t count)", MarkerClassName(m_env.m_asset), MakeSafeTypeName(def)) LINE("{") @@ -310,7 +312,7 @@ namespace m_intendation++; LINEF("{0} = var;", MakeTypePtrVarName(def)) - PrintMarkPtrArrayMethod_PointerCheck(def, info, reusable); + PrintMarkPtrArrayMethod_PointerCheck(def, info); LINE("") LINE("var++;") @@ -531,7 +533,8 @@ namespace } } - static bool MarkMember_ShouldMakePointerCheck(const MemberInformation* member, const DeclarationModifierComputations& modifier, MemberLoadType loadType) + static bool + MarkMember_ShouldMakePointerCheck(const MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) { if (loadType != MemberLoadType::ARRAY_POINTER && loadType != MemberLoadType::POINTER_ARRAY && loadType != MemberLoadType::SINGLE_POINTER) { @@ -780,11 +783,11 @@ namespace }; } // namespace -std::vector ZoneMarkTemplate::GetFilesToRender(RenderingContext* context) +std::vector ZoneMarkTemplate::GetFilesToRender(const RenderingContext& context) { std::vector files; - auto assetName = context->m_asset->m_definition->m_name; + auto assetName = context.m_asset->m_definition->m_name; utils::MakeStringLowerCase(assetName); files.emplace_back(std::format("{0}/{0}_mark_db.h", assetName), TAG_HEADER); @@ -793,7 +796,7 @@ std::vector ZoneMarkTemplate::GetFilesToRender(RenderingContex return files; } -void ZoneMarkTemplate::RenderFile(std::ostream& stream, const int fileTag, RenderingContext* context) +void ZoneMarkTemplate::RenderFile(std::ostream& stream, const int fileTag, const RenderingContext& context) { Template t(stream, context); diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneMarkTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneMarkTemplate.h index 5583b54e..f430c9d4 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneMarkTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneMarkTemplate.h @@ -4,6 +4,6 @@ class ZoneMarkTemplate final : public ICodeTemplate { public: - std::vector GetFilesToRender(RenderingContext* context) override; - void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) override; + std::vector GetFilesToRender(const RenderingContext& context) override; + void RenderFile(std::ostream& stream, int fileTag, const RenderingContext& context) override; }; diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.cpp index 41ccf831..44c5a98c 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.cpp @@ -15,7 +15,7 @@ namespace class Template final : BaseTemplate { public: - Template(std::ostream& stream, RenderingContext* context) + Template(std::ostream& stream, const RenderingContext& context) : BaseTemplate(stream, context) { } @@ -30,8 +30,9 @@ namespace LINE("") LINE("#pragma once") LINE("") - LINE("#include \"Writing/AssetWriter.h\"") LINEF("#include \"Game/{0}/{0}.h\"", m_env.m_game) + LINE("#include \"Writing/AssetWriter.h\"") + LINE("") LINE("#include ") LINE("") LINEF("namespace {0}", m_env.m_game) @@ -41,31 +42,16 @@ namespace LINE("{") m_intendation++; - LINE(VariableDecl(m_env.m_asset->m_definition)) - LINE(WrittenVariableDecl(m_env.m_asset->m_definition)) - LINE(PointerVariableDecl(m_env.m_asset->m_definition)) - LINE(WrittenPointerVariableDecl(m_env.m_asset->m_definition)) - LINE("") - - // Variable Declarations: type varType; - for (const auto* type : m_env.m_used_types) - { - if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - LINE(VariableDecl(type->m_type)) - LINE(WrittenVariableDecl(type->m_type)) - } - } - for (const auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) - { - LINE(PointerVariableDecl(type->m_type)) - LINE(WrittenPointerVariableDecl(type->m_type)) - } - } + m_intendation--; + LINE("public:") + m_intendation++; + PrintHeaderConstructor(); + PrintHeaderMainWriteMethodDeclaration(m_env.m_asset); LINE("") + m_intendation--; + LINE("private:") + m_intendation++; // Method Declarations for (const auto* type : m_env.m_used_types) @@ -91,12 +77,32 @@ namespace } PrintHeaderWriteMethodDeclaration(m_env.m_asset); PrintHeaderTempPtrWriteMethodDeclaration(m_env.m_asset); + LINE("") - m_intendation--; - LINE("public:") - m_intendation++; - PrintHeaderConstructor(); - PrintHeaderMainWriteMethodDeclaration(m_env.m_asset); + + LINE(VariableDecl(m_env.m_asset->m_definition)) + LINE(WrittenVariableDecl(m_env.m_asset->m_definition)) + LINE(PointerVariableDecl(m_env.m_asset->m_definition)) + LINE(WrittenPointerVariableDecl(m_env.m_asset->m_definition)) + LINE("") + + // Variable Declarations: type varType; + for (const auto* type : m_env.m_used_types) + { + if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) + { + LINE(VariableDecl(type->m_type)) + LINE(WrittenVariableDecl(type->m_type)) + } + } + for (const auto* type : m_env.m_used_types) + { + if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) + { + LINE(PointerVariableDecl(type->m_type)) + LINE(WrittenPointerVariableDecl(type->m_type)) + } + } m_intendation--; LINE("};") @@ -113,21 +119,25 @@ namespace LINE("// ====================================================================") LINE("") LINEF("#include \"{0}_write_db.h\"", Lower(m_env.m_asset->m_definition->m_name)) - LINE("#include ") - LINE("") if (!m_env.m_referenced_assets.empty()) { + LINE("") LINE("// Referenced Assets:") for (const auto* type : m_env.m_referenced_assets) { LINEF("#include \"../{0}/{0}_write_db.h\"", Lower(type->m_type->m_name)) } - LINE("") } + + LINE("") + LINE("#include ") + LINE("") LINEF("using namespace {0};", m_env.m_game) LINE("") PrintConstructorMethod(); + LINE("") + PrintMainWriteMethod(); for (const auto* type : m_env.m_used_types) { @@ -157,8 +167,6 @@ namespace PrintWriteMethod(m_env.m_asset); LINE("") PrintWritePtrMethod(m_env.m_asset); - LINE("") - PrintMainWriteMethod(); } private: @@ -1116,7 +1124,7 @@ namespace LINEF("m_stream->MarkFollowing(*{0});", MakeTypeWrittenPtrVarName(def)) } - void PrintWritePtrArrayMethod_PointerCheck(const DataDefinition* def, StructureInformation* info, const bool reusable) + void PrintWritePtrArrayMethod_PointerCheck(const DataDefinition* def, const StructureInformation* info, const bool reusable) { LINEF("if (*{0})", MakeTypePtrVarName(def)) LINE("{") @@ -1150,7 +1158,7 @@ namespace LINE("}") } - void PrintWritePtrArrayMethod(const DataDefinition* def, StructureInformation* info, const bool reusable) + void PrintWritePtrArrayMethod(const DataDefinition* def, const StructureInformation* info, const bool reusable) { LINEF("void {0}::WritePtrArray_{1}(const bool atStreamStart, const size_t count)", WriterClassName(m_env.m_asset), MakeSafeTypeName(def)) LINE("{") @@ -1225,11 +1233,11 @@ namespace }; } // namespace -std::vector ZoneWriteTemplate::GetFilesToRender(RenderingContext* context) +std::vector ZoneWriteTemplate::GetFilesToRender(const RenderingContext& context) { std::vector files; - auto assetName = context->m_asset->m_definition->m_name; + auto assetName = context.m_asset->m_definition->m_name; for (auto& c : assetName) c = static_cast(tolower(c)); @@ -1239,7 +1247,7 @@ std::vector ZoneWriteTemplate::GetFilesToRender(RenderingConte return files; } -void ZoneWriteTemplate::RenderFile(std::ostream& stream, const int fileTag, RenderingContext* context) +void ZoneWriteTemplate::RenderFile(std::ostream& stream, const int fileTag, const RenderingContext& context) { Template t(stream, context); diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.h index df072484..e2211212 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.h @@ -4,6 +4,6 @@ class ZoneWriteTemplate final : public ICodeTemplate { public: - std::vector GetFilesToRender(RenderingContext* context) override; - void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) override; + std::vector GetFilesToRender(const RenderingContext& context) override; + void RenderFile(std::ostream& stream, int fileTag, const RenderingContext& context) override; }; diff --git a/src/ZoneCommon/Zone/Zone.cpp b/src/ZoneCommon/Zone/Zone.cpp index 5014120a..f5ee6af1 100644 --- a/src/ZoneCommon/Zone/Zone.cpp +++ b/src/ZoneCommon/Zone/Zone.cpp @@ -1,13 +1,13 @@ #include "Zone.h" Zone::Zone(std::string name, const zone_priority_t priority, IGame* game) - : m_memory(std::make_unique()), - m_registered(false), - m_name(std::move(name)), + : m_name(std::move(name)), m_priority(priority), m_language(GameLanguage::LANGUAGE_NONE), m_game(game), - m_pools(ZoneAssetPools::CreateForGame(game->GetId(), this, priority)) + m_pools(ZoneAssetPools::CreateForGame(game->GetId(), this, priority)), + m_memory(std::make_unique()), + m_registered(false) { } @@ -28,7 +28,7 @@ void Zone::Register() } } -ZoneMemory* Zone::GetMemory() const +ZoneMemory& Zone::Memory() const { - return m_memory.get(); + return *m_memory; } diff --git a/src/ZoneCommon/Zone/Zone.h b/src/ZoneCommon/Zone/Zone.h index 9f586b83..48c4d7d6 100644 --- a/src/ZoneCommon/Zone/Zone.h +++ b/src/ZoneCommon/Zone/Zone.h @@ -3,7 +3,6 @@ #include "Game/GameLanguage.h" #include "Game/IGame.h" #include "Pool/ZoneAssetPools.h" -#include "Utils/ClassUtils.h" #include "Zone/ZoneTypes.h" #include "ZoneMemory.h" #include "ZoneScriptStrings.h" @@ -16,10 +15,6 @@ class ZoneAssetPools; class Zone { - std::unique_ptr m_memory; - - bool m_registered; - public: std::string m_name; zone_priority_t m_priority; @@ -37,5 +32,10 @@ public: void Register(); - _NODISCARD ZoneMemory* GetMemory() const; + [[nodiscard]] ZoneMemory& Memory() const; + +private: + std::unique_ptr m_memory; + + bool m_registered; }; diff --git a/src/ZoneLoading/Game/IW3/ContentLoaderIW3.cpp b/src/ZoneLoading/Game/IW3/ContentLoaderIW3.cpp index e78039c9..ed3e3909 100644 --- a/src/ZoneLoading/Game/IW3/ContentLoaderIW3.cpp +++ b/src/ZoneLoading/Game/IW3/ContentLoaderIW3.cpp @@ -32,8 +32,9 @@ using namespace IW3; -ContentLoader::ContentLoader() - : varXAsset(nullptr), +ContentLoader::ContentLoader(Zone& zone) + : ContentLoaderBase(zone), + varXAsset(nullptr), varScriptStringList(nullptr) { } @@ -54,12 +55,12 @@ void ContentLoader::LoadScriptStringList(const bool atStreamStart) LoadXStringArray(true, varScriptStringList->count); if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); + m_zone.m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); } m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone.m_script_strings.Count() <= SCR_STRING_MAX + 1); } void ContentLoader::LoadXAsset(const bool atStreamStart) const @@ -67,7 +68,7 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const #define LOAD_ASSET(type_index, typeName, headerEntry) \ case type_index: \ { \ - Loader_##typeName loader(m_zone, m_stream); \ + Loader_##typeName loader(m_zone, *m_stream); \ loader.Load(&varXAsset->header.headerEntry); \ break; \ } @@ -133,10 +134,9 @@ void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) +void ContentLoader::Load(ZoneInputStream& stream) { - m_zone = zone; - m_stream = stream; + m_stream = &stream; m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); diff --git a/src/ZoneLoading/Game/IW3/ContentLoaderIW3.h b/src/ZoneLoading/Game/IW3/ContentLoaderIW3.h index 1d0c0d30..fb44f42d 100644 --- a/src/ZoneLoading/Game/IW3/ContentLoaderIW3.h +++ b/src/ZoneLoading/Game/IW3/ContentLoaderIW3.h @@ -1,4 +1,5 @@ #pragma once + #include "Game/IW3/IW3.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" @@ -7,17 +8,18 @@ namespace IW3 { class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; + public: + explicit ContentLoader(Zone& zone); + void Load(ZoneInputStream& stream) override; + + private: void LoadScriptStringList(bool atStreamStart); void LoadXAsset(bool atStreamStart) const; void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); - - void Load(Zone* zone, IZoneInputStream* stream) override; + XAsset* varXAsset; + ScriptStringList* varScriptStringList; }; } // namespace IW3 diff --git a/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.cpp index b3befd5c..b2585045 100644 --- a/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.cpp @@ -5,7 +5,7 @@ using namespace IW3; -Actions_GfxImage::Actions_GfxImage(Zone* zone) +Actions_GfxImage::Actions_GfxImage(Zone& zone) : AssetLoadingActions(zone) { } @@ -19,6 +19,6 @@ void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) { const size_t loadDefSize = offsetof(IW3::GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast(m_zone->GetMemory()->AllocRaw(loadDefSize)); + image->texture.loadDef = static_cast(m_zone.Memory().AllocRaw(loadDefSize)); memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.h index fc2c9617..6b48483c 100644 --- a/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.h @@ -8,7 +8,7 @@ namespace IW3 class Actions_GfxImage final : public AssetLoadingActions { public: - explicit Actions_GfxImage(Zone* zone); + explicit Actions_GfxImage(Zone& zone); void OnImageLoaded(GfxImage* image) const; void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; diff --git a/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.cpp b/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.cpp index 8c58ca9b..5d899987 100644 --- a/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.cpp +++ b/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.cpp @@ -4,7 +4,7 @@ using namespace IW3; -Actions_LoadedSound::Actions_LoadedSound(Zone* zone) +Actions_LoadedSound::Actions_LoadedSound(Zone& zone) : AssetLoadingActions(zone) { } @@ -14,7 +14,7 @@ void Actions_LoadedSound::SetSoundData(MssSound* sound) const if (sound->info.data_len > 0) { const auto* tempData = sound->data; - sound->data = m_zone->GetMemory()->Alloc(sound->info.data_len); + sound->data = m_zone.Memory().Alloc(sound->info.data_len); memcpy(sound->data, tempData, sound->info.data_len); } else diff --git a/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.h b/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.h index 6df942e7..7787400f 100644 --- a/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.h +++ b/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.h @@ -8,7 +8,7 @@ namespace IW3 class Actions_LoadedSound final : public AssetLoadingActions { public: - explicit Actions_LoadedSound(Zone* zone); + explicit Actions_LoadedSound(Zone& zone); void SetSoundData(MssSound* sound) const; }; diff --git a/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.cpp b/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.cpp index 1bfedf58..5de47662 100644 --- a/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.cpp +++ b/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.cpp @@ -10,6 +10,7 @@ #include "Loading/Steps/StepAddProcessor.h" #include "Loading/Steps/StepAllocXBlocks.h" #include "Loading/Steps/StepLoadZoneContent.h" +#include "Loading/Steps/StepLoadZoneSizes.h" #include "Loading/Steps/StepSkipBytes.h" #include "Utils/ClassUtils.h" @@ -77,16 +78,15 @@ std::unique_ptr ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& SetupBlock(*zoneLoader); - zoneLoader->AddLoadingStep(std::make_unique(std::make_unique(ZoneConstants::AUTHED_CHUNK_SIZE))); + zoneLoader->AddLoadingStep(step::CreateStepAddProcessor(processor::CreateProcessorInflate(ZoneConstants::AUTHED_CHUNK_SIZE))); // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique(8)); - // Skip size and externalSize fields since they are not interesting for us - zoneLoader->AddLoadingStep(std::make_unique()); + zoneLoader->AddLoadingStep(step::CreateStepLoadZoneSizes()); + zoneLoader->AddLoadingStep(step::CreateStepAllocXBlocks()); // Start of the zone content zoneLoader->AddLoadingStep( - std::make_unique(std::make_unique(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + step::CreateStepLoadZoneContent(std::make_unique(*zonePtr), ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); return zoneLoader; } diff --git a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.cpp b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.cpp index 6ae4f493..a15b7229 100644 --- a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.cpp +++ b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.cpp @@ -42,8 +42,9 @@ using namespace IW4; -ContentLoader::ContentLoader() - : varXAsset(nullptr), +ContentLoader::ContentLoader(Zone& zone) + : ContentLoaderBase(zone), + varXAsset(nullptr), varScriptStringList(nullptr) { } @@ -64,12 +65,12 @@ void ContentLoader::LoadScriptStringList(const bool atStreamStart) LoadXStringArray(true, varScriptStringList->count); if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); + m_zone.m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); } m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone.m_script_strings.Count() <= SCR_STRING_MAX + 1); } void ContentLoader::LoadXAsset(const bool atStreamStart) const @@ -77,7 +78,7 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const #define LOAD_ASSET(type_index, typeName, headerEntry) \ case type_index: \ { \ - Loader_##typeName loader(m_zone, m_stream); \ + Loader_##typeName loader(m_zone, *m_stream); \ loader.Load(&varXAsset->header.headerEntry); \ break; \ } @@ -153,10 +154,9 @@ void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) +void ContentLoader::Load(ZoneInputStream& stream) { - m_zone = zone; - m_stream = stream; + m_stream = &stream; m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); diff --git a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h index 8a3fd944..a3c30973 100644 --- a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h +++ b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h @@ -9,9 +9,9 @@ namespace IW4 class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { public: - ContentLoader(); + explicit ContentLoader(Zone& zone); - void Load(Zone* zone, IZoneInputStream* stream) override; + void Load(ZoneInputStream& stream) override; private: void LoadScriptStringList(bool atStreamStart); diff --git a/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.cpp index 9c208c2f..31e30897 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.cpp @@ -5,7 +5,7 @@ using namespace IW4; -Actions_GfxImage::Actions_GfxImage(Zone* zone) +Actions_GfxImage::Actions_GfxImage(Zone& zone) : AssetLoadingActions(zone) { } @@ -19,6 +19,6 @@ void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) { const size_t loadDefSize = offsetof(IW4::GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast(m_zone->GetMemory()->AllocRaw(loadDefSize)); + image->texture.loadDef = static_cast(m_zone.Memory().AllocRaw(loadDefSize)); memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.h index 5dc03af6..dda325d7 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.h @@ -8,7 +8,7 @@ namespace IW4 class Actions_GfxImage final : public AssetLoadingActions { public: - explicit Actions_GfxImage(Zone* zone); + explicit Actions_GfxImage(Zone& zone); void OnImageLoaded(GfxImage* image) const; void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; diff --git a/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.cpp b/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.cpp index 4f4b579f..9a3a571b 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.cpp +++ b/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.cpp @@ -4,7 +4,7 @@ using namespace IW4; -Actions_LoadedSound::Actions_LoadedSound(Zone* zone) +Actions_LoadedSound::Actions_LoadedSound(Zone& zone) : AssetLoadingActions(zone) { } @@ -14,7 +14,7 @@ void Actions_LoadedSound::SetSoundData(MssSound* sound) const if (sound->info.data_len > 0) { const auto* tempData = sound->data; - sound->data = m_zone->GetMemory()->Alloc(sound->info.data_len); + sound->data = m_zone.Memory().Alloc(sound->info.data_len); memcpy(sound->data, tempData, sound->info.data_len); } else diff --git a/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.h b/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.h index 7b04a24a..c13591b5 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.h +++ b/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.h @@ -8,7 +8,7 @@ namespace IW4 class Actions_LoadedSound final : public AssetLoadingActions { public: - explicit Actions_LoadedSound(Zone* zone); + explicit Actions_LoadedSound(Zone& zone); void SetSoundData(MssSound* sound) const; }; diff --git a/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.cpp b/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.cpp index 887dc3ae..be873394 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.cpp +++ b/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.cpp @@ -4,7 +4,7 @@ using namespace IW4; -Actions_XModel::Actions_XModel(Zone* zone) +Actions_XModel::Actions_XModel(Zone& zone) : AssetLoadingActions(zone) { } @@ -13,7 +13,7 @@ void Actions_XModel::SetModelSurfs(XModelLodInfo* lodInfo, XModelSurfs* modelSur { if (modelSurfs) { - lodInfo->modelSurfs = m_zone->GetMemory()->Alloc(); + lodInfo->modelSurfs = m_zone.Memory().Alloc(); memcpy(lodInfo->modelSurfs, modelSurfs, sizeof(XModelSurfs)); } } diff --git a/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.h b/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.h index 8f98d377..8a192307 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.h +++ b/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.h @@ -8,7 +8,7 @@ namespace IW4 class Actions_XModel final : public AssetLoadingActions { public: - explicit Actions_XModel(Zone* zone); + explicit Actions_XModel(Zone& zone); void SetModelSurfs(XModelLodInfo* lodInfo, XModelSurfs* modelSurfs) const; }; diff --git a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp index f7347570..4cc808e0 100644 --- a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp +++ b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp @@ -15,6 +15,7 @@ #include "Loading/Steps/StepLoadHash.h" #include "Loading/Steps/StepLoadSignature.h" #include "Loading/Steps/StepLoadZoneContent.h" +#include "Loading/Steps/StepLoadZoneSizes.h" #include "Loading/Steps/StepRemoveProcessor.h" #include "Loading/Steps/StepSkipBytes.h" #include "Loading/Steps/StepVerifyFileName.h" @@ -123,43 +124,43 @@ namespace // If file is signed setup a RSA instance. auto rsa = SetupRsa(isOfficial); - zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::MAGIC_AUTH_HEADER)); - zoneLoader.AddLoadingStep(std::make_unique(4)); // Skip reserved + zoneLoader.AddLoadingStep(step::CreateStepVerifyMagic(ZoneConstants::MAGIC_AUTH_HEADER)); + zoneLoader.AddLoadingStep(step::CreateStepSkipBytes(4)); // Skip reserved - auto subHeaderHash = std::make_unique(sizeof(DB_AuthHash::bytes), 1); + auto subHeaderHash = step::CreateStepLoadHash(sizeof(DB_AuthHash::bytes), 1); auto* subHeaderHashPtr = subHeaderHash.get(); zoneLoader.AddLoadingStep(std::move(subHeaderHash)); - auto subHeaderHashSignature = std::make_unique(sizeof(DB_AuthSignature::bytes)); + auto subHeaderHashSignature = step::CreateStepLoadSignature(sizeof(DB_AuthSignature::bytes)); auto* subHeaderHashSignaturePtr = subHeaderHashSignature.get(); zoneLoader.AddLoadingStep(std::move(subHeaderHashSignature)); - zoneLoader.AddLoadingStep(std::make_unique(std::move(rsa), subHeaderHashSignaturePtr, subHeaderHashPtr)); + zoneLoader.AddLoadingStep(step::CreateStepVerifySignature(std::move(rsa), subHeaderHashSignaturePtr, subHeaderHashPtr)); - auto subHeaderCapture = std::make_unique(sizeof(DB_AuthSubHeader)); + auto subHeaderCapture = processor::CreateProcessorCaptureData(sizeof(DB_AuthSubHeader)); auto* subHeaderCapturePtr = subHeaderCapture.get(); - zoneLoader.AddLoadingStep(std::make_unique(std::move(subHeaderCapture))); + zoneLoader.AddLoadingStep(step::CreateStepAddProcessor(std::move(subHeaderCapture))); - zoneLoader.AddLoadingStep(std::make_unique(fileName, sizeof(DB_AuthSubHeader::fastfileName))); - zoneLoader.AddLoadingStep(std::make_unique(4)); // Skip reserved + zoneLoader.AddLoadingStep(step::CreateStepVerifyFileName(fileName, sizeof(DB_AuthSubHeader::fastfileName))); + zoneLoader.AddLoadingStep(step::CreateStepSkipBytes(4)); // Skip reserved auto masterBlockHashes = - std::make_unique(sizeof(DB_AuthHash::bytes), static_cast(std::extent_v)); + step::CreateStepLoadHash(sizeof(DB_AuthHash::bytes), static_cast(std::extent_v)); auto* masterBlockHashesPtr = masterBlockHashes.get(); zoneLoader.AddLoadingStep(std::move(masterBlockHashes)); - zoneLoader.AddLoadingStep(std::make_unique(cryptography::CreateSha256(), 0, subHeaderHashPtr, subHeaderCapturePtr)); - zoneLoader.AddLoadingStep(std::make_unique(subHeaderCapturePtr)); + zoneLoader.AddLoadingStep(step::CreateStepVerifyHash(cryptography::CreateSha256(), 0, subHeaderHashPtr, subHeaderCapturePtr)); + zoneLoader.AddLoadingStep(step::CreateStepRemoveProcessor(subHeaderCapturePtr)); // Skip the rest of the first chunk - zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); + zoneLoader.AddLoadingStep(step::CreateStepSkipBytes(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); - zoneLoader.AddLoadingStep(std::make_unique( - std::make_unique(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, - ZoneConstants::AUTHED_CHUNK_SIZE, - static_cast(std::extent_v), - cryptography::CreateSha256(), - masterBlockHashesPtr))); + zoneLoader.AddLoadingStep(step::CreateStepAddProcessor( + processor::CreateProcessorAuthedBlocks(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, + ZoneConstants::AUTHED_CHUNK_SIZE, + static_cast(std::extent_v), + cryptography::CreateSha256(), + masterBlockHashesPtr))); } } // namespace @@ -185,30 +186,29 @@ std::unique_ptr ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& SetupBlock(*zoneLoader); // Skip unknown 1 byte field that the game ignores as well - zoneLoader->AddLoadingStep(std::make_unique(1)); + zoneLoader->AddLoadingStep(step::CreateStepSkipBytes(1)); // Skip timestamp - zoneLoader->AddLoadingStep(std::make_unique(8)); + zoneLoader->AddLoadingStep(step::CreateStepSkipBytes(8)); // Add steps for loading the auth header which also contain the signature of the zone if it is signed. AddAuthHeaderSteps(isSecure, isOfficial, *zoneLoader, fileName); - zoneLoader->AddLoadingStep(std::make_unique(std::make_unique(ZoneConstants::AUTHED_CHUNK_SIZE))); + zoneLoader->AddLoadingStep(step::CreateStepAddProcessor(processor::CreateProcessorInflate(ZoneConstants::AUTHED_CHUNK_SIZE))); if (isIw4x) // IW4x has one extra byte of padding here for protection purposes { - zoneLoader->AddLoadingStep(std::make_unique(std::make_unique())); - zoneLoader->AddLoadingStep(std::make_unique(1)); + zoneLoader->AddLoadingStep(step::CreateStepAddProcessor(processor::CreateProcessorIW4xDecryption())); + zoneLoader->AddLoadingStep(step::CreateStepSkipBytes(1)); } // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique(8)); - // Skip size and externalSize fields since they are not interesting for us - zoneLoader->AddLoadingStep(std::make_unique()); + zoneLoader->AddLoadingStep(step::CreateStepLoadZoneSizes()); + zoneLoader->AddLoadingStep(step::CreateStepAllocXBlocks()); // Start of the zone content zoneLoader->AddLoadingStep( - std::make_unique(std::make_unique(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + step::CreateStepLoadZoneContent(std::make_unique(*zonePtr), ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); return zoneLoader; } diff --git a/src/ZoneLoading/Game/IW5/ContentLoaderIW5.cpp b/src/ZoneLoading/Game/IW5/ContentLoaderIW5.cpp index 101d259b..2558ab88 100644 --- a/src/ZoneLoading/Game/IW5/ContentLoaderIW5.cpp +++ b/src/ZoneLoading/Game/IW5/ContentLoaderIW5.cpp @@ -47,8 +47,9 @@ using namespace IW5; -ContentLoader::ContentLoader() - : varXAsset(nullptr), +ContentLoader::ContentLoader(Zone& zone) + : ContentLoaderBase(zone), + varXAsset(nullptr), varScriptStringList(nullptr) { } @@ -69,12 +70,12 @@ void ContentLoader::LoadScriptStringList(const bool atStreamStart) LoadXStringArray(true, varScriptStringList->count); if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); + m_zone.m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); } m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone.m_script_strings.Count() <= SCR_STRING_MAX + 1); } void ContentLoader::LoadXAsset(const bool atStreamStart) const @@ -82,7 +83,7 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const #define LOAD_ASSET(type_index, typeName, headerEntry) \ case type_index: \ { \ - Loader_##typeName loader(m_zone, m_stream); \ + Loader_##typeName loader(m_zone, *m_stream); \ loader.Load(&varXAsset->header.headerEntry); \ break; \ } @@ -162,10 +163,9 @@ void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) +void ContentLoader::Load(ZoneInputStream& stream) { - m_zone = zone; - m_stream = stream; + m_stream = &stream; m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); diff --git a/src/ZoneLoading/Game/IW5/ContentLoaderIW5.h b/src/ZoneLoading/Game/IW5/ContentLoaderIW5.h index 115f2c91..b06631a2 100644 --- a/src/ZoneLoading/Game/IW5/ContentLoaderIW5.h +++ b/src/ZoneLoading/Game/IW5/ContentLoaderIW5.h @@ -1,4 +1,5 @@ #pragma once + #include "Game/IW5/IW5.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" @@ -7,17 +8,18 @@ namespace IW5 { class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; + public: + explicit ContentLoader(Zone& zone); + void Load(ZoneInputStream& stream) override; + + private: void LoadScriptStringList(bool atStreamStart); void LoadXAsset(bool atStreamStart) const; void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); - - void Load(Zone* zone, IZoneInputStream* stream) override; + XAsset* varXAsset; + ScriptStringList* varScriptStringList; }; } // namespace IW5 diff --git a/src/ZoneLoading/Game/IW5/XAssets/clipmap_t/clipmap_t_actions.cpp b/src/ZoneLoading/Game/IW5/XAssets/clipmap_t/clipmap_t_actions.cpp index 0ce5583b..08492510 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/clipmap_t/clipmap_t_actions.cpp +++ b/src/ZoneLoading/Game/IW5/XAssets/clipmap_t/clipmap_t_actions.cpp @@ -5,13 +5,13 @@ using namespace IW5; -Actions_clipMap_t::Actions_clipMap_t(Zone* zone) +Actions_clipMap_t::Actions_clipMap_t(Zone& zone) : AssetLoadingActions(zone) { } void Actions_clipMap_t::ReallocClipInfo(const ClipInfo* clipInfo, clipMap_t* clipMap) const { - clipMap->pInfo = m_zone->GetMemory()->Alloc(); + clipMap->pInfo = m_zone.Memory().Alloc(); memcpy(clipMap->pInfo, clipInfo, sizeof(ClipInfo)); } diff --git a/src/ZoneLoading/Game/IW5/XAssets/clipmap_t/clipmap_t_actions.h b/src/ZoneLoading/Game/IW5/XAssets/clipmap_t/clipmap_t_actions.h index 062ca06f..d7f50b97 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/clipmap_t/clipmap_t_actions.h +++ b/src/ZoneLoading/Game/IW5/XAssets/clipmap_t/clipmap_t_actions.h @@ -8,7 +8,7 @@ namespace IW5 class Actions_clipMap_t final : public AssetLoadingActions { public: - explicit Actions_clipMap_t(Zone* zone); + explicit Actions_clipMap_t(Zone& zone); void ReallocClipInfo(const ClipInfo* clipInfo, clipMap_t* clipMap) const; }; diff --git a/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.cpp index cb5f7a75..70b58e51 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.cpp @@ -5,7 +5,7 @@ using namespace IW5; -Actions_GfxImage::Actions_GfxImage(Zone* zone) +Actions_GfxImage::Actions_GfxImage(Zone& zone) : AssetLoadingActions(zone) { } @@ -19,6 +19,6 @@ void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) { const size_t loadDefSize = offsetof(IW5::GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast(m_zone->GetMemory()->AllocRaw(loadDefSize)); + image->texture.loadDef = static_cast(m_zone.Memory().AllocRaw(loadDefSize)); memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.h index 7ea60d7d..944089fd 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.h @@ -8,7 +8,7 @@ namespace IW5 class Actions_GfxImage final : public AssetLoadingActions { public: - explicit Actions_GfxImage(Zone* zone); + explicit Actions_GfxImage(Zone& zone); void OnImageLoaded(GfxImage* image) const; void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; diff --git a/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.cpp b/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.cpp index 6c4f27aa..d8fbad7a 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.cpp +++ b/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.cpp @@ -4,7 +4,7 @@ using namespace IW5; -Actions_LoadedSound::Actions_LoadedSound(Zone* zone) +Actions_LoadedSound::Actions_LoadedSound(Zone& zone) : AssetLoadingActions(zone) { } @@ -14,7 +14,7 @@ void Actions_LoadedSound::SetSoundData(MssSound* sound) const if (sound->info.data_len > 0) { char* tempData = sound->data; - sound->data = m_zone->GetMemory()->Alloc(sound->info.data_len); + sound->data = m_zone.Memory().Alloc(sound->info.data_len); memcpy(sound->data, tempData, sound->info.data_len); } else diff --git a/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.h b/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.h index 4e0de4d2..649c7b5f 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.h +++ b/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.h @@ -8,7 +8,7 @@ namespace IW5 class Actions_LoadedSound final : public AssetLoadingActions { public: - explicit Actions_LoadedSound(Zone* zone); + explicit Actions_LoadedSound(Zone& zone); void SetSoundData(MssSound* sound) const; }; diff --git a/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.cpp b/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.cpp index 5739c607..c082e8ed 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.cpp +++ b/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.cpp @@ -4,7 +4,7 @@ using namespace IW5; -Actions_XModel::Actions_XModel(Zone* zone) +Actions_XModel::Actions_XModel(Zone& zone) : AssetLoadingActions(zone) { } @@ -13,7 +13,7 @@ void Actions_XModel::SetModelSurfs(XModelLodInfo* lodInfo, XModelSurfs* modelSur { if (modelSurfs) { - lodInfo->modelSurfs = m_zone->GetMemory()->Alloc(); + lodInfo->modelSurfs = m_zone.Memory().Alloc(); memcpy(lodInfo->modelSurfs, modelSurfs, sizeof(XModelSurfs)); } } diff --git a/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.h b/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.h index 3176c8f9..0117de3e 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.h +++ b/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.h @@ -8,7 +8,7 @@ namespace IW5 class Actions_XModel final : public AssetLoadingActions { public: - explicit Actions_XModel(Zone* zone); + explicit Actions_XModel(Zone& zone); void SetModelSurfs(XModelLodInfo* lodInfo, XModelSurfs* modelSurfs) const; }; diff --git a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp index b35b4274..4e77a1ca 100644 --- a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp +++ b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp @@ -14,6 +14,7 @@ #include "Loading/Steps/StepLoadHash.h" #include "Loading/Steps/StepLoadSignature.h" #include "Loading/Steps/StepLoadZoneContent.h" +#include "Loading/Steps/StepLoadZoneSizes.h" #include "Loading/Steps/StepRemoveProcessor.h" #include "Loading/Steps/StepSkipBytes.h" #include "Loading/Steps/StepVerifyFileName.h" @@ -107,43 +108,43 @@ namespace // If file is signed setup a RSA instance. auto rsa = SetupRsa(isOfficial); - zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::MAGIC_AUTH_HEADER)); - zoneLoader.AddLoadingStep(std::make_unique(4)); // Skip reserved + zoneLoader.AddLoadingStep(step::CreateStepVerifyMagic(ZoneConstants::MAGIC_AUTH_HEADER)); + zoneLoader.AddLoadingStep(step::CreateStepSkipBytes(4)); // Skip reserved - auto subHeaderHash = std::make_unique(sizeof(DB_AuthHash::bytes), 1); + auto subHeaderHash = step::CreateStepLoadHash(sizeof(DB_AuthHash::bytes), 1); auto* subHeaderHashPtr = subHeaderHash.get(); zoneLoader.AddLoadingStep(std::move(subHeaderHash)); - auto subHeaderHashSignature = std::make_unique(sizeof(DB_AuthSignature::bytes)); + auto subHeaderHashSignature = step::CreateStepLoadSignature(sizeof(DB_AuthSignature::bytes)); auto* subHeaderHashSignaturePtr = subHeaderHashSignature.get(); zoneLoader.AddLoadingStep(std::move(subHeaderHashSignature)); - zoneLoader.AddLoadingStep(std::make_unique(std::move(rsa), subHeaderHashSignaturePtr, subHeaderHashPtr)); + zoneLoader.AddLoadingStep(step::CreateStepVerifySignature(std::move(rsa), subHeaderHashSignaturePtr, subHeaderHashPtr)); - auto subHeaderCapture = std::make_unique(sizeof(DB_AuthSubHeader)); + auto subHeaderCapture = processor::CreateProcessorCaptureData(sizeof(DB_AuthSubHeader)); auto* subHeaderCapturePtr = subHeaderCapture.get(); - zoneLoader.AddLoadingStep(std::make_unique(std::move(subHeaderCapture))); + zoneLoader.AddLoadingStep(step::CreateStepAddProcessor(std::move(subHeaderCapture))); - zoneLoader.AddLoadingStep(std::make_unique(fileName, sizeof(DB_AuthSubHeader::fastfileName))); - zoneLoader.AddLoadingStep(std::make_unique(4)); // Skip reserved + zoneLoader.AddLoadingStep(step::CreateStepVerifyFileName(fileName, sizeof(DB_AuthSubHeader::fastfileName))); + zoneLoader.AddLoadingStep(step::CreateStepSkipBytes(4)); // Skip reserved auto masterBlockHashes = - std::make_unique(sizeof(DB_AuthHash::bytes), static_cast(std::extent_v)); + step::CreateStepLoadHash(sizeof(DB_AuthHash::bytes), static_cast(std::extent_v)); auto* masterBlockHashesPtr = masterBlockHashes.get(); zoneLoader.AddLoadingStep(std::move(masterBlockHashes)); - zoneLoader.AddLoadingStep(std::make_unique(cryptography::CreateSha256(), 0, subHeaderHashPtr, subHeaderCapturePtr)); - zoneLoader.AddLoadingStep(std::make_unique(subHeaderCapturePtr)); + zoneLoader.AddLoadingStep(step::CreateStepVerifyHash(cryptography::CreateSha256(), 0, subHeaderHashPtr, subHeaderCapturePtr)); + zoneLoader.AddLoadingStep(step::CreateStepRemoveProcessor(subHeaderCapturePtr)); // Skip the rest of the first chunk - zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); + zoneLoader.AddLoadingStep(step::CreateStepSkipBytes(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); - zoneLoader.AddLoadingStep(std::make_unique( - std::make_unique(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, - ZoneConstants::AUTHED_CHUNK_SIZE, - static_cast(std::extent_v), - cryptography::CreateSha256(), - masterBlockHashesPtr))); + zoneLoader.AddLoadingStep(step::CreateStepAddProcessor( + processor::CreateProcessorAuthedBlocks(ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, + ZoneConstants::AUTHED_CHUNK_SIZE, + static_cast(std::extent_v), + cryptography::CreateSha256(), + masterBlockHashesPtr))); } } // namespace @@ -168,24 +169,23 @@ std::unique_ptr ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& SetupBlock(*zoneLoader); // Skip unknown 1 byte field that the game ignores as well - zoneLoader->AddLoadingStep(std::make_unique(1)); + zoneLoader->AddLoadingStep(step::CreateStepSkipBytes(1)); // Skip timestamp - zoneLoader->AddLoadingStep(std::make_unique(8)); + zoneLoader->AddLoadingStep(step::CreateStepSkipBytes(8)); // Add steps for loading the auth header which also contain the signature of the zone if it is signed. AddAuthHeaderSteps(isSecure, isOfficial, *zoneLoader, fileName); - zoneLoader->AddLoadingStep(std::make_unique(std::make_unique(ZoneConstants::AUTHED_CHUNK_SIZE))); + zoneLoader->AddLoadingStep(step::CreateStepAddProcessor(processor::CreateProcessorInflate(ZoneConstants::AUTHED_CHUNK_SIZE))); // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique(8)); - // Skip size and externalSize fields since they are not interesting for us - zoneLoader->AddLoadingStep(std::make_unique()); + zoneLoader->AddLoadingStep(step::CreateStepLoadZoneSizes()); + zoneLoader->AddLoadingStep(step::CreateStepAllocXBlocks()); // Start of the zone content zoneLoader->AddLoadingStep( - std::make_unique(std::make_unique(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + step::CreateStepLoadZoneContent(std::make_unique(*zonePtr), ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); return zoneLoader; } diff --git a/src/ZoneLoading/Game/T5/ContentLoaderT5.cpp b/src/ZoneLoading/Game/T5/ContentLoaderT5.cpp index 327cdf93..2fe47338 100644 --- a/src/ZoneLoading/Game/T5/ContentLoaderT5.cpp +++ b/src/ZoneLoading/Game/T5/ContentLoaderT5.cpp @@ -39,8 +39,9 @@ using namespace T5; -ContentLoader::ContentLoader() - : varXAsset(nullptr), +ContentLoader::ContentLoader(Zone& zone) + : ContentLoaderBase(zone), + varXAsset(nullptr), varScriptStringList(nullptr) { } @@ -61,12 +62,12 @@ void ContentLoader::LoadScriptStringList(const bool atStreamStart) LoadXStringArray(true, varScriptStringList->count); if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); + m_zone.m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); } m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone.m_script_strings.Count() <= SCR_STRING_MAX + 1); } void ContentLoader::LoadXAsset(const bool atStreamStart) const @@ -74,7 +75,7 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const #define LOAD_ASSET(type_index, typeName, headerEntry) \ case type_index: \ { \ - Loader_##typeName loader(m_zone, m_stream); \ + Loader_##typeName loader(m_zone, *m_stream); \ loader.Load(&varXAsset->header.headerEntry); \ break; \ } @@ -146,10 +147,9 @@ void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) +void ContentLoader::Load(ZoneInputStream& stream) { - m_zone = zone; - m_stream = stream; + m_stream = &stream; m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); diff --git a/src/ZoneLoading/Game/T5/ContentLoaderT5.h b/src/ZoneLoading/Game/T5/ContentLoaderT5.h index e924514b..3fd035f4 100644 --- a/src/ZoneLoading/Game/T5/ContentLoaderT5.h +++ b/src/ZoneLoading/Game/T5/ContentLoaderT5.h @@ -1,4 +1,5 @@ #pragma once + #include "Game/T5/T5.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" @@ -7,17 +8,18 @@ namespace T5 { class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; + public: + explicit ContentLoader(Zone& zone); + void Load(ZoneInputStream& stream) override; + + private: void LoadScriptStringList(bool atStreamStart); void LoadXAsset(bool atStreamStart) const; void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); - - void Load(Zone* zone, IZoneInputStream* stream) override; + XAsset* varXAsset; + ScriptStringList* varScriptStringList; }; } // namespace T5 diff --git a/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.cpp index f25439f9..dff82fb6 100644 --- a/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.cpp @@ -5,7 +5,7 @@ using namespace T5; -Actions_GfxImage::Actions_GfxImage(Zone* zone) +Actions_GfxImage::Actions_GfxImage(Zone& zone) : AssetLoadingActions(zone) { } @@ -19,6 +19,6 @@ void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) { const size_t loadDefSize = offsetof(GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast(m_zone->GetMemory()->AllocRaw(loadDefSize)); + image->texture.loadDef = static_cast(m_zone.Memory().AllocRaw(loadDefSize)); memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.h index bc98aefe..9648cee2 100644 --- a/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.h @@ -8,7 +8,7 @@ namespace T5 class Actions_GfxImage final : public AssetLoadingActions { public: - explicit Actions_GfxImage(Zone* zone); + explicit Actions_GfxImage(Zone& zone); void OnImageLoaded(GfxImage* image) const; void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; diff --git a/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.cpp b/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.cpp index d1fa61fd..e04c9ead 100644 --- a/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.cpp +++ b/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.cpp @@ -10,6 +10,7 @@ #include "Loading/Steps/StepAddProcessor.h" #include "Loading/Steps/StepAllocXBlocks.h" #include "Loading/Steps/StepLoadZoneContent.h" +#include "Loading/Steps/StepLoadZoneSizes.h" #include "Loading/Steps/StepSkipBytes.h" #include "Utils/ClassUtils.h" @@ -77,16 +78,15 @@ std::unique_ptr ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& SetupBlock(*zoneLoader); - zoneLoader->AddLoadingStep(std::make_unique(std::make_unique(ZoneConstants::AUTHED_CHUNK_SIZE))); + zoneLoader->AddLoadingStep(step::CreateStepAddProcessor(processor::CreateProcessorInflate(ZoneConstants::AUTHED_CHUNK_SIZE))); // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique(8)); - // Skip size and externalSize fields since they are not interesting for us - zoneLoader->AddLoadingStep(std::make_unique()); + zoneLoader->AddLoadingStep(step::CreateStepLoadZoneSizes()); + zoneLoader->AddLoadingStep(step::CreateStepAllocXBlocks()); // Start of the zone content zoneLoader->AddLoadingStep( - std::make_unique(std::make_unique(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + step::CreateStepLoadZoneContent(std::make_unique(*zonePtr), ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); return zoneLoader; } diff --git a/src/ZoneLoading/Game/T6/ContentLoaderT6.cpp b/src/ZoneLoading/Game/T6/ContentLoaderT6.cpp index 2b54ebc1..287da637 100644 --- a/src/ZoneLoading/Game/T6/ContentLoaderT6.cpp +++ b/src/ZoneLoading/Game/T6/ContentLoaderT6.cpp @@ -55,8 +55,9 @@ using namespace T6; -ContentLoader::ContentLoader() - : varXAsset(nullptr), +ContentLoader::ContentLoader(Zone& zone) + : ContentLoaderBase(zone), + varXAsset(nullptr), varScriptStringList(nullptr) { } @@ -77,12 +78,12 @@ void ContentLoader::LoadScriptStringList(const bool atStreamStart) LoadXStringArray(true, varScriptStringList->count); if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); + m_zone.m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast(varScriptStringList->count)); } m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone.m_script_strings.Count() <= SCR_STRING_MAX + 1); } void ContentLoader::LoadXAsset(const bool atStreamStart) const @@ -90,7 +91,7 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const #define LOAD_ASSET(type_index, typeName, headerEntry) \ case type_index: \ { \ - Loader_##typeName loader(m_zone, m_stream); \ + Loader_##typeName loader(m_zone, *m_stream); \ loader.Load(&varXAsset->header.headerEntry); \ break; \ } @@ -175,10 +176,9 @@ void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) +void ContentLoader::Load(ZoneInputStream& stream) { - m_zone = zone; - m_stream = stream; + m_stream = &stream; m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); diff --git a/src/ZoneLoading/Game/T6/ContentLoaderT6.h b/src/ZoneLoading/Game/T6/ContentLoaderT6.h index fc88dc59..1ef06b3a 100644 --- a/src/ZoneLoading/Game/T6/ContentLoaderT6.h +++ b/src/ZoneLoading/Game/T6/ContentLoaderT6.h @@ -1,4 +1,5 @@ #pragma once + #include "Game/T6/T6.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" @@ -7,17 +8,18 @@ namespace T6 { class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; + public: + explicit ContentLoader(Zone& zone); + void Load(ZoneInputStream& stream) override; + + private: void LoadScriptStringList(bool atStreamStart); void LoadXAsset(bool atStreamStart) const; void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); - - void Load(Zone* zone, IZoneInputStream* stream) override; + XAsset* varXAsset; + ScriptStringList* varScriptStringList; }; } // namespace T6 diff --git a/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.cpp index 532b515d..41763a0d 100644 --- a/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.cpp @@ -5,7 +5,7 @@ using namespace T6; -Actions_GfxImage::Actions_GfxImage(Zone* zone) +Actions_GfxImage::Actions_GfxImage(Zone& zone) : AssetLoadingActions(zone) { } @@ -19,6 +19,6 @@ void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) { const size_t loadDefSize = offsetof(T6::GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast(m_zone->GetMemory()->AllocRaw(loadDefSize)); + image->texture.loadDef = static_cast(m_zone.Memory().AllocRaw(loadDefSize)); memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.h index d938ff6f..41f7b188 100644 --- a/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.h @@ -8,7 +8,7 @@ namespace T6 class Actions_GfxImage final : public AssetLoadingActions { public: - explicit Actions_GfxImage(Zone* zone); + explicit Actions_GfxImage(Zone& zone); void OnImageLoaded(GfxImage* image) const; void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; diff --git a/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp b/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp index 09642fd6..e2bb2d24 100644 --- a/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp +++ b/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp @@ -35,7 +35,7 @@ namespace for (const auto& languagePrefix : languagePrefixes) { - if (zoneName.compare(0, languagePrefix.m_prefix.length(), languagePrefix.m_prefix) == 0) + if (zoneName.starts_with(languagePrefix.m_prefix)) { return languagePrefix.m_language; } @@ -128,17 +128,17 @@ namespace } } - ISignatureProvider* AddAuthHeaderSteps(const bool isSecure, ZoneLoader& zoneLoader, std::string& fileName) + ISignatureProvider* AddAuthHeaderSteps(const bool isSecure, ZoneLoader& zoneLoader, const std::string& fileName) { // Unsigned zones do not have an auth header if (!isSecure) return nullptr; - zoneLoader.AddLoadingStep(std::make_unique(ZoneConstants::MAGIC_AUTH_HEADER)); - zoneLoader.AddLoadingStep(std::make_unique(4)); // Loading Flags which are always zero - zoneLoader.AddLoadingStep(std::make_unique(fileName, 32)); + zoneLoader.AddLoadingStep(step::CreateStepVerifyMagic(ZoneConstants::MAGIC_AUTH_HEADER)); + zoneLoader.AddLoadingStep(step::CreateStepSkipBytes(4)); // Loading Flags which are always zero + zoneLoader.AddLoadingStep(step::CreateStepVerifyFileName(fileName, 32)); - auto signatureLoadStep = std::make_unique(256); + auto signatureLoadStep = step::CreateStepLoadSignature(256); auto* signatureLoadStepPtr = signatureLoadStep.get(); zoneLoader.AddLoadingStep(std::move(signatureLoadStep)); @@ -148,7 +148,7 @@ namespace ICapturedDataProvider* AddXChunkProcessor(const bool isEncrypted, ZoneLoader& zoneLoader, std::string& fileName) { ICapturedDataProvider* result = nullptr; - auto xChunkProcessor = std::make_unique(ZoneConstants::STREAM_COUNT, ZoneConstants::XCHUNK_SIZE, ZoneConstants::VANILLA_BUFFER_SIZE); + auto xChunkProcessor = processor::CreateProcessorXChunks(ZoneConstants::STREAM_COUNT, ZoneConstants::XCHUNK_SIZE, ZoneConstants::VANILLA_BUFFER_SIZE); if (isEncrypted) { @@ -161,7 +161,7 @@ namespace // Decompress the chunks using zlib xChunkProcessor->AddChunkProcessor(std::make_unique()); - zoneLoader.AddLoadingStep(std::make_unique(std::move(xChunkProcessor))); + zoneLoader.AddLoadingStep(step::CreateStepAddProcessor(std::move(xChunkProcessor))); // If there is encryption, the signed data of the zone is the final hash blocks provided by the Salsa20 IV adaption algorithm return result; @@ -199,16 +199,16 @@ std::unique_ptr ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& ICapturedDataProvider* signatureDataProvider = AddXChunkProcessor(isEncrypted, *zoneLoader, fileName); // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique()); - zoneLoader->AddLoadingStep(std::make_unique()); + zoneLoader->AddLoadingStep(step::CreateStepLoadZoneSizes()); + zoneLoader->AddLoadingStep(step::CreateStepAllocXBlocks()); // Start of the zone content zoneLoader->AddLoadingStep( - std::make_unique(std::make_unique(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + step::CreateStepLoadZoneContent(std::make_unique(*zonePtr), ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); if (isSecure) { - zoneLoader->AddLoadingStep(std::make_unique(std::move(rsa), signatureProvider, signatureDataProvider)); + zoneLoader->AddLoadingStep(step::CreateStepVerifySignature(std::move(rsa), signatureProvider, signatureDataProvider)); } return zoneLoader; diff --git a/src/ZoneLoading/Loading/AssetLoader.cpp b/src/ZoneLoading/Loading/AssetLoader.cpp index 868aae62..18c660a6 100644 --- a/src/ZoneLoading/Loading/AssetLoader.cpp +++ b/src/ZoneLoading/Loading/AssetLoader.cpp @@ -3,10 +3,10 @@ #include #include -AssetLoader::AssetLoader(const asset_type_t assetType, Zone* zone, IZoneInputStream* stream) +AssetLoader::AssetLoader(const asset_type_t assetType, Zone& zone, ZoneInputStream& stream) : ContentLoaderBase(zone, stream), - m_asset_type(assetType), - varScriptString(nullptr) + varScriptString(nullptr), + m_asset_type(assetType) { } @@ -16,11 +16,11 @@ XAssetInfoGeneric* AssetLoader::LinkAsset(std::string name, std::vector scriptStrings, std::vector indirectAssetReferences) const { - return m_zone->m_pools->AddAsset( + return m_zone.m_pools->AddAsset( m_asset_type, std::move(name), asset, std::move(dependencies), std::move(scriptStrings), std::move(indirectAssetReferences)); } XAssetInfoGeneric* AssetLoader::GetAssetInfo(const std::string& name) const { - return m_zone->m_pools->GetAsset(m_asset_type, name); + return m_zone.m_pools->GetAsset(m_asset_type, name); } diff --git a/src/ZoneLoading/Loading/AssetLoader.h b/src/ZoneLoading/Loading/AssetLoader.h index dd9e2c04..67257069 100644 --- a/src/ZoneLoading/Loading/AssetLoader.h +++ b/src/ZoneLoading/Loading/AssetLoader.h @@ -4,17 +4,12 @@ #include "Pool/XAssetInfo.h" #include "Zone/ZoneTypes.h" -#include #include class AssetLoader : public ContentLoaderBase { - asset_type_t m_asset_type; - protected: - scr_string_t* varScriptString; - - AssetLoader(asset_type_t assetType, Zone* zone, IZoneInputStream* stream); + AssetLoader(asset_type_t assetType, Zone& zone, ZoneInputStream& stream); XAssetInfoGeneric* LinkAsset(std::string name, void* asset, @@ -22,5 +17,10 @@ protected: std::vector scriptStrings, std::vector indirectAssetReferences) const; - _NODISCARD XAssetInfoGeneric* GetAssetInfo(const std::string& name) const; + [[nodiscard]] XAssetInfoGeneric* GetAssetInfo(const std::string& name) const; + + scr_string_t* varScriptString; + +private: + asset_type_t m_asset_type; }; diff --git a/src/ZoneLoading/Loading/AssetLoadingActions.cpp b/src/ZoneLoading/Loading/AssetLoadingActions.cpp index 2908a982..f1ff127e 100644 --- a/src/ZoneLoading/Loading/AssetLoadingActions.cpp +++ b/src/ZoneLoading/Loading/AssetLoadingActions.cpp @@ -1,6 +1,6 @@ #include "AssetLoadingActions.h" -AssetLoadingActions::AssetLoadingActions(Zone* zone) +AssetLoadingActions::AssetLoadingActions(Zone& zone) + : m_zone(zone) { - m_zone = zone; } diff --git a/src/ZoneLoading/Loading/AssetLoadingActions.h b/src/ZoneLoading/Loading/AssetLoadingActions.h index 37e7a781..6e2ccb62 100644 --- a/src/ZoneLoading/Loading/AssetLoadingActions.h +++ b/src/ZoneLoading/Loading/AssetLoadingActions.h @@ -4,9 +4,9 @@ class AssetLoadingActions { -protected: - Zone* m_zone; - public: - explicit AssetLoadingActions(Zone* zone); + explicit AssetLoadingActions(Zone& zone); + +protected: + Zone& m_zone; }; diff --git a/src/ZoneLoading/Loading/AssetMarker.cpp b/src/ZoneLoading/Loading/AssetMarker.cpp index 2761fed3..c215c7cf 100644 --- a/src/ZoneLoading/Loading/AssetMarker.cpp +++ b/src/ZoneLoading/Loading/AssetMarker.cpp @@ -3,9 +3,9 @@ #include #include -AssetMarker::AssetMarker(const asset_type_t assetType, Zone* zone) - : m_asset_type(assetType), - m_zone(zone) +AssetMarker::AssetMarker(const asset_type_t assetType, Zone& zone) + : m_zone(zone), + m_asset_type(assetType) { } @@ -23,9 +23,9 @@ void AssetMarker::AddDependency(XAssetInfoGeneric* assetInfo) void AssetMarker::Mark_ScriptString(const scr_string_t scrString) { - assert(scrString < m_zone->m_script_strings.Count()); + assert(scrString < m_zone.m_script_strings.Count()); - if (scrString >= m_zone->m_script_strings.Count()) + if (scrString >= m_zone.m_script_strings.Count()) return; m_used_script_strings.emplace(scrString); @@ -57,7 +57,7 @@ void AssetMarker::MarkArray_IndirectAssetRef(const asset_type_t type, const char XAssetInfoGeneric* AssetMarker::GetAssetInfoByName(const std::string& name) const { - return m_zone->m_pools->GetAsset(m_asset_type, name); + return m_zone.m_pools->GetAsset(m_asset_type, name); } std::vector AssetMarker::GetDependencies() const diff --git a/src/ZoneLoading/Loading/AssetMarker.h b/src/ZoneLoading/Loading/AssetMarker.h index bb24c1b1..3507db4b 100644 --- a/src/ZoneLoading/Loading/AssetMarker.h +++ b/src/ZoneLoading/Loading/AssetMarker.h @@ -2,21 +2,19 @@ #include "ContentLoaderBase.h" #include "Pool/XAssetInfo.h" -#include "Utils/ClassUtils.h" #include "Zone/ZoneTypes.h" #include class AssetMarker { - asset_type_t m_asset_type; - - std::unordered_set m_dependencies; - std::unordered_set m_used_script_strings; - std::unordered_set m_indirect_asset_references; +public: + [[nodiscard]] std::vector GetDependencies() const; + [[nodiscard]] std::vector GetUsedScriptStrings() const; + [[nodiscard]] std::vector GetIndirectAssetReferences() const; protected: - AssetMarker(asset_type_t assetType, Zone* zone); + AssetMarker(asset_type_t assetType, Zone& zone); void AddDependency(XAssetInfoGeneric* assetInfo); @@ -26,12 +24,14 @@ protected: void Mark_IndirectAssetRef(asset_type_t type, const char* assetRefName); void MarkArray_IndirectAssetRef(asset_type_t type, const char** assetRefNames, size_t count); - _NODISCARD XAssetInfoGeneric* GetAssetInfoByName(const std::string& name) const; + [[nodiscard]] XAssetInfoGeneric* GetAssetInfoByName(const std::string& name) const; - Zone* m_zone; + Zone& m_zone; -public: - _NODISCARD std::vector GetDependencies() const; - _NODISCARD std::vector GetUsedScriptStrings() const; - _NODISCARD std::vector GetIndirectAssetReferences() const; +private: + asset_type_t m_asset_type; + + std::unordered_set m_dependencies; + std::unordered_set m_used_script_strings; + std::unordered_set m_indirect_asset_references; }; diff --git a/src/ZoneLoading/Loading/ContentLoaderBase.cpp b/src/ZoneLoading/Loading/ContentLoaderBase.cpp index 8ac12b96..1b4420f6 100644 --- a/src/ZoneLoading/Loading/ContentLoaderBase.cpp +++ b/src/ZoneLoading/Loading/ContentLoaderBase.cpp @@ -5,17 +5,19 @@ const void* ContentLoaderBase::PTR_FOLLOWING = reinterpret_cast(-1); const void* ContentLoaderBase::PTR_INSERT = reinterpret_cast(-2); -ContentLoaderBase::ContentLoaderBase() +ContentLoaderBase::ContentLoaderBase(Zone& zone) : varXString(nullptr), - m_zone(nullptr), + m_zone(zone), + m_memory(zone.Memory()), m_stream(nullptr) { } -ContentLoaderBase::ContentLoaderBase(Zone* zone, IZoneInputStream* stream) +ContentLoaderBase::ContentLoaderBase(Zone& zone, ZoneInputStream& stream) : varXString(nullptr), m_zone(zone), - m_stream(stream) + m_memory(zone.Memory()), + m_stream(&stream) { } diff --git a/src/ZoneLoading/Loading/ContentLoaderBase.h b/src/ZoneLoading/Loading/ContentLoaderBase.h index eba6aac2..51fe7cc8 100644 --- a/src/ZoneLoading/Loading/ContentLoaderBase.h +++ b/src/ZoneLoading/Loading/ContentLoaderBase.h @@ -1,6 +1,6 @@ #pragma once -#include "Zone/Stream/IZoneInputStream.h" +#include "Zone/Stream/ZoneInputStream.h" #include "Zone/Zone.h" class ContentLoaderBase @@ -9,17 +9,23 @@ protected: static const void* PTR_FOLLOWING; static const void* PTR_INSERT; - const char** varXString; +public: + virtual ~ContentLoaderBase() = default; + ContentLoaderBase(const ContentLoaderBase& other) = default; + ContentLoaderBase(ContentLoaderBase&& other) noexcept = default; + ContentLoaderBase& operator=(const ContentLoaderBase& other) = delete; + ContentLoaderBase& operator=(ContentLoaderBase&& other) noexcept = delete; - Zone* m_zone; - IZoneInputStream* m_stream; - - ContentLoaderBase(); - ContentLoaderBase(Zone* zone, IZoneInputStream* stream); +protected: + explicit ContentLoaderBase(Zone& zone); + ContentLoaderBase(Zone& zone, ZoneInputStream& stream); void LoadXString(bool atStreamStart) const; void LoadXStringArray(bool atStreamStart, size_t count); -public: - virtual ~ContentLoaderBase() = default; + const char** varXString; + + Zone& m_zone; + MemoryManager& m_memory; + ZoneInputStream* m_stream; }; diff --git a/src/ZoneLoading/Loading/IContentLoadingEntryPoint.h b/src/ZoneLoading/Loading/IContentLoadingEntryPoint.h index 3ffda768..25a8db46 100644 --- a/src/ZoneLoading/Loading/IContentLoadingEntryPoint.h +++ b/src/ZoneLoading/Loading/IContentLoadingEntryPoint.h @@ -1,12 +1,16 @@ #pragma once -#include "Zone/Stream/IZoneInputStream.h" -#include "Zone/Zone.h" +#include "Zone/Stream/ZoneInputStream.h" class IContentLoadingEntryPoint { public: + IContentLoadingEntryPoint() = default; virtual ~IContentLoadingEntryPoint() = default; + IContentLoadingEntryPoint(const IContentLoadingEntryPoint& other) = default; + IContentLoadingEntryPoint(IContentLoadingEntryPoint&& other) noexcept = default; + IContentLoadingEntryPoint& operator=(const IContentLoadingEntryPoint& other) = default; + IContentLoadingEntryPoint& operator=(IContentLoadingEntryPoint&& other) noexcept = default; - virtual void Load(Zone* zone, IZoneInputStream* stream) = 0; + virtual void Load(ZoneInputStream& stream) = 0; }; diff --git a/src/ZoneLoading/Loading/IHashProvider.h b/src/ZoneLoading/Loading/IHashProvider.h index da76becb..16d4d1d2 100644 --- a/src/ZoneLoading/Loading/IHashProvider.h +++ b/src/ZoneLoading/Loading/IHashProvider.h @@ -6,5 +6,12 @@ class IHashProvider { public: + IHashProvider() = default; + virtual ~IHashProvider() = default; + IHashProvider(const IHashProvider& other) = default; + IHashProvider(IHashProvider&& other) noexcept = default; + IHashProvider& operator=(const IHashProvider& other) = default; + IHashProvider& operator=(IHashProvider&& other) noexcept = default; + virtual void GetHash(unsigned hashIndex, const uint8_t** pHash, size_t* pSize) = 0; }; diff --git a/src/ZoneLoading/Loading/ILoadingStep.h b/src/ZoneLoading/Loading/ILoadingStep.h index 6f29f718..dc2f402f 100644 --- a/src/ZoneLoading/Loading/ILoadingStep.h +++ b/src/ZoneLoading/Loading/ILoadingStep.h @@ -8,7 +8,12 @@ class ZoneLoader; class ILoadingStep { public: + ILoadingStep() = default; virtual ~ILoadingStep() = default; + ILoadingStep(const ILoadingStep& other) = default; + ILoadingStep(ILoadingStep&& other) noexcept = default; + ILoadingStep& operator=(const ILoadingStep& other) = default; + ILoadingStep& operator=(ILoadingStep&& other) noexcept = default; - virtual void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) = 0; + virtual void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) = 0; }; diff --git a/src/ZoneLoading/Loading/ISignatureProvider.h b/src/ZoneLoading/Loading/ISignatureProvider.h index 009eaaea..590ff5f4 100644 --- a/src/ZoneLoading/Loading/ISignatureProvider.h +++ b/src/ZoneLoading/Loading/ISignatureProvider.h @@ -4,5 +4,12 @@ class ISignatureProvider { public: + ISignatureProvider() = default; + virtual ~ISignatureProvider() = default; + ISignatureProvider(const ISignatureProvider& other) = default; + ISignatureProvider(ISignatureProvider&& other) noexcept = default; + ISignatureProvider& operator=(const ISignatureProvider& other) = default; + ISignatureProvider& operator=(ISignatureProvider&& other) noexcept = default; + virtual void GetSignature(const uint8_t** pSignature, size_t* pSize) = 0; }; diff --git a/src/ZoneLoading/Loading/LoadingFileStream.h b/src/ZoneLoading/Loading/LoadingFileStream.h index 8073f477..170e091d 100644 --- a/src/ZoneLoading/Loading/LoadingFileStream.h +++ b/src/ZoneLoading/Loading/LoadingFileStream.h @@ -1,15 +1,18 @@ #pragma once + #include "ILoadingStream.h" +#include #include class LoadingFileStream final : public ILoadingStream { - std::istream& m_stream; - public: explicit LoadingFileStream(std::istream& stream); size_t Load(void* buffer, size_t length) override; int64_t Pos() override; + +private: + std::istream& m_stream; }; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp index cc5c8f39..1f3498cc 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp @@ -5,39 +5,20 @@ #include "Loading/Exception/TooManyAuthedGroupsException.h" #include "Loading/Exception/UnexpectedEndOfFileException.h" +#include #include #include #include -class ProcessorAuthedBlocks::Impl +class ProcessorAuthedBlocks final : public StreamProcessor { - ProcessorAuthedBlocks* const m_base; - - const unsigned m_authed_chunk_count; - const size_t m_chunk_size; - const unsigned m_max_master_block_count; - - const std::unique_ptr m_hash_function; - IHashProvider* const m_master_block_hash_provider; - const std::unique_ptr m_chunk_hashes_buffer; - const std::unique_ptr m_current_chunk_hash_buffer; - - const std::unique_ptr m_chunk_buffer; - unsigned m_current_group; - unsigned m_current_chunk_in_group; - - size_t m_current_chunk_offset; - size_t m_current_chunk_size; - public: - Impl(ProcessorAuthedBlocks* base, - const unsigned authedChunkCount, - const size_t chunkSize, - const unsigned maxMasterBlockCount, - std::unique_ptr hashFunction, - IHashProvider* masterBlockHashProvider) - : m_base(base), - m_authed_chunk_count(authedChunkCount), + ProcessorAuthedBlocks(const unsigned authedChunkCount, + const size_t chunkSize, + const unsigned maxMasterBlockCount, + std::unique_ptr hashFunction, + IHashProvider* masterBlockHashProvider) + : m_authed_chunk_count(authedChunkCount), m_chunk_size(chunkSize), m_max_master_block_count(maxMasterBlockCount), m_hash_function(std::move(hashFunction)), @@ -53,13 +34,43 @@ public: assert(m_authed_chunk_count * m_hash_function->GetHashSize() <= m_chunk_size); } + size_t Load(void* buffer, const size_t length) override + { + size_t loadedSize = 0; + + while (loadedSize < length) + { + if (m_current_chunk_offset >= m_current_chunk_size) + { + if (!NextChunk()) + return loadedSize; + } + + auto sizeToWrite = length - loadedSize; + sizeToWrite = std::min(sizeToWrite, m_current_chunk_size - m_current_chunk_offset); + + assert(length - loadedSize >= sizeToWrite); + std::memcpy(&static_cast(buffer)[loadedSize], &m_chunk_buffer[m_current_chunk_offset], sizeToWrite); + loadedSize += sizeToWrite; + m_current_chunk_offset += sizeToWrite; + } + + return loadedSize; + } + + int64_t Pos() override + { + return m_base_stream->Pos() - static_cast(m_current_chunk_size - m_current_chunk_offset); + } + +private: bool NextChunk() { m_current_chunk_offset = 0; while (true) { - m_current_chunk_size = m_base->m_base_stream->Load(m_chunk_buffer.get(), m_chunk_size); + m_current_chunk_size = m_base_stream->Load(m_chunk_buffer.get(), m_chunk_size); if (m_current_chunk_size == 0) return false; @@ -79,7 +90,9 @@ public: if (masterBlockHashSize != m_hash_function->GetHashSize() || std::memcmp(m_current_chunk_hash_buffer.get(), masterBlockHash, m_hash_function->GetHashSize()) != 0) + { throw InvalidHashException(); + } memcpy(m_chunk_hashes_buffer.get(), m_chunk_buffer.get(), m_authed_chunk_count * m_hash_function->GetHashSize()); @@ -91,7 +104,9 @@ public: &m_chunk_hashes_buffer[(m_current_chunk_in_group - 1) * m_hash_function->GetHashSize()], m_hash_function->GetHashSize()) != 0) + { throw InvalidHashException(); + } if (++m_current_chunk_in_group > m_authed_chunk_count) { @@ -107,58 +122,31 @@ public: } } - size_t Load(void* buffer, const size_t length) - { - size_t loadedSize = 0; + const unsigned m_authed_chunk_count; + const size_t m_chunk_size; + const unsigned m_max_master_block_count; - while (loadedSize < length) - { - if (m_current_chunk_offset >= m_current_chunk_size) - { - if (!NextChunk()) - return loadedSize; - } + const std::unique_ptr m_hash_function; + IHashProvider* const m_master_block_hash_provider; + const std::unique_ptr m_chunk_hashes_buffer; + const std::unique_ptr m_current_chunk_hash_buffer; - size_t sizeToWrite = length - loadedSize; - if (sizeToWrite > m_current_chunk_size - m_current_chunk_offset) - sizeToWrite = m_current_chunk_size - m_current_chunk_offset; + const std::unique_ptr m_chunk_buffer; + unsigned m_current_group; + unsigned m_current_chunk_in_group; - assert(length - loadedSize >= sizeToWrite); - memcpy(&static_cast(buffer)[loadedSize], &m_chunk_buffer[m_current_chunk_offset], sizeToWrite); - loadedSize += sizeToWrite; - m_current_chunk_offset += sizeToWrite; - } - - return loadedSize; - } - - int64_t Pos() - { - return m_base->m_base_stream->Pos() - (m_current_chunk_size - m_current_chunk_offset); - } + size_t m_current_chunk_offset; + size_t m_current_chunk_size; }; -ProcessorAuthedBlocks::ProcessorAuthedBlocks(const unsigned authedChunkCount, - const size_t chunkSize, - const unsigned maxMasterBlockCount, - std::unique_ptr hashFunction, - IHashProvider* masterBlockHashProvider) - : m_impl(new Impl(this, authedChunkCount, chunkSize, maxMasterBlockCount, std::move(hashFunction), masterBlockHashProvider)) +namespace processor { -} - -ProcessorAuthedBlocks::~ProcessorAuthedBlocks() -{ - delete m_impl; - m_impl = nullptr; -} - -size_t ProcessorAuthedBlocks::Load(void* buffer, const size_t length) -{ - return m_impl->Load(buffer, length); -} - -int64_t ProcessorAuthedBlocks::Pos() -{ - return m_impl->Pos(); -} + std::unique_ptr CreateProcessorAuthedBlocks(unsigned authedChunkCount, + size_t chunkSize, + unsigned maxMasterBlockCount, + std::unique_ptr hashFunction, + IHashProvider* masterBlockHashProvider) + { + return std::make_unique(authedChunkCount, chunkSize, maxMasterBlockCount, std::move(hashFunction), masterBlockHashProvider); + } +} // namespace processor diff --git a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h index 5bcf4a19..f6cf4883 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h @@ -6,23 +6,11 @@ #include -class ProcessorAuthedBlocks final : public StreamProcessor +namespace processor { - class Impl; - Impl* m_impl; - -public: - ProcessorAuthedBlocks(unsigned authedChunkCount, - size_t chunkSize, - unsigned maxMasterBlockCount, - std::unique_ptr hashFunction, - IHashProvider* masterBlockHashProvider); - ~ProcessorAuthedBlocks() override; - ProcessorAuthedBlocks(const ProcessorAuthedBlocks& other) = delete; - ProcessorAuthedBlocks(ProcessorAuthedBlocks&& other) noexcept = default; - ProcessorAuthedBlocks& operator=(const ProcessorAuthedBlocks& other) = delete; - ProcessorAuthedBlocks& operator=(ProcessorAuthedBlocks&& other) noexcept = default; - - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; -}; + std::unique_ptr CreateProcessorAuthedBlocks(unsigned authedChunkCount, + size_t chunkSize, + unsigned maxMasterBlockCount, + std::unique_ptr hashFunction, + IHashProvider* masterBlockHashProvider); +} diff --git a/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.cpp b/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.cpp index f0b1b3b5..2cf88b17 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.cpp @@ -1,51 +1,68 @@ #include "ProcessorCaptureData.h" +#include #include #include -ProcessorCaptureData::ProcessorCaptureData(const size_t captureSize) - : m_data(std::make_unique(captureSize)), - m_capture_size(captureSize), - m_captured_data_size(0) +namespace { -} + class ProcessorCaptureData final : public processor::IProcessorCaptureData + { + public: + explicit ProcessorCaptureData(const size_t captureSize) + : m_data(std::make_unique(captureSize)), + m_capture_size(captureSize), + m_captured_data_size(0) + { + } -ProcessorCaptureData::~ProcessorCaptureData() = default; + size_t Load(void* buffer, const size_t length) override + { + if (m_captured_data_size >= m_capture_size) + return m_base_stream->Load(buffer, length); -size_t ProcessorCaptureData::Load(void* buffer, const size_t length) + auto dataToCapture = m_capture_size - m_captured_data_size; + dataToCapture = std::min(length, dataToCapture); + + auto loadedSize = m_base_stream->Load(&m_data[m_captured_data_size], dataToCapture); + assert(length >= loadedSize); + std::memcpy(buffer, &m_data[m_captured_data_size], loadedSize); + + m_captured_data_size += loadedSize; + + if (length > dataToCapture) + loadedSize += m_base_stream->Load(&static_cast(buffer)[dataToCapture], length - dataToCapture); + + return loadedSize; + } + + int64_t Pos() override + { + return m_base_stream->Pos(); + } + + void GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) override + { + assert(pCapturedData != nullptr); + assert(pSize != nullptr); + + assert(m_captured_data_size == m_capture_size); + + *pCapturedData = m_data.get(); + *pSize = m_captured_data_size; + } + + private: + std::unique_ptr m_data; + size_t m_capture_size; + size_t m_captured_data_size; + }; +} // namespace + +namespace processor { - if (m_captured_data_size >= m_capture_size) - return m_base_stream->Load(buffer, length); - - size_t dataToCapture = m_capture_size - m_captured_data_size; - - if (length < dataToCapture) - dataToCapture = length; - - size_t loadedSize = m_base_stream->Load(&m_data[m_captured_data_size], dataToCapture); - assert(length >= loadedSize); - memcpy(buffer, &m_data[m_captured_data_size], loadedSize); - - m_captured_data_size += loadedSize; - - if (length > dataToCapture) - loadedSize += m_base_stream->Load(&static_cast(buffer)[dataToCapture], length - dataToCapture); - - return loadedSize; -} - -int64_t ProcessorCaptureData::Pos() -{ - return m_base_stream->Pos(); -} - -void ProcessorCaptureData::GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) -{ - assert(pCapturedData != nullptr); - assert(pSize != nullptr); - - assert(m_captured_data_size == m_capture_size); - - *pCapturedData = m_data.get(); - *pSize = m_captured_data_size; -} + std::unique_ptr CreateProcessorCaptureData(size_t captureSize) + { + return std::make_unique(captureSize); + } +} // namespace processor diff --git a/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.h b/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.h index 4d6fac57..810b9ad1 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.h @@ -1,20 +1,15 @@ #pragma once + #include "Loading/StreamProcessor.h" #include "Utils/ICapturedDataProvider.h" #include -class ProcessorCaptureData final : public StreamProcessor, public ICapturedDataProvider +namespace processor { - std::unique_ptr m_data; - const size_t m_capture_size; - size_t m_captured_data_size; + class IProcessorCaptureData : public StreamProcessor, public ICapturedDataProvider + { + }; -public: - explicit ProcessorCaptureData(size_t captureSize); - ~ProcessorCaptureData() override; - - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; - void GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) override; -}; + std::unique_ptr CreateProcessorCaptureData(size_t captureSize); +} // namespace processor diff --git a/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.cpp b/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.cpp index c26157f9..393a5f4d 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.cpp @@ -2,44 +2,62 @@ #include -ProcessorIW4xDecryption::ProcessorIW4xDecryption() - : m_last_byte(0u) +namespace { -} - -uint8_t ProcessorIW4xDecryption::RotateLeft(const uint8_t value, const unsigned count) -{ - assert(count < sizeof(value) * 8); - return static_cast(value << count | (value >> ((sizeof(value) * 8) - count))); -} - -uint8_t ProcessorIW4xDecryption::RotateRight(uint8_t value, const unsigned count) -{ - assert(count < sizeof(value) * 8); - return static_cast(value >> count | (value << ((sizeof(value) * 8) - count))); -} - -size_t ProcessorIW4xDecryption::Load(void* buffer, const size_t length) -{ - const auto readLen = m_base_stream->Load(buffer, length); - - auto* charBuffer = static_cast(buffer); - for (auto i = 0u; i < readLen; i++) + uint8_t RotateLeft(const uint8_t value, const unsigned count) { - auto value = charBuffer[i]; - value ^= m_last_byte; - value = RotateLeft(value, 4); - value ^= -1; - value = RotateRight(value, 6); - - charBuffer[i] = value; - m_last_byte = value; + assert(count < sizeof(value) * 8); + return static_cast(value << count | (value >> ((sizeof(value) * 8) - count))); } - return readLen; -} + uint8_t RotateRight(const uint8_t value, const unsigned count) + { + assert(count < sizeof(value) * 8); + return static_cast(value >> count | (value << ((sizeof(value) * 8) - count))); + } -int64_t ProcessorIW4xDecryption::Pos() + class ProcessorIW4xDecryption final : public StreamProcessor + { + public: + ProcessorIW4xDecryption() + : m_last_byte(0u) + { + } + + size_t Load(void* buffer, const size_t length) override + { + const auto readLen = m_base_stream->Load(buffer, length); + + auto* charBuffer = static_cast(buffer); + for (auto i = 0u; i < readLen; i++) + { + auto value = charBuffer[i]; + value ^= m_last_byte; + value = RotateLeft(value, 4); + value ^= -1; + value = RotateRight(value, 6); + + charBuffer[i] = value; + m_last_byte = value; + } + + return readLen; + } + + int64_t Pos() override + { + return m_base_stream->Pos(); + } + + private: + uint8_t m_last_byte; + }; +} // namespace + +namespace processor { - return m_base_stream->Pos(); -} + std::unique_ptr CreateProcessorIW4xDecryption() + { + return std::make_unique(); + } +} // namespace processor diff --git a/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.h b/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.h index 6f9acc37..19946be9 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.h @@ -1,16 +1,10 @@ #pragma once + #include "Loading/StreamProcessor.h" -class ProcessorIW4xDecryption final : public StreamProcessor +#include + +namespace processor { - uint8_t m_last_byte; - - static uint8_t RotateLeft(uint8_t value, unsigned count); - static uint8_t RotateRight(uint8_t value, unsigned count); - -public: - ProcessorIW4xDecryption(); - - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; -}; + std::unique_ptr CreateProcessorIW4xDecryption(); +} diff --git a/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp b/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp index e04de7db..3cca74f6 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp @@ -8,93 +8,85 @@ #include #include -class ProcessorInflate::Impl +namespace { - z_stream m_stream{}; - ProcessorInflate* m_base; + constexpr size_t DEFAULT_BUFFER_SIZE = 0x2000; - std::unique_ptr m_buffer; - size_t m_buffer_size; - -public: - Impl(ProcessorInflate* baseClass, const size_t bufferSize) - : m_buffer(std::make_unique(bufferSize)), - m_buffer_size(bufferSize) + class ProcessorInflate final : public StreamProcessor { - m_base = baseClass; - - m_stream.zalloc = Z_NULL; - m_stream.zfree = Z_NULL; - m_stream.opaque = Z_NULL; - m_stream.avail_in = 0; - m_stream.next_in = Z_NULL; - - const int ret = inflateInit(&m_stream); - - if (ret != Z_OK) + public: + explicit ProcessorInflate(const size_t bufferSize) + : m_buffer(std::make_unique(bufferSize)), + m_buffer_size(bufferSize) { - throw std::runtime_error("Initializing inflate failed"); + m_stream.zalloc = Z_NULL; + m_stream.zfree = Z_NULL; + m_stream.opaque = Z_NULL; + m_stream.avail_in = 0; + m_stream.next_in = Z_NULL; + + const int ret = inflateInit(&m_stream); + + if (ret != Z_OK) + throw std::runtime_error("Initializing inflate failed"); } - } - ~Impl() - { - inflateEnd(&m_stream); - } - - Impl(const Impl& other) = delete; - Impl(Impl&& other) noexcept = default; - Impl& operator=(const Impl& other) = delete; - Impl& operator=(Impl&& other) noexcept = default; - - size_t Load(void* buffer, const size_t length) - { - m_stream.next_out = static_cast(buffer); - m_stream.avail_out = static_cast(length); - - while (m_stream.avail_out > 0) + ~ProcessorInflate() override { - if (m_stream.avail_in == 0) - { - m_stream.avail_in = static_cast(m_base->m_base_stream->Load(m_buffer.get(), m_buffer_size)); - m_stream.next_in = m_buffer.get(); + inflateEnd(&m_stream); + } - if (m_stream.avail_in == 0) // EOF - return length - m_stream.avail_out; + ProcessorInflate(const ProcessorInflate& other) = delete; + ProcessorInflate(ProcessorInflate&& other) noexcept = default; + ProcessorInflate& operator=(const ProcessorInflate& other) = delete; + ProcessorInflate& operator=(ProcessorInflate&& other) noexcept = default; + + size_t Load(void* buffer, const size_t length) override + { + m_stream.next_out = static_cast(buffer); + m_stream.avail_out = static_cast(length); + + while (m_stream.avail_out > 0) + { + if (m_stream.avail_in == 0) + { + m_stream.avail_in = static_cast(m_base_stream->Load(m_buffer.get(), m_buffer_size)); + m_stream.next_in = m_buffer.get(); + + if (m_stream.avail_in == 0) // EOF + return length - m_stream.avail_out; + } + + const auto ret = inflate(&m_stream, Z_SYNC_FLUSH); + + if (ret < 0) + throw InvalidCompressionException(); } - const auto ret = inflate(&m_stream, Z_SYNC_FLUSH); - - if (ret < 0) - throw InvalidCompressionException(); + return length - m_stream.avail_out; } - return length - m_stream.avail_out; + int64_t Pos() override + { + return m_base_stream->Pos(); + } + + private: + z_stream m_stream{}; + std::unique_ptr m_buffer; + size_t m_buffer_size; + }; +} // namespace + +namespace processor +{ + std::unique_ptr CreateProcessorInflate() + { + return std::make_unique(DEFAULT_BUFFER_SIZE); } -}; -ProcessorInflate::ProcessorInflate() - : ProcessorInflate(DEFAULT_BUFFER_SIZE) -{ -} - -ProcessorInflate::ProcessorInflate(const size_t bufferSize) - : m_impl(new Impl(this, bufferSize)) -{ -} - -ProcessorInflate::~ProcessorInflate() -{ - delete m_impl; - m_impl = nullptr; -} - -size_t ProcessorInflate::Load(void* buffer, const size_t length) -{ - return m_impl->Load(buffer, length); -} - -int64_t ProcessorInflate::Pos() -{ - return m_base_stream->Pos(); -} + std::unique_ptr CreateProcessorInflate(size_t bufferSize) + { + return std::make_unique(bufferSize); + } +} // namespace processor diff --git a/src/ZoneLoading/Loading/Processor/ProcessorInflate.h b/src/ZoneLoading/Loading/Processor/ProcessorInflate.h index f1e17ed5..bf704ee0 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorInflate.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorInflate.h @@ -1,22 +1,11 @@ #pragma once + #include "Loading/StreamProcessor.h" -class ProcessorInflate final : public StreamProcessor +#include + +namespace processor { - class Impl; - Impl* m_impl; - - static constexpr size_t DEFAULT_BUFFER_SIZE = 0x2000; - -public: - ProcessorInflate(); - ProcessorInflate(size_t bufferSize); - ~ProcessorInflate() override; - ProcessorInflate(const ProcessorInflate& other) = delete; - ProcessorInflate(ProcessorInflate&& other) noexcept = default; - ProcessorInflate& operator=(const ProcessorInflate& other) = delete; - ProcessorInflate& operator=(ProcessorInflate&& other) noexcept = default; - - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; -}; + std::unique_ptr CreateProcessorInflate(); + std::unique_ptr CreateProcessorInflate(size_t bufferSize); +} // namespace processor diff --git a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp index 73279921..e74fc044 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp @@ -1,21 +1,44 @@ #include "ProcessorStreamCipher.h" -ProcessorStreamCipher::ProcessorStreamCipher(std::unique_ptr cipher) - : m_cipher(std::move(cipher)) +namespace { -} - -size_t ProcessorStreamCipher::Load(void* buffer, const size_t length) -{ - if (m_base_stream != nullptr) + class ProcessorStreamCipher final : public StreamProcessor { - const size_t readSize = m_base_stream->Load(buffer, length); + public: + explicit ProcessorStreamCipher(std::unique_ptr cipher) + : m_cipher(std::move(cipher)) + { + } - if (readSize > 0) - m_cipher->Process(buffer, buffer, readSize); + size_t Load(void* buffer, const size_t length) override + { + if (m_base_stream != nullptr) + { + const size_t readSize = m_base_stream->Load(buffer, length); - return readSize; + if (readSize > 0) + m_cipher->Process(buffer, buffer, readSize); + + return readSize; + } + + return 0; + } + + int64_t Pos() override + { + return m_base_stream->Pos(); + } + + private: + std::unique_ptr m_cipher; + }; +} // namespace + +namespace processor +{ + std::unique_ptr CreateProcessorStreamCipher(std::unique_ptr cipher) + { + return std::make_unique(std::move(cipher)); } - - return 0; -} +} // namespace processor diff --git a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h index 3b40f4a5..d74908c0 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h @@ -5,13 +5,7 @@ #include -class ProcessorStreamCipher final : public StreamProcessor +namespace processor { -public: - explicit ProcessorStreamCipher(std::unique_ptr cipher); - - size_t Load(void* buffer, size_t length) override; - -private: - std::unique_ptr m_cipher; -}; + std::unique_ptr CreateProcessorStreamCipher(std::unique_ptr cipher); +} diff --git a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp index c0f727c8..6d73eafc 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp @@ -8,331 +8,302 @@ #include #include #include +#include #include #include -class DBLoadStream +namespace { - int m_index; - - std::unique_ptr m_buffers[2]; - - uint8_t* m_input_buffer; - size_t m_input_size; - - uint8_t* m_output_buffer; - size_t m_output_size; - - size_t m_chunk_size; - - bool m_is_loading; - std::mutex m_load_mutex; - std::condition_variable m_loading_finished; - std::thread m_load_thread; - - std::vector>& m_processors; - - void Load() + class DbLoadStream { - std::lock_guard lock(m_load_mutex); - - bool firstProcessor = true; - - for (const auto& processor : m_processors) + public: + DbLoadStream(const int streamIndex, const size_t chunkSize, std::vector>& chunkProcessors) + : m_index(streamIndex), + m_input_size(0), + m_output_size(0), + m_chunk_size(chunkSize), + m_is_loading(false), + m_processors(chunkProcessors) { - if (!firstProcessor) - { - uint8_t* previousInputBuffer = m_input_buffer; - m_input_buffer = m_output_buffer; - m_output_buffer = previousInputBuffer; + for (auto& buffer : m_buffers) + buffer = std::make_unique(chunkSize); - m_input_size = m_output_size; - m_output_size = 0; - } - - m_output_size = processor->Process(m_index, m_input_buffer, m_input_size, m_output_buffer, m_chunk_size); - - firstProcessor = false; + m_input_buffer = m_buffers[0].get(); + m_output_buffer = m_buffers[1].get(); } - m_is_loading = false; - m_loading_finished.notify_all(); - } - -public: - DBLoadStream(const int streamIndex, const size_t chunkSize, std::vector>& chunkProcessors) - : m_processors(chunkProcessors) - { - m_index = streamIndex; - m_chunk_size = chunkSize; - - for (auto& buffer : m_buffers) - buffer = std::make_unique(chunkSize); - - m_input_buffer = m_buffers[0].get(); - m_output_buffer = m_buffers[1].get(); - - m_input_size = 0; - m_output_size = 0; - - m_is_loading = false; - } - - [[nodiscard]] uint8_t* GetInputBuffer() const - { - return m_input_buffer; - } - - void StartLoading(const size_t inputSize) - { - if (inputSize > 0) + [[nodiscard]] uint8_t* GetInputBuffer() const { - std::unique_lock lock(m_load_mutex); + return m_input_buffer; + } + void StartLoading(const size_t inputSize) + { + if (inputSize > 0) + { + std::unique_lock lock(m_load_mutex); + + if (m_is_loading) + { + m_loading_finished.wait(lock); + } + + m_input_size = inputSize; + m_is_loading = true; + m_load_thread = std::thread(&DbLoadStream::Load, this); + m_load_thread.detach(); + } + else + { + m_output_size = 0; + } + } + + void GetOutput(const uint8_t** pBuffer, size_t* pSize) + { + assert(pBuffer != nullptr); + assert(pSize != nullptr); + + std::unique_lock lock(m_load_mutex); if (m_is_loading) { m_loading_finished.wait(lock); } - m_input_size = inputSize; - m_is_loading = true; - m_load_thread = std::thread(&DBLoadStream::Load, this); - m_load_thread.detach(); - } - else - { - m_output_size = 0; - } - } - - void GetOutput(const uint8_t** pBuffer, size_t* pSize) - { - assert(pBuffer != nullptr); - assert(pSize != nullptr); - - std::unique_lock lock(m_load_mutex); - if (m_is_loading) - { - m_loading_finished.wait(lock); + *pBuffer = m_output_buffer; + *pSize = m_output_size; } - *pBuffer = m_output_buffer; - *pSize = m_output_size; - } -}; - -class ProcessorXChunks::ProcessorXChunksImpl -{ - ProcessorXChunks* m_base; - - std::vector> m_streams; - size_t m_chunk_size; - size_t m_vanilla_buffer_size; - std::vector> m_chunk_processors; - - bool m_initialized_streams; - unsigned int m_current_stream; - const uint8_t* m_current_chunk; - size_t m_current_chunk_size; - size_t m_current_chunk_offset; - size_t m_vanilla_buffer_offset; - - bool m_eof_reached; - unsigned int m_eof_stream; - - void AdvanceStream(const unsigned streamNum) - { - assert(streamNum < m_streams.size()); - - if (m_eof_reached) - return; - - xchunk_size_t chunkSize; - if (m_vanilla_buffer_size > 0) + private: + void Load() { - if (m_vanilla_buffer_offset + sizeof(chunkSize) > m_vanilla_buffer_size) + std::lock_guard lock(m_load_mutex); + + bool firstProcessor = true; + + for (const auto& processor : m_processors) { - m_base->m_base_stream->Load(&chunkSize, m_vanilla_buffer_size - m_vanilla_buffer_offset); - m_vanilla_buffer_offset = 0; - } - - m_vanilla_buffer_offset = (m_vanilla_buffer_offset + sizeof(chunkSize)) % m_vanilla_buffer_size; - } - - const size_t readSize = m_base->m_base_stream->Load(&chunkSize, sizeof(chunkSize)); - - if (readSize == 0) - { - m_eof_reached = true; - m_eof_stream = streamNum; - return; - } - - if (chunkSize > m_chunk_size) - { - throw InvalidChunkSizeException(chunkSize, m_chunk_size); - } - - const auto& stream = m_streams[streamNum]; - const size_t loadedChunkSize = m_base->m_base_stream->Load(stream->GetInputBuffer(), chunkSize); - - if (loadedChunkSize != chunkSize) - { - throw InvalidChunkSizeException(chunkSize); - } - - if (m_vanilla_buffer_size > 0) - { - m_vanilla_buffer_offset = (m_vanilla_buffer_offset + loadedChunkSize) % m_vanilla_buffer_size; - } - - stream->StartLoading(loadedChunkSize); - } - - void NextStream() - { - AdvanceStream(m_current_stream); - - m_current_stream = (m_current_stream + 1) % m_streams.size(); - m_current_chunk_offset = 0; - m_streams[m_current_stream]->GetOutput(&m_current_chunk, &m_current_chunk_size); - } - - void InitStreams() - { - m_initialized_streams = true; - m_vanilla_buffer_offset = static_cast(m_base->m_base_stream->Pos()); - - const auto streamCount = static_cast(m_streams.size()); - for (auto streamNum = 0u; streamNum < streamCount; streamNum++) - { - AdvanceStream(streamNum); - } - - m_current_stream = 0; - m_current_chunk_offset = 0; - m_streams[0]->GetOutput(&m_current_chunk, &m_current_chunk_size); - } - - [[nodiscard]] bool EndOfStream() const - { - return m_eof_reached && m_eof_stream == m_current_stream; - } - -public: - ProcessorXChunksImpl(ProcessorXChunks* base, const int numStreams, const size_t xChunkSize) - { - assert(base != nullptr); - assert(numStreams > 0); - assert(xChunkSize > 0); - - m_base = base; - - for (int streamIndex = 0; streamIndex < numStreams; streamIndex++) - { - m_streams.emplace_back(std::make_unique(streamIndex, xChunkSize, m_chunk_processors)); - } - - m_chunk_size = xChunkSize; - m_vanilla_buffer_size = 0; - - m_initialized_streams = false; - m_current_stream = 0; - m_current_chunk = nullptr; - m_current_chunk_size = 0; - m_current_chunk_offset = 0; - m_vanilla_buffer_offset = 0; - - m_eof_reached = false; - m_eof_stream = 0; - } - - ProcessorXChunksImpl(ProcessorXChunks* base, const int numStreams, const size_t xChunkSize, const size_t vanillaBufferSize) - : ProcessorXChunksImpl(base, numStreams, xChunkSize) - { - m_vanilla_buffer_size = vanillaBufferSize; - } - - void AddChunkProcessor(std::unique_ptr streamProcessor) - { - assert(streamProcessor != nullptr); - - m_chunk_processors.emplace_back(std::move(streamProcessor)); - } - - size_t Load(void* buffer, const size_t length) - { - assert(buffer != nullptr); - - if (!m_initialized_streams) - { - InitStreams(); - } - - size_t loadedSize = 0; - while (!EndOfStream() && loadedSize < length) - { - auto* bufferPos = static_cast(buffer) + loadedSize; - const size_t sizeToRead = length - loadedSize; - const size_t bytesLeftInCurrentChunk = m_current_chunk_size - m_current_chunk_offset; - - if (sizeToRead > bytesLeftInCurrentChunk) - { - assert(sizeToRead >= bytesLeftInCurrentChunk); - memcpy(bufferPos, &m_current_chunk[m_current_chunk_offset], bytesLeftInCurrentChunk); - loadedSize += bytesLeftInCurrentChunk; - - NextStream(); - } - else - { - memcpy(bufferPos, &m_current_chunk[m_current_chunk_offset], sizeToRead); - loadedSize += sizeToRead; - m_current_chunk_offset += sizeToRead; - - if (m_current_chunk_offset == m_current_chunk_size) + if (!firstProcessor) { + uint8_t* previousInputBuffer = m_input_buffer; + m_input_buffer = m_output_buffer; + m_output_buffer = previousInputBuffer; + + m_input_size = m_output_size; + m_output_size = 0; + } + + m_output_size = processor->Process(m_index, m_input_buffer, m_input_size, m_output_buffer, m_chunk_size); + + firstProcessor = false; + } + + m_is_loading = false; + m_loading_finished.notify_all(); + } + + int m_index; + + std::unique_ptr m_buffers[2]; + + uint8_t* m_input_buffer; + size_t m_input_size; + + uint8_t* m_output_buffer; + size_t m_output_size; + + size_t m_chunk_size; + + bool m_is_loading; + std::mutex m_load_mutex; + std::condition_variable m_loading_finished; + std::thread m_load_thread; + + std::vector>& m_processors; + }; + + class ProcessorXChunks final : public processor::IProcessorXChunks + { + public: + ProcessorXChunks(const int numStreams, const size_t xChunkSize, const std::optional vanillaBufferSize) + : m_chunk_size(xChunkSize), + m_vanilla_buffer_size(vanillaBufferSize), + m_initialized_streams(false), + m_current_stream(0), + m_current_chunk(nullptr), + m_current_chunk_size(0), + m_current_chunk_offset(0), + m_vanilla_buffer_offset(0), + m_eof_reached(false), + m_eof_stream(0) + { + assert(numStreams > 0); + assert(xChunkSize > 0); + + for (int streamIndex = 0; streamIndex < numStreams; streamIndex++) + { + m_streams.emplace_back(std::make_unique(streamIndex, xChunkSize, m_chunk_processors)); + } + } + + size_t Load(void* buffer, const size_t length) override + { + assert(buffer != nullptr); + + if (!m_initialized_streams) + { + InitStreams(); + } + + size_t loadedSize = 0; + while (!EndOfStream() && loadedSize < length) + { + auto* bufferPos = static_cast(buffer) + loadedSize; + const size_t sizeToRead = length - loadedSize; + const size_t bytesLeftInCurrentChunk = m_current_chunk_size - m_current_chunk_offset; + + if (sizeToRead > bytesLeftInCurrentChunk) + { + assert(sizeToRead >= bytesLeftInCurrentChunk); + std::memcpy(bufferPos, &m_current_chunk[m_current_chunk_offset], bytesLeftInCurrentChunk); + loadedSize += bytesLeftInCurrentChunk; + NextStream(); } + else + { + std::memcpy(bufferPos, &m_current_chunk[m_current_chunk_offset], sizeToRead); + loadedSize += sizeToRead; + m_current_chunk_offset += sizeToRead; + + if (m_current_chunk_offset == m_current_chunk_size) + { + NextStream(); + } + } } + + return loadedSize; } - return loadedSize; - } + int64_t Pos() override + { + return m_base_stream->Pos(); + } - int64_t Pos() const + void AddChunkProcessor(std::unique_ptr chunkProcessor) override + { + assert(chunkProcessor); + + m_chunk_processors.emplace_back(std::move(chunkProcessor)); + } + + private: + void AdvanceStream(const unsigned streamNum) + { + assert(streamNum < m_streams.size()); + + if (m_eof_reached) + return; + + xchunk_size_t chunkSize; + if (m_vanilla_buffer_size.has_value()) + { + if (m_vanilla_buffer_offset + sizeof(chunkSize) > *m_vanilla_buffer_size) + { + m_base_stream->Load(&chunkSize, *m_vanilla_buffer_size - m_vanilla_buffer_offset); + m_vanilla_buffer_offset = 0; + } + + m_vanilla_buffer_offset = (m_vanilla_buffer_offset + sizeof(chunkSize)) % *m_vanilla_buffer_size; + } + + const size_t readSize = m_base_stream->Load(&chunkSize, sizeof(chunkSize)); + + if (readSize == 0) + { + m_eof_reached = true; + m_eof_stream = streamNum; + return; + } + + if (chunkSize > m_chunk_size) + { + throw InvalidChunkSizeException(chunkSize, m_chunk_size); + } + + const auto& stream = m_streams[streamNum]; + const size_t loadedChunkSize = m_base_stream->Load(stream->GetInputBuffer(), chunkSize); + + if (loadedChunkSize != chunkSize) + { + throw InvalidChunkSizeException(chunkSize); + } + + if (m_vanilla_buffer_size.has_value()) + { + m_vanilla_buffer_offset = (m_vanilla_buffer_offset + loadedChunkSize) % *m_vanilla_buffer_size; + } + + stream->StartLoading(loadedChunkSize); + } + + void NextStream() + { + AdvanceStream(m_current_stream); + + m_current_stream = (m_current_stream + 1) % m_streams.size(); + m_current_chunk_offset = 0; + m_streams[m_current_stream]->GetOutput(&m_current_chunk, &m_current_chunk_size); + } + + void InitStreams() + { + m_initialized_streams = true; + m_vanilla_buffer_offset = static_cast(m_base_stream->Pos()); + + const auto streamCount = static_cast(m_streams.size()); + for (auto streamNum = 0u; streamNum < streamCount; streamNum++) + { + AdvanceStream(streamNum); + } + + m_current_stream = 0; + m_current_chunk_offset = 0; + m_streams[0]->GetOutput(&m_current_chunk, &m_current_chunk_size); + } + + [[nodiscard]] bool EndOfStream() const + { + return m_eof_reached && m_eof_stream == m_current_stream; + } + + std::vector> m_streams; + size_t m_chunk_size; + std::optional m_vanilla_buffer_size; + std::vector> m_chunk_processors; + + bool m_initialized_streams; + unsigned int m_current_stream; + const uint8_t* m_current_chunk; + size_t m_current_chunk_size; + size_t m_current_chunk_offset; + size_t m_vanilla_buffer_offset; + + bool m_eof_reached; + unsigned int m_eof_stream; + }; +} // namespace + +namespace processor +{ + std::unique_ptr CreateProcessorXChunks(int numStreams, const size_t xChunkSize) { - return m_base->m_base_stream->Pos(); + return std::make_unique(numStreams, xChunkSize, std::nullopt); } -}; -ProcessorXChunks::ProcessorXChunks(const int numStreams, const size_t xChunkSize) -{ - m_impl = new ProcessorXChunksImpl(this, numStreams, xChunkSize); -} - -ProcessorXChunks::ProcessorXChunks(const int numStreams, const size_t xChunkSize, const size_t vanillaBufferSize) -{ - m_impl = new ProcessorXChunksImpl(this, numStreams, xChunkSize, vanillaBufferSize); -} - -ProcessorXChunks::~ProcessorXChunks() -{ - delete m_impl; - m_impl = nullptr; -} - -void ProcessorXChunks::AddChunkProcessor(std::unique_ptr chunkProcessor) const -{ - m_impl->AddChunkProcessor(std::move(chunkProcessor)); -} - -size_t ProcessorXChunks::Load(void* buffer, const size_t length) -{ - return m_impl->Load(buffer, length); -} - -int64_t ProcessorXChunks::Pos() -{ - return m_impl->Pos(); -} + std::unique_ptr CreateProcessorXChunks(int numStreams, const size_t xChunkSize, const size_t vanillaBufferSize) + { + return std::make_unique(numStreams, xChunkSize, vanillaBufferSize); + } +} // namespace processor diff --git a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.h b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.h index 924f799b..dec161af 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.h @@ -4,18 +4,14 @@ #include -class ProcessorXChunks : public StreamProcessor +namespace processor { - class ProcessorXChunksImpl; - ProcessorXChunksImpl* m_impl; + class IProcessorXChunks : public StreamProcessor + { + public: + virtual void AddChunkProcessor(std::unique_ptr chunkProcessor) = 0; + }; -public: - ProcessorXChunks(int numStreams, size_t xChunkSize); - ProcessorXChunks(int numStreams, size_t xChunkSize, size_t vanillaBufferSize); - ~ProcessorXChunks() override; - - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; - - void AddChunkProcessor(std::unique_ptr chunkProcessor) const; -}; + std::unique_ptr CreateProcessorXChunks(int numStreams, size_t xChunkSize); + std::unique_ptr CreateProcessorXChunks(int numStreams, size_t xChunkSize, size_t vanillaBufferSize); +} // namespace processor diff --git a/src/ZoneLoading/Loading/Steps/StepAddProcessor.cpp b/src/ZoneLoading/Loading/Steps/StepAddProcessor.cpp index f86e9c93..42483dcc 100644 --- a/src/ZoneLoading/Loading/Steps/StepAddProcessor.cpp +++ b/src/ZoneLoading/Loading/Steps/StepAddProcessor.cpp @@ -2,16 +2,33 @@ #include -StepAddProcessor::StepAddProcessor(std::unique_ptr streamProcessor) - : m_stream_processor(std::move(streamProcessor)) +namespace { -} + class StepAddProcessor final : public ILoadingStep + { + public: + explicit StepAddProcessor(std::unique_ptr streamProcessor) + : m_stream_processor(std::move(streamProcessor)) + { + } -void StepAddProcessor::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + assert(m_stream_processor != nullptr); + + zoneLoader.AddStreamProcessor(std::move(m_stream_processor)); + m_stream_processor = nullptr; + } + + private: + std::unique_ptr m_stream_processor; + }; +} // namespace + +namespace step { - assert(zoneLoader != nullptr); - assert(m_stream_processor != nullptr); - - zoneLoader->AddStreamProcessor(std::move(m_stream_processor)); - m_stream_processor = nullptr; -} + std::unique_ptr CreateStepAddProcessor(std::unique_ptr streamProcessor) + { + return std::make_unique(std::move(streamProcessor)); + } +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepAddProcessor.h b/src/ZoneLoading/Loading/Steps/StepAddProcessor.h index 661ec0e6..83f8a49f 100644 --- a/src/ZoneLoading/Loading/Steps/StepAddProcessor.h +++ b/src/ZoneLoading/Loading/Steps/StepAddProcessor.h @@ -4,12 +4,7 @@ #include -class StepAddProcessor final : public ILoadingStep +namespace step { - std::unique_ptr m_stream_processor; - -public: - explicit StepAddProcessor(std::unique_ptr streamProcessor); - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; -}; + std::unique_ptr CreateStepAddProcessor(std::unique_ptr streamProcessor); +} diff --git a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp index 352d814b..c4b9d59e 100644 --- a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp +++ b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp @@ -2,28 +2,43 @@ #include "Loading/Exception/InvalidXBlockSizeException.h" -const uint64_t StepAllocXBlocks::MAX_XBLOCK_SIZE = 0x3C000000; - -void StepAllocXBlocks::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) +namespace { - const auto blockCount = static_cast(zoneLoader->m_blocks.size()); + constexpr uint64_t MAX_XBLOCK_SIZE = 0x3C000000; - const auto blockSizes = std::make_unique(blockCount); - stream->Load(blockSizes.get(), sizeof(xblock_size_t) * blockCount); - - uint64_t totalMemory = 0; - for (unsigned int block = 0; block < blockCount; block++) + class StepAllocXBlocks final : public ILoadingStep { - totalMemory += blockSizes[block]; - } + public: + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + const auto blockCount = static_cast(zoneLoader.m_blocks.size()); - if (totalMemory > MAX_XBLOCK_SIZE) - { - throw InvalidXBlockSizeException(totalMemory, MAX_XBLOCK_SIZE); - } + const auto blockSizes = std::make_unique(blockCount); + stream.Load(blockSizes.get(), sizeof(xblock_size_t) * blockCount); - for (unsigned int block = 0; block < blockCount; block++) + uint64_t totalMemory = 0; + for (unsigned int block = 0; block < blockCount; block++) + { + totalMemory += blockSizes[block]; + } + + if (totalMemory > MAX_XBLOCK_SIZE) + { + throw InvalidXBlockSizeException(totalMemory, MAX_XBLOCK_SIZE); + } + + for (unsigned int block = 0; block < blockCount; block++) + { + zoneLoader.m_blocks[block]->Alloc(blockSizes[block]); + } + } + }; +} // namespace + +namespace step +{ + std::unique_ptr CreateStepAllocXBlocks() { - zoneLoader->m_blocks[block]->Alloc(blockSizes[block]); + return std::make_unique(); } -} +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.h b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.h index 99f1cc3a..0b280d2f 100644 --- a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.h +++ b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.h @@ -2,10 +2,9 @@ #include "Loading/ILoadingStep.h" -class StepAllocXBlocks final : public ILoadingStep -{ - static const uint64_t MAX_XBLOCK_SIZE; +#include -public: - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; -}; +namespace step +{ + std::unique_ptr CreateStepAllocXBlocks(); +} diff --git a/src/ZoneLoading/Loading/Steps/StepDumpData.cpp b/src/ZoneLoading/Loading/Steps/StepDumpData.cpp index 3356ba2b..3999dc4d 100644 --- a/src/ZoneLoading/Loading/Steps/StepDumpData.cpp +++ b/src/ZoneLoading/Loading/Steps/StepDumpData.cpp @@ -2,39 +2,57 @@ #include -StepDumpData::StepDumpData(const size_t dumpCount) - : m_dump_count(dumpCount) +namespace { -} - -void StepDumpData::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - uint8_t tempBuffer[128]; - auto dumpedBytes = 0uz; - - std::ofstream tempFile("dump.dat", std::fstream::out | std::fstream::binary); - - while (dumpedBytes < m_dump_count) + class StepDumpData final : public ILoadingStep { - size_t toDump; - - if (m_dump_count - dumpedBytes < sizeof(tempBuffer)) + public: + explicit StepDumpData(const size_t dumpCount) + : m_dump_count(dumpCount) { - toDump = m_dump_count - dumpedBytes; - } - else - { - toDump = sizeof(tempBuffer); } - const auto loadedSize = stream->Load(tempBuffer, toDump); - dumpedBytes += loadedSize; + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + uint8_t tempBuffer[128]; + auto dumpedBytes = 0uz; - if (loadedSize == 0) - break; + std::ofstream tempFile("dump.dat", std::fstream::out | std::fstream::binary); - tempFile.write(reinterpret_cast(tempBuffer), static_cast(loadedSize)); + while (dumpedBytes < m_dump_count) + { + size_t toDump; + + if (m_dump_count - dumpedBytes < sizeof(tempBuffer)) + { + toDump = m_dump_count - dumpedBytes; + } + else + { + toDump = sizeof(tempBuffer); + } + + const auto loadedSize = stream.Load(tempBuffer, toDump); + dumpedBytes += loadedSize; + + if (loadedSize == 0) + break; + + tempFile.write(reinterpret_cast(tempBuffer), static_cast(loadedSize)); + } + + tempFile.close(); + } + + private: + size_t m_dump_count; + }; +} // namespace + +namespace step +{ + std::unique_ptr CreateStepDumpData(size_t dumpCount) + { + return std::make_unique(dumpCount); } - - tempFile.close(); -} +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepDumpData.h b/src/ZoneLoading/Loading/Steps/StepDumpData.h index dc01b570..07beac1a 100644 --- a/src/ZoneLoading/Loading/Steps/StepDumpData.h +++ b/src/ZoneLoading/Loading/Steps/StepDumpData.h @@ -2,13 +2,9 @@ #include "Loading/ILoadingStep.h" -class StepDumpData final : public ILoadingStep +#include + +namespace step { -public: - explicit StepDumpData(size_t dumpCount); - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; - -private: - size_t m_dump_count; -}; + std::unique_ptr CreateStepDumpData(size_t dumpCount); +} diff --git a/src/ZoneLoading/Loading/Steps/StepLoadHash.cpp b/src/ZoneLoading/Loading/Steps/StepLoadHash.cpp index 545ccd84..750f6cac 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadHash.cpp +++ b/src/ZoneLoading/Loading/Steps/StepLoadHash.cpp @@ -4,40 +4,56 @@ #include -StepLoadHash::StepLoadHash(const size_t hashSize, const unsigned hashCount) - : m_hash_size(hashSize), - m_hash_count(hashCount), - m_hashes(std::make_unique(hashSize * hashCount)) +namespace { -} + class StepLoadHash final : public step::IStepLoadHash + { + public: + StepLoadHash(const size_t hashSize, const unsigned hashCount) + : m_hash_size(hashSize), + m_hash_count(hashCount), + m_hashes(std::make_unique(hashSize * hashCount)) + { + } -StepLoadHash::~StepLoadHash() = default; + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + if (stream.Load(m_hashes.get(), m_hash_size * m_hash_count) != m_hash_size * m_hash_count) + throw UnexpectedEndOfFileException(); + } -void StepLoadHash::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) + void GetHash(const unsigned hashIndex, const uint8_t** pHash, size_t* pSize) override + { + assert(pHash != nullptr); + assert(pSize != nullptr); + assert(hashIndex < m_hash_count); + + assert(m_hashes); + + *pHash = &m_hashes[m_hash_size * hashIndex]; + *pSize = m_hash_size; + } + + void GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) override + { + assert(pCapturedData != nullptr); + assert(pSize != nullptr); + + *pCapturedData = m_hashes.get(); + *pSize = m_hash_size * m_hash_count; + } + + private: + size_t m_hash_size; + unsigned m_hash_count; + std::unique_ptr m_hashes; + }; +} // namespace + +namespace step { - assert(stream != nullptr); - - if (stream->Load(m_hashes.get(), m_hash_size * m_hash_count) != m_hash_size * m_hash_count) - throw UnexpectedEndOfFileException(); -} - -void StepLoadHash::GetHash(const unsigned hashIndex, const uint8_t** pHash, size_t* pSize) -{ - assert(pHash != nullptr); - assert(pSize != nullptr); - assert(hashIndex >= 0 && hashIndex < m_hash_count); - - assert(m_hashes); - - *pHash = &m_hashes[m_hash_size * hashIndex]; - *pSize = m_hash_size; -} - -void StepLoadHash::GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) -{ - assert(pCapturedData != nullptr); - assert(pSize != nullptr); - - *pCapturedData = m_hashes.get(); - *pSize = m_hash_size * m_hash_count; -} + std::unique_ptr CreateStepLoadHash(const size_t hashSize, const unsigned hashCount) + { + return std::make_unique(hashSize, hashCount); + } +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepLoadHash.h b/src/ZoneLoading/Loading/Steps/StepLoadHash.h index c7e4cdf8..4bca2b9d 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadHash.h +++ b/src/ZoneLoading/Loading/Steps/StepLoadHash.h @@ -6,22 +6,11 @@ #include -class StepLoadHash final : public ILoadingStep, public IHashProvider, public ICapturedDataProvider +namespace step { - const size_t m_hash_size; - const unsigned m_hash_count; - std::unique_ptr m_hashes; + class IStepLoadHash : public ILoadingStep, public IHashProvider, public ICapturedDataProvider + { + }; -public: - StepLoadHash(size_t hashSize, unsigned hashCount); - ~StepLoadHash() override; - - StepLoadHash(const StepLoadHash& other) = delete; - StepLoadHash(StepLoadHash&& other) noexcept = default; - StepLoadHash& operator=(const StepLoadHash& other) = delete; - StepLoadHash& operator=(StepLoadHash&& other) noexcept = delete; - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; - void GetHash(unsigned hashIndex, const uint8_t** pHash, size_t* pSize) override; - void GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) override; -}; + std::unique_ptr CreateStepLoadHash(size_t hashSize, unsigned hashCount); +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepLoadSignature.cpp b/src/ZoneLoading/Loading/Steps/StepLoadSignature.cpp index 8fbc19e8..789c61ac 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadSignature.cpp +++ b/src/ZoneLoading/Loading/Steps/StepLoadSignature.cpp @@ -4,33 +4,44 @@ #include -StepLoadSignature::StepLoadSignature(const size_t signatureSize) +namespace { - m_signature_size = signatureSize; - m_signature = new uint8_t[signatureSize]; -} + class StepLoadSignature final : public step::IStepLoadSignature + { + public: + explicit StepLoadSignature(const size_t signatureSize) + : m_signature(std::make_unique(signatureSize)), + m_signature_size(signatureSize) + { + } -StepLoadSignature::~StepLoadSignature() + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + if (stream.Load(m_signature.get(), m_signature_size) != m_signature_size) + throw UnexpectedEndOfFileException(); + } + + void GetSignature(const uint8_t** pSignature, size_t* pSize) override + { + assert(pSignature != nullptr); + assert(pSize != nullptr); + + assert(m_signature != nullptr); + + *pSignature = m_signature.get(); + *pSize = m_signature_size; + } + + private: + std::unique_ptr m_signature; + size_t m_signature_size; + }; +} // namespace + +namespace step { - delete[] m_signature; - m_signature = nullptr; -} - -void StepLoadSignature::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - assert(stream != nullptr); - - if (stream->Load(m_signature, m_signature_size) != m_signature_size) - throw UnexpectedEndOfFileException(); -} - -void StepLoadSignature::GetSignature(const uint8_t** pSignature, size_t* pSize) -{ - assert(pSignature != nullptr); - assert(pSize != nullptr); - - assert(m_signature != nullptr); - - *pSignature = m_signature; - *pSize = m_signature_size; -} + std::unique_ptr CreateStepLoadSignature(const size_t signatureSize) + { + return std::make_unique(signatureSize); + } +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepLoadSignature.h b/src/ZoneLoading/Loading/Steps/StepLoadSignature.h index 822653ce..ec0de07e 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadSignature.h +++ b/src/ZoneLoading/Loading/Steps/StepLoadSignature.h @@ -3,15 +3,13 @@ #include "Loading/ILoadingStep.h" #include "Loading/ISignatureProvider.h" -class StepLoadSignature final : public ILoadingStep, public ISignatureProvider +#include + +namespace step { - uint8_t* m_signature; - size_t m_signature_size; + class IStepLoadSignature : public ILoadingStep, public ISignatureProvider + { + }; -public: - explicit StepLoadSignature(size_t signatureSize); - ~StepLoadSignature() override; - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; - void GetSignature(const uint8_t** pSignature, size_t* pSize) override; -}; + std::unique_ptr CreateStepLoadSignature(size_t signatureSize); +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.cpp b/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.cpp index fa4e1c67..5b0ed359 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.cpp +++ b/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.cpp @@ -1,25 +1,38 @@ #include "StepLoadZoneContent.h" -#include "Zone/Stream/Impl/XBlockInputStream.h" +#include "Zone/Stream/ZoneInputStream.h" -#include - -StepLoadZoneContent::StepLoadZoneContent(std::unique_ptr entryPoint, - Zone* zone, - const int offsetBlockBitCount, - const block_t insertBlock) - : m_content_loader(std::move(entryPoint)), - m_zone(zone), - m_offset_block_bit_count(offsetBlockBitCount), - m_insert_block(insertBlock) +namespace { -} + class StepLoadZoneContent final : public ILoadingStep + { + public: + StepLoadZoneContent(std::unique_ptr entryPoint, const int offsetBlockBitCount, const block_t insertBlock) + : m_content_loader(std::move(entryPoint)), + m_offset_block_bit_count(offsetBlockBitCount), + m_insert_block(insertBlock) + { + } -void StepLoadZoneContent::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + const auto inputStream = ZoneInputStream::Create(zoneLoader.m_blocks, stream, m_offset_block_bit_count, m_insert_block); + + m_content_loader->Load(*inputStream); + } + + private: + std::unique_ptr m_content_loader; + int m_offset_block_bit_count; + block_t m_insert_block; + }; +} // namespace + +namespace step { - auto* inputStream = new XBlockInputStream(zoneLoader->m_blocks, stream, m_offset_block_bit_count, m_insert_block); - - m_content_loader->Load(m_zone, inputStream); - - delete inputStream; -} + std::unique_ptr + CreateStepLoadZoneContent(std::unique_ptr entryPoint, const int offsetBlockBitCount, const block_t insertBlock) + { + return std::make_unique(std::move(entryPoint), offsetBlockBitCount, insertBlock); + } +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.h b/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.h index 450c7f16..2e1c2614 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.h +++ b/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.h @@ -5,15 +5,8 @@ #include -class StepLoadZoneContent final : public ILoadingStep +namespace step { - std::unique_ptr m_content_loader; - Zone* m_zone; - int m_offset_block_bit_count; - block_t m_insert_block; - -public: - StepLoadZoneContent(std::unique_ptr entryPoint, Zone* zone, int offsetBlockBitCount, block_t insertBlock); - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; -}; + std::unique_ptr + CreateStepLoadZoneContent(std::unique_ptr entryPoint, int offsetBlockBitCount, block_t insertBlock); +} diff --git a/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.cpp b/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.cpp index b9cd87e6..6cd9abec 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.cpp +++ b/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.cpp @@ -1,23 +1,42 @@ #include "StepLoadZoneSizes.h" -StepLoadZoneSizes::StepLoadZoneSizes() - : m_size(0), - m_external_size(0) +namespace { -} + class StepLoadZoneSizes final : public step::IStepLoadZoneSizes + { + public: + StepLoadZoneSizes() + : m_size(0), + m_external_size(0) + { + } -void StepLoadZoneSizes::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - stream->Load(&m_size, sizeof(m_size)); - stream->Load(&m_external_size, sizeof(m_external_size)); -} + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + stream.Load(&m_size, sizeof(m_size)); + stream.Load(&m_external_size, sizeof(m_external_size)); + } -size_t StepLoadZoneSizes::GetSize() const -{ - return m_size; -} + [[nodiscard]] uint32_t GetSize() const override + { + return m_size; + } -size_t StepLoadZoneSizes::GetExternalSize() const + [[nodiscard]] uint32_t GetExternalSize() const override + { + return m_external_size; + } + + private: + uint32_t m_size; + uint32_t m_external_size; + }; +} // namespace + +namespace step { - return m_external_size; -} + std::unique_ptr CreateStepLoadZoneSizes() + { + return std::make_unique(); + } +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.h b/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.h index 10061adf..5c7eb74a 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.h +++ b/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.h @@ -1,20 +1,17 @@ #pragma once #include "Loading/ILoadingStep.h" -#include "Utils/ClassUtils.h" -#include +#include -class StepLoadZoneSizes final : public ILoadingStep +namespace step { - size_t m_size; - size_t m_external_size; + class IStepLoadZoneSizes : public ILoadingStep + { + public: + [[nodiscard]] virtual uint32_t GetSize() const = 0; + [[nodiscard]] virtual uint32_t GetExternalSize() const = 0; + }; -public: - StepLoadZoneSizes(); - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; - - _NODISCARD size_t GetSize() const; - _NODISCARD size_t GetExternalSize() const; -}; + std::unique_ptr CreateStepLoadZoneSizes(); +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.cpp b/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.cpp index 521f93b5..dee13b8b 100644 --- a/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.cpp +++ b/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.cpp @@ -2,15 +2,32 @@ #include -StepRemoveProcessor::StepRemoveProcessor(StreamProcessor* streamProcessor) - : m_stream_processor(streamProcessor) +namespace { -} + class StepRemoveProcessor final : public ILoadingStep + { + public: + explicit StepRemoveProcessor(const StreamProcessor* streamProcessor) + : m_stream_processor(streamProcessor) + { + } -void StepRemoveProcessor::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + assert(m_stream_processor != nullptr); + + zoneLoader.RemoveStreamProcessor(m_stream_processor); + } + + private: + const StreamProcessor* m_stream_processor; + }; +} // namespace + +namespace step { - assert(zoneLoader != nullptr); - assert(m_stream_processor != nullptr); - - zoneLoader->RemoveStreamProcessor(m_stream_processor); -} + std::unique_ptr CreateStepRemoveProcessor(const StreamProcessor* streamProcessor) + { + return std::make_unique(streamProcessor); + } +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.h b/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.h index 8049bad5..fef6acf3 100644 --- a/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.h +++ b/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.h @@ -1,13 +1,11 @@ #pragma once #include "Loading/ILoadingStep.h" +#include "Loading/StreamProcessor.h" -class StepRemoveProcessor final : public ILoadingStep +#include + +namespace step { - StreamProcessor* m_stream_processor; - -public: - explicit StepRemoveProcessor(StreamProcessor* streamProcessor); - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; -}; + std::unique_ptr CreateStepRemoveProcessor(const StreamProcessor* streamProcessor); +} diff --git a/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp b/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp index 028e49c0..b2874f54 100644 --- a/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp +++ b/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp @@ -1,30 +1,48 @@ #include "StepSkipBytes.h" -StepSkipBytes::StepSkipBytes(const size_t skipCount) - : m_skip_count(skipCount) +namespace { -} - -void StepSkipBytes::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - uint8_t tempBuffer[128]; - auto skippedBytes = 0uz; - - while (skippedBytes < m_skip_count) + class StepSkipBytes final : public ILoadingStep { - size_t toSkip; - - if (m_skip_count - skippedBytes < sizeof(tempBuffer)) + public: + explicit StepSkipBytes(const size_t skipCount) + : m_skip_count(skipCount) { - toSkip = m_skip_count - skippedBytes; - } - else - { - toSkip = sizeof(tempBuffer); } - stream->Load(tempBuffer, toSkip); + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + uint8_t tempBuffer[128]; + auto skippedBytes = 0uz; - skippedBytes += toSkip; + while (skippedBytes < m_skip_count) + { + size_t toSkip; + + if (m_skip_count - skippedBytes < sizeof(tempBuffer)) + { + toSkip = m_skip_count - skippedBytes; + } + else + { + toSkip = sizeof(tempBuffer); + } + + stream.Load(tempBuffer, toSkip); + + skippedBytes += toSkip; + } + } + + private: + size_t m_skip_count; + }; +} // namespace + +namespace step +{ + std::unique_ptr CreateStepSkipBytes(size_t skipCount) + { + return std::make_unique(skipCount); } -} +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepSkipBytes.h b/src/ZoneLoading/Loading/Steps/StepSkipBytes.h index 417eb805..e1800f3f 100644 --- a/src/ZoneLoading/Loading/Steps/StepSkipBytes.h +++ b/src/ZoneLoading/Loading/Steps/StepSkipBytes.h @@ -2,13 +2,9 @@ #include "Loading/ILoadingStep.h" -class StepSkipBytes final : public ILoadingStep +#include + +namespace step { -public: - explicit StepSkipBytes(size_t skipCount); - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; - -private: - size_t m_skip_count; -}; + std::unique_ptr CreateStepSkipBytes(size_t skipCount); +} diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyFileName.cpp b/src/ZoneLoading/Loading/Steps/StepVerifyFileName.cpp index d1ab39c0..98962132 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyFileName.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifyFileName.cpp @@ -4,43 +4,61 @@ #include -StepVerifyFileName::StepVerifyFileName(std::string fileName, const size_t fileNameBufferSize) - : m_expected_file_name(std::move(fileName)), - m_file_name_buffer_size(fileNameBufferSize) +namespace { - if (m_expected_file_name.length() > (m_file_name_buffer_size - 1)) - m_expected_file_name.erase(m_file_name_buffer_size - 1); -} - -void StepVerifyFileName::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - std::stringstream originalFilenameStream; - unsigned bufferOffset = 0; - char c; - - for (; bufferOffset < m_file_name_buffer_size; bufferOffset++) + class StepVerifyFileName final : public ILoadingStep { - - stream->Load(&c, sizeof(char)); - - if (c == '\00') + public: + StepVerifyFileName(std::string fileName, const size_t fileNameBufferSize) + : m_expected_file_name(std::move(fileName)), + m_file_name_buffer_size(fileNameBufferSize) { - bufferOffset++; - break; + if (m_expected_file_name.length() > (m_file_name_buffer_size - 1)) + m_expected_file_name.erase(m_file_name_buffer_size - 1); } - originalFilenameStream << c; - } + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + std::stringstream originalFilenameStream; + unsigned bufferOffset = 0; + char c; - // Skip the rest of the buffer which should be null bytes - while (bufferOffset < m_file_name_buffer_size) + for (; bufferOffset < m_file_name_buffer_size; bufferOffset++) + { + stream.Load(&c, sizeof(char)); + + if (c == '\00') + { + bufferOffset++; + break; + } + + originalFilenameStream << c; + } + + // Skip the rest of the buffer which should be null bytes + while (bufferOffset < m_file_name_buffer_size) + { + stream.Load(&c, sizeof(char)); + bufferOffset++; + } + + const auto originalFileName = originalFilenameStream.str(); + + if (originalFileName != m_expected_file_name) + throw InvalidFileNameException(m_expected_file_name, originalFileName); + } + + private: + std::string m_expected_file_name; + size_t m_file_name_buffer_size; + }; +} // namespace + +namespace step +{ + std::unique_ptr CreateStepVerifyFileName(std::string fileName, const size_t fileNameBufferSize) { - stream->Load(&c, sizeof(char)); - bufferOffset++; + return std::make_unique(std::move(fileName), fileNameBufferSize); } - - std::string originalFileName = originalFilenameStream.str(); - - if (originalFileName != m_expected_file_name) - throw InvalidFileNameException(m_expected_file_name, originalFileName); -} +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyFileName.h b/src/ZoneLoading/Loading/Steps/StepVerifyFileName.h index 542d08e2..23bda199 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyFileName.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifyFileName.h @@ -2,13 +2,10 @@ #include "Loading/ILoadingStep.h" -class StepVerifyFileName final : public ILoadingStep +#include +#include + +namespace step { - std::string m_expected_file_name; - size_t m_file_name_buffer_size; - -public: - explicit StepVerifyFileName(std::string fileName, size_t fileNameBufferSize); - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; -}; + std::unique_ptr CreateStepVerifyFileName(std::string fileName, size_t fileNameBufferSize); +} diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp b/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp index dcbacf8f..41887c8b 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp @@ -5,37 +5,59 @@ #include #include -StepVerifyHash::StepVerifyHash(std::unique_ptr hashFunction, - const unsigned hashIndex, - IHashProvider* hashProvider, - ICapturedDataProvider* dataProvider) - : m_hash_function(std::move(hashFunction)), - m_hash_index(hashIndex), - m_hash_provider(hashProvider), - m_data_provider(dataProvider) +namespace { -} + class StepVerifyHash final : public ILoadingStep + { + public: + StepVerifyHash(std::unique_ptr hashFunction, + const unsigned hashIndex, + IHashProvider* hashProvider, + ICapturedDataProvider* dataProvider) + : m_hash_function(std::move(hashFunction)), + m_hash_index(hashIndex), + m_hash_provider(hashProvider), + m_data_provider(dataProvider) + { + } -StepVerifyHash::~StepVerifyHash() = default; + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + const uint8_t* dataToHash = nullptr; + size_t dataToHashSize = 0; + m_data_provider->GetCapturedData(&dataToHash, &dataToHashSize); -void StepVerifyHash::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) + const uint8_t* hashData = nullptr; + size_t hashSize = 0; + m_hash_provider->GetHash(m_hash_index, &hashData, &hashSize); + + if (hashSize != m_hash_function->GetHashSize()) + throw InvalidHashException(); + + const auto hashMemory = std::make_unique(m_hash_function->GetHashSize()); + m_hash_function->Init(); + m_hash_function->Process(dataToHash, dataToHashSize); + m_hash_function->Finish(hashMemory.get()); + + if (std::memcmp(hashData, hashMemory.get(), m_hash_function->GetHashSize()) != 0) + throw InvalidHashException(); + } + + private: + std::unique_ptr m_hash_function; + unsigned m_hash_index; + IHashProvider* m_hash_provider; + ICapturedDataProvider* m_data_provider; + }; +} // namespace + +namespace step { - const uint8_t* dataToHash = nullptr; - size_t dataToHashSize = 0; - m_data_provider->GetCapturedData(&dataToHash, &dataToHashSize); - - const uint8_t* hashData = nullptr; - size_t hashSize = 0; - m_hash_provider->GetHash(m_hash_index, &hashData, &hashSize); - - if (hashSize != m_hash_function->GetHashSize()) - throw InvalidHashException(); - - const std::unique_ptr hashMemory = std::make_unique(m_hash_function->GetHashSize()); - m_hash_function->Init(); - m_hash_function->Process(dataToHash, dataToHashSize); - m_hash_function->Finish(hashMemory.get()); - - if (std::memcmp(hashData, hashMemory.get(), m_hash_function->GetHashSize()) != 0) - throw InvalidHashException(); -} + std::unique_ptr CreateStepVerifyHash(std::unique_ptr hashFunction, + unsigned hashIndex, + IHashProvider* hashProvider, + ICapturedDataProvider* dataProvider) + { + return std::make_unique(std::move(hashFunction), hashIndex, hashProvider, dataProvider); + } +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyHash.h b/src/ZoneLoading/Loading/Steps/StepVerifyHash.h index b85fb3d7..db54fd28 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyHash.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifyHash.h @@ -7,23 +7,10 @@ #include -class StepVerifyHash final : public ILoadingStep +namespace step { - std::unique_ptr m_hash_function; - unsigned m_hash_index; - IHashProvider* m_hash_provider; - ICapturedDataProvider* m_data_provider; - -public: - StepVerifyHash(std::unique_ptr hashFunction, - unsigned hashIndex, - IHashProvider* hashProvider, - ICapturedDataProvider* dataProvider); - ~StepVerifyHash(); - StepVerifyHash(const StepVerifyHash& other) = delete; - StepVerifyHash(StepVerifyHash&& other) noexcept = default; - StepVerifyHash& operator=(const StepVerifyHash& other) = delete; - StepVerifyHash& operator=(StepVerifyHash&& other) noexcept = default; - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; -}; + std::unique_ptr CreateStepVerifyHash(std::unique_ptr hashFunction, + unsigned hashIndex, + IHashProvider* hashProvider, + ICapturedDataProvider* dataProvider); +} diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyMagic.cpp b/src/ZoneLoading/Loading/Steps/StepVerifyMagic.cpp index 047f4284..4827db28 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyMagic.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifyMagic.cpp @@ -4,21 +4,40 @@ #include -StepVerifyMagic::StepVerifyMagic(const char* magic) +namespace { - m_magic = magic; - m_magic_len = strlen(m_magic); -} - -void StepVerifyMagic::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - char currentCharacter; - - for (unsigned i = 0; i < m_magic_len; i++) + class StepVerifyMagic final : public ILoadingStep { - stream->Load(¤tCharacter, sizeof(char)); + public: + explicit StepVerifyMagic(const char* magic) + : m_magic(magic), + m_magic_len(strlen(m_magic)) + { + } - if (currentCharacter != m_magic[i]) - throw InvalidMagicException(m_magic); + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + char currentCharacter; + + for (unsigned i = 0; i < m_magic_len; i++) + { + stream.Load(¤tCharacter, sizeof(char)); + + if (currentCharacter != m_magic[i]) + throw InvalidMagicException(m_magic); + } + } + + private: + const char* m_magic; + size_t m_magic_len; + }; +} // namespace + +namespace step +{ + std::unique_ptr CreateStepVerifyMagic(const char* magic) + { + return std::make_unique(magic); } -} +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyMagic.h b/src/ZoneLoading/Loading/Steps/StepVerifyMagic.h index 9eed7410..206ab1b9 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyMagic.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifyMagic.h @@ -2,13 +2,9 @@ #include "Loading/ILoadingStep.h" -class StepVerifyMagic final : public ILoadingStep +#include + +namespace step { - const char* m_magic; - size_t m_magic_len; - -public: - explicit StepVerifyMagic(const char* magic); - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; -}; + std::unique_ptr CreateStepVerifyMagic(const char* magic); +} diff --git a/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp b/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp index 00152fd6..6fb7780f 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp @@ -4,31 +4,53 @@ #include -StepVerifySignature::StepVerifySignature(std::unique_ptr signatureAlgorithm, - ISignatureProvider* signatureProvider, - ICapturedDataProvider* signatureDataProvider) - : m_algorithm(std::move(signatureAlgorithm)), - m_signature_provider(signatureProvider), - m_signature_data_provider(signatureDataProvider) +namespace { -} - -void StepVerifySignature::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - assert(m_algorithm != nullptr); - assert(m_signature_provider != nullptr); - assert(m_signature_data_provider != nullptr); - - const uint8_t* signature; - size_t signatureSize; - m_signature_provider->GetSignature(&signature, &signatureSize); - - const uint8_t* signatureData; - size_t signatureDataSize; - m_signature_data_provider->GetCapturedData(&signatureData, &signatureDataSize); - - if (!m_algorithm->Verify(signatureData, signatureDataSize, signature, signatureSize)) + class StepVerifySignature final : public ILoadingStep { - throw InvalidSignatureException(); + public: + StepVerifySignature(std::unique_ptr signatureAlgorithm, + ISignatureProvider* signatureProvider, + ICapturedDataProvider* signatureDataProvider) + : m_algorithm(std::move(signatureAlgorithm)), + m_signature_provider(signatureProvider), + m_signature_data_provider(signatureDataProvider) + { + } + + void PerformStep(ZoneLoader& zoneLoader, ILoadingStream& stream) override + { + assert(m_algorithm != nullptr); + assert(m_signature_provider != nullptr); + assert(m_signature_data_provider != nullptr); + + const uint8_t* signature; + size_t signatureSize; + m_signature_provider->GetSignature(&signature, &signatureSize); + + const uint8_t* signatureData; + size_t signatureDataSize; + m_signature_data_provider->GetCapturedData(&signatureData, &signatureDataSize); + + if (!m_algorithm->Verify(signatureData, signatureDataSize, signature, signatureSize)) + { + throw InvalidSignatureException(); + } + } + + private: + std::unique_ptr m_algorithm; + ISignatureProvider* m_signature_provider; + ICapturedDataProvider* m_signature_data_provider; + }; +} // namespace + +namespace step +{ + std::unique_ptr CreateStepVerifySignature(std::unique_ptr signatureAlgorithm, + ISignatureProvider* signatureProvider, + ICapturedDataProvider* signatureDataProvider) + { + return std::make_unique(std::move(signatureAlgorithm), signatureProvider, signatureDataProvider); } -} +} // namespace step diff --git a/src/ZoneLoading/Loading/Steps/StepVerifySignature.h b/src/ZoneLoading/Loading/Steps/StepVerifySignature.h index 3ce85bfe..7d6f6abc 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifySignature.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifySignature.h @@ -5,21 +5,11 @@ #include "Loading/ISignatureProvider.h" #include "Utils/ICapturedDataProvider.h" -class StepVerifySignature final : public ILoadingStep +#include + +namespace step { - std::unique_ptr m_algorithm; - ISignatureProvider* m_signature_provider; - ICapturedDataProvider* m_signature_data_provider; - -public: - StepVerifySignature(std::unique_ptr signatureAlgorithm, - ISignatureProvider* signatureProvider, - ICapturedDataProvider* signatureDataProvider); - ~StepVerifySignature() override = default; - StepVerifySignature(const StepVerifySignature& other) = delete; - StepVerifySignature(StepVerifySignature&& other) noexcept = default; - StepVerifySignature& operator=(const StepVerifySignature& other) = delete; - StepVerifySignature& operator=(StepVerifySignature&& other) noexcept = default; - - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; -}; + std::unique_ptr CreateStepVerifySignature(std::unique_ptr signatureAlgorithm, + ISignatureProvider* signatureProvider, + ICapturedDataProvider* signatureDataProvider); +} diff --git a/src/ZoneLoading/Loading/ZoneLoader.cpp b/src/ZoneLoading/Loading/ZoneLoader.cpp index e3569b24..a1f7d0c0 100644 --- a/src/ZoneLoading/Loading/ZoneLoader.cpp +++ b/src/ZoneLoading/Loading/ZoneLoader.cpp @@ -4,6 +4,9 @@ #include "LoadingFileStream.h" #include +#include +#include +#include ZoneLoader::ZoneLoader(std::unique_ptr zone) : m_processor_chain_dirty(false), @@ -31,12 +34,12 @@ void ZoneLoader::AddXBlock(std::unique_ptr block) m_blocks.push_back(block.get()); std::ranges::sort(m_blocks, - [](XBlock* b1, XBlock* b2) -> bool + [](const XBlock* b1, const XBlock* b2) -> bool { return b1->m_index < b2->m_index; }); - m_zone->GetMemory()->AddBlock(std::move(block)); + m_zone->Memory().AddBlock(std::move(block)); } void ZoneLoader::AddLoadingStep(std::unique_ptr step) @@ -50,7 +53,7 @@ void ZoneLoader::AddStreamProcessor(std::unique_ptr streamProce m_processor_chain_dirty = true; } -void ZoneLoader::RemoveStreamProcessor(StreamProcessor* streamProcessor) +void ZoneLoader::RemoveStreamProcessor(const StreamProcessor* streamProcessor) { for (auto i = m_processors.begin(); i < m_processors.end(); ++i) { @@ -67,23 +70,24 @@ std::unique_ptr ZoneLoader::LoadZone(std::istream& stream) { LoadingFileStream fileStream(stream); auto* endStream = BuildLoadingChain(&fileStream); + assert(endStream); try { for (const auto& step : m_steps) { - step->PerformStep(this, endStream); + step->PerformStep(*this, *endStream); if (m_processor_chain_dirty) { endStream = BuildLoadingChain(&fileStream); + assert(endStream); } } } catch (LoadingException& e) { - const auto detailedMessage = e.DetailedMessage(); - printf("Loading fastfile failed: %s\n", detailedMessage.c_str()); + std::cerr << std::format("Loading fastfile failed: {}\n", e.DetailedMessage()); return nullptr; } diff --git a/src/ZoneLoading/Loading/ZoneLoader.h b/src/ZoneLoading/Loading/ZoneLoader.h index f0bfe3f1..ddce977e 100644 --- a/src/ZoneLoading/Loading/ZoneLoader.h +++ b/src/ZoneLoading/Loading/ZoneLoader.h @@ -13,25 +13,26 @@ class ILoadingStep; class ZoneLoader { - std::vector> m_steps; - std::vector> m_processors; - - bool m_processor_chain_dirty; - - std::unique_ptr m_zone; - - ILoadingStream* BuildLoadingChain(ILoadingStream* rootStream); - public: - std::vector m_blocks; - explicit ZoneLoader(std::unique_ptr zone); void AddXBlock(std::unique_ptr block); void AddLoadingStep(std::unique_ptr step); void AddStreamProcessor(std::unique_ptr streamProcessor); - void RemoveStreamProcessor(StreamProcessor* streamProcessor); + void RemoveStreamProcessor(const StreamProcessor* streamProcessor); std::unique_ptr LoadZone(std::istream& stream); + + std::vector m_blocks; + +private: + ILoadingStream* BuildLoadingChain(ILoadingStream* rootStream); + + std::vector> m_steps; + std::vector> m_processors; + + bool m_processor_chain_dirty; + + std::unique_ptr m_zone; }; diff --git a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp deleted file mode 100644 index 55d98480..00000000 --- a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp +++ /dev/null @@ -1,248 +0,0 @@ -#include "XBlockInputStream.h" - -#include "Loading/Exception/BlockOverflowException.h" -#include "Loading/Exception/InvalidOffsetBlockException.h" -#include "Loading/Exception/InvalidOffsetBlockOffsetException.h" -#include "Loading/Exception/OutOfBlockBoundsException.h" - -#include -#include - -XBlockInputStream::XBlockInputStream(std::vector& blocks, ILoadingStream* stream, const int blockBitCount, const block_t insertBlock) - : m_blocks(blocks) -{ - m_stream = stream; - - const auto blockCount = static_cast(blocks.size()); - m_block_offsets = std::make_unique(blockCount); - std::memset(m_block_offsets.get(), 0, sizeof(size_t) * blockCount); - - m_block_bit_count = blockBitCount; - - assert(insertBlock < static_cast(blocks.size())); - m_insert_block = blocks[insertBlock]; -} - -void XBlockInputStream::Align(const unsigned align) -{ - assert(!m_block_stack.empty()); - - if (align > 0) - { - const block_t blockIndex = m_block_stack.top()->m_index; - m_block_offsets[blockIndex] = (m_block_offsets[blockIndex] + align - 1u) / align * align; - } -} - -void XBlockInputStream::PushBlock(const block_t block) -{ - assert(block < static_cast(m_blocks.size())); - - XBlock* newBlock = m_blocks[block]; - - assert(newBlock->m_index == block); - - m_block_stack.push(newBlock); - - if (newBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) - { - m_temp_offsets.push(m_block_offsets[newBlock->m_index]); - } -} - -block_t XBlockInputStream::PopBlock() -{ - assert(!m_block_stack.empty()); - - if (m_block_stack.empty()) - return -1; - - const XBlock* poppedBlock = m_block_stack.top(); - - m_block_stack.pop(); - - // If the temp block is not used anymore right now, reset it to the buffer start since as the name suggests, the data inside is temporary. - if (poppedBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) - { - m_block_offsets[poppedBlock->m_index] = m_temp_offsets.top(); - m_temp_offsets.pop(); - } - - return poppedBlock->m_index; -} - -void* XBlockInputStream::Alloc(const unsigned align) -{ - assert(!m_block_stack.empty()); - - if (m_block_stack.empty()) - return nullptr; - - XBlock* block = m_block_stack.top(); - - Align(align); - - if (m_block_offsets[block->m_index] > block->m_buffer_size) - { - throw BlockOverflowException(block); - } - - return &block->m_buffer[m_block_offsets[block->m_index]]; -} - -void XBlockInputStream::LoadDataRaw(void* dst, const size_t size) -{ - m_stream->Load(dst, size); -} - -void XBlockInputStream::LoadDataInBlock(void* dst, const size_t size) -{ - assert(!m_block_stack.empty()); - - if (m_block_stack.empty()) - return; - - XBlock* block = m_block_stack.top(); - - if (block->m_buffer > dst || block->m_buffer + block->m_buffer_size < dst) - { - throw OutOfBlockBoundsException(block); - } - - if (static_cast(dst) + size > block->m_buffer + block->m_buffer_size) - { - throw BlockOverflowException(block); - } - - // Theoretically ptr should always be at the current block offset. - assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); - - switch (block->m_type) - { - case XBlock::Type::BLOCK_TYPE_TEMP: - case XBlock::Type::BLOCK_TYPE_NORMAL: - m_stream->Load(dst, size); - break; - - case XBlock::Type::BLOCK_TYPE_RUNTIME: - memset(dst, 0, size); - break; - - case XBlock::Type::BLOCK_TYPE_DELAY: - assert(false); - break; - } - - IncBlockPos(size); -} - -void XBlockInputStream::IncBlockPos(const size_t size) -{ - assert(!m_block_stack.empty()); - - if (m_block_stack.empty()) - return; - - const XBlock* block = m_block_stack.top(); - m_block_offsets[block->m_index] += size; -} - -void XBlockInputStream::LoadNullTerminated(void* dst) -{ - assert(!m_block_stack.empty()); - - if (m_block_stack.empty()) - return; - - XBlock* block = m_block_stack.top(); - - if (block->m_buffer > dst || block->m_buffer + block->m_buffer_size < dst) - { - throw OutOfBlockBoundsException(block); - } - - // Theoretically ptr should always be at the current block offset. - assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); - - uint8_t byte; - size_t offset = static_cast(dst) - block->m_buffer; - do - { - if (offset >= block->m_buffer_size) - { - throw BlockOverflowException(block); - } - - m_stream->Load(&byte, 1); - block->m_buffer[offset++] = byte; - } while (byte != 0); - - m_block_offsets[block->m_index] = offset; -} - -void** XBlockInputStream::InsertPointer() -{ - m_block_stack.push(m_insert_block); - - Align(alignof(void*)); - - if (m_block_offsets[m_insert_block->m_index] + sizeof(void*) > m_insert_block->m_buffer_size) - { - throw BlockOverflowException(m_insert_block); - } - - auto* ptr = reinterpret_cast(&m_insert_block->m_buffer[m_block_offsets[m_insert_block->m_index]]); - - IncBlockPos(sizeof(void*)); - - m_block_stack.pop(); - - return ptr; -} - -void* XBlockInputStream::ConvertOffsetToPointer(const void* offset) -{ - // -1 because otherwise Block 0 Offset 0 would be just 0 which is already used to signalize a nullptr. - // So all offsets are moved by 1. - const auto offsetInt = reinterpret_cast(offset) - 1u; - - const block_t blockNum = static_cast(offsetInt >> (sizeof(offsetInt) * 8u - m_block_bit_count)); - const size_t blockOffset = offsetInt & (UINTPTR_MAX >> m_block_bit_count); - - if (blockNum < 0 || blockNum >= static_cast(m_blocks.size())) - { - throw InvalidOffsetBlockException(blockNum); - } - - XBlock* block = m_blocks[blockNum]; - - if (block->m_buffer_size <= blockOffset) - { - throw InvalidOffsetBlockOffsetException(block, blockOffset); - } - - return &block->m_buffer[blockOffset]; -} - -void* XBlockInputStream::ConvertOffsetToAlias(const void* offset) -{ - // For details see ConvertOffsetToPointer - const auto offsetInt = reinterpret_cast(offset) - 1; - - const block_t blockNum = static_cast(offsetInt >> (sizeof(offsetInt) * 8 - m_block_bit_count)); - const size_t blockOffset = offsetInt & (UINTPTR_MAX >> m_block_bit_count); - - if (blockNum < 0 || blockNum >= static_cast(m_blocks.size())) - { - throw InvalidOffsetBlockException(blockNum); - } - - XBlock* block = m_blocks[blockNum]; - - if (block->m_buffer_size <= blockOffset + sizeof(void*)) - { - throw InvalidOffsetBlockOffsetException(block, blockOffset); - } - - return *reinterpret_cast(&block->m_buffer[blockOffset]); -} diff --git a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h deleted file mode 100644 index 617880aa..00000000 --- a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include "Loading/ILoadingStream.h" -#include "Zone/Stream/IZoneInputStream.h" -#include "Zone/XBlock.h" - -#include -#include -#include - -class XBlockInputStream final : public IZoneInputStream -{ -public: - XBlockInputStream(std::vector& blocks, ILoadingStream* stream, int blockBitCount, block_t insertBlock); - - void PushBlock(block_t block) override; - block_t PopBlock() override; - - void* Alloc(unsigned align) override; - - void LoadDataRaw(void* dst, size_t size) override; - void LoadDataInBlock(void* dst, size_t size) override; - void IncBlockPos(size_t size) override; - void LoadNullTerminated(void* dst) override; - - void** InsertPointer() override; - - void* ConvertOffsetToPointer(const void* offset) override; - void* ConvertOffsetToAlias(const void* offset) override; - -private: - void Align(unsigned align); - - std::vector& m_blocks; - std::unique_ptr m_block_offsets; - - std::stack m_block_stack; - std::stack m_temp_offsets; - ILoadingStream* m_stream; - - unsigned m_block_bit_count; - XBlock* m_insert_block; -}; diff --git a/src/ZoneLoading/Zone/Stream/ZoneInputStream.cpp b/src/ZoneLoading/Zone/Stream/ZoneInputStream.cpp new file mode 100644 index 00000000..86e3343f --- /dev/null +++ b/src/ZoneLoading/Zone/Stream/ZoneInputStream.cpp @@ -0,0 +1,249 @@ +#include "ZoneInputStream.h" + +#include "Loading/Exception/BlockOverflowException.h" +#include "Loading/Exception/InvalidOffsetBlockException.h" +#include "Loading/Exception/InvalidOffsetBlockOffsetException.h" +#include "Loading/Exception/OutOfBlockBoundsException.h" +#include "Utils/Alignment.h" + +#include +#include +#include + +namespace +{ + class XBlockInputStream final : public ZoneInputStream + { + public: + XBlockInputStream(std::vector& blocks, ILoadingStream& stream, const unsigned blockBitCount, const block_t insertBlock) + : m_blocks(blocks), + m_stream(stream) + { + const auto blockCount = static_cast(blocks.size()); + m_block_offsets = std::make_unique(blockCount); + std::memset(m_block_offsets.get(), 0, sizeof(size_t) * blockCount); + + m_block_bit_count = blockBitCount; + + assert(insertBlock < static_cast(blocks.size())); + m_insert_block = blocks[insertBlock]; + } + + void PushBlock(const block_t block) override + { + assert(block < static_cast(m_blocks.size())); + + auto* newBlock = m_blocks[block]; + assert(newBlock->m_index == block); + + m_block_stack.push(newBlock); + + if (newBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) + m_temp_offsets.push(m_block_offsets[newBlock->m_index]); + } + + block_t PopBlock() override + { + assert(!m_block_stack.empty()); + + if (m_block_stack.empty()) + return -1; + + const auto* poppedBlock = m_block_stack.top(); + + m_block_stack.pop(); + + // If the temp block is not used anymore right now, reset it to the buffer start since as the name suggests, the data inside is temporary. + if (poppedBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) + { + m_block_offsets[poppedBlock->m_index] = m_temp_offsets.top(); + m_temp_offsets.pop(); + } + + return poppedBlock->m_index; + } + + void* Alloc(const unsigned align) override + { + assert(!m_block_stack.empty()); + + if (m_block_stack.empty()) + return nullptr; + + auto* block = m_block_stack.top(); + + Align(align); + + if (m_block_offsets[block->m_index] > block->m_buffer_size) + throw BlockOverflowException(block); + + return &block->m_buffer[m_block_offsets[block->m_index]]; + } + + void LoadDataRaw(void* dst, const size_t size) override + { + m_stream.Load(dst, size); + } + + void LoadDataInBlock(void* dst, const size_t size) override + { + assert(!m_block_stack.empty()); + + if (m_block_stack.empty()) + return; + + auto* block = m_block_stack.top(); + + if (block->m_buffer > dst || block->m_buffer + block->m_buffer_size < dst) + throw OutOfBlockBoundsException(block); + + if (static_cast(dst) + size > block->m_buffer + block->m_buffer_size) + throw BlockOverflowException(block); + + // Theoretically ptr should always be at the current block offset. + assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); + + switch (block->m_type) + { + case XBlock::Type::BLOCK_TYPE_TEMP: + case XBlock::Type::BLOCK_TYPE_NORMAL: + m_stream.Load(dst, size); + break; + + case XBlock::Type::BLOCK_TYPE_RUNTIME: + memset(dst, 0, size); + break; + + case XBlock::Type::BLOCK_TYPE_DELAY: + assert(false); + break; + } + + IncBlockPos(size); + } + + void IncBlockPos(const size_t size) override + { + assert(!m_block_stack.empty()); + + if (m_block_stack.empty()) + return; + + const auto* block = m_block_stack.top(); + m_block_offsets[block->m_index] += size; + } + + void LoadNullTerminated(void* dst) override + { + assert(!m_block_stack.empty()); + + if (m_block_stack.empty()) + return; + + auto* block = m_block_stack.top(); + + if (block->m_buffer > dst || block->m_buffer + block->m_buffer_size < dst) + throw OutOfBlockBoundsException(block); + + // Theoretically ptr should always be at the current block offset. + assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); + + uint8_t byte; + auto offset = static_cast(static_cast(dst) - block->m_buffer); + do + { + if (offset >= block->m_buffer_size) + throw BlockOverflowException(block); + + m_stream.Load(&byte, 1); + block->m_buffer[offset++] = byte; + } while (byte != 0); + + m_block_offsets[block->m_index] = offset; + } + + void** InsertPointer() override + { + m_block_stack.push(m_insert_block); + + Align(alignof(void*)); + + if (m_block_offsets[m_insert_block->m_index] + sizeof(void*) > m_insert_block->m_buffer_size) + throw BlockOverflowException(m_insert_block); + + auto* ptr = reinterpret_cast(&m_insert_block->m_buffer[m_block_offsets[m_insert_block->m_index]]); + + IncBlockPos(sizeof(void*)); + + m_block_stack.pop(); + + return ptr; + } + + void* ConvertOffsetToPointer(const void* offset) override + { + // -1 because otherwise Block 0 Offset 0 would be just 0 which is already used to signalize a nullptr. + // So all offsets are moved by 1. + const auto offsetInt = reinterpret_cast(offset) - 1u; + + const auto blockNum = static_cast(offsetInt >> (sizeof(offsetInt) * 8u - m_block_bit_count)); + const auto blockOffset = static_cast(offsetInt & (UINTPTR_MAX >> m_block_bit_count)); + + if (blockNum < 0 || blockNum >= static_cast(m_blocks.size())) + throw InvalidOffsetBlockException(blockNum); + + auto* block = m_blocks[blockNum]; + + if (block->m_buffer_size <= blockOffset) + throw InvalidOffsetBlockOffsetException(block, blockOffset); + + return &block->m_buffer[blockOffset]; + } + + void* ConvertOffsetToAlias(const void* offset) override + { + // For details see ConvertOffsetToPointer + const auto offsetInt = reinterpret_cast(offset) - 1u; + + const auto blockNum = static_cast(offsetInt >> (sizeof(offsetInt) * 8u - m_block_bit_count)); + const auto blockOffset = static_cast(offsetInt & (UINTPTR_MAX >> m_block_bit_count)); + + if (blockNum < 0 || blockNum >= static_cast(m_blocks.size())) + throw InvalidOffsetBlockException(blockNum); + + auto* block = m_blocks[blockNum]; + + if (block->m_buffer_size <= blockOffset + sizeof(void*)) + throw InvalidOffsetBlockOffsetException(block, blockOffset); + + return *reinterpret_cast(&block->m_buffer[blockOffset]); + } + + private: + void Align(const unsigned align) + { + assert(!m_block_stack.empty()); + + if (align > 0) + { + const auto blockIndex = m_block_stack.top()->m_index; + m_block_offsets[blockIndex] = utils::Align(m_block_offsets[blockIndex], static_cast(align)); + } + } + + std::vector& m_blocks; + std::unique_ptr m_block_offsets; + + std::stack m_block_stack; + std::stack m_temp_offsets; + ILoadingStream& m_stream; + + unsigned m_block_bit_count; + XBlock* m_insert_block; + }; +} // namespace + +std::unique_ptr ZoneInputStream::Create(std::vector& blocks, ILoadingStream& stream, unsigned blockBitCount, block_t insertBlock) +{ + return std::make_unique(blocks, stream, blockBitCount, insertBlock); +} diff --git a/src/ZoneLoading/Zone/Stream/IZoneInputStream.h b/src/ZoneLoading/Zone/Stream/ZoneInputStream.h similarity index 84% rename from src/ZoneLoading/Zone/Stream/IZoneInputStream.h rename to src/ZoneLoading/Zone/Stream/ZoneInputStream.h index c363b759..70acb592 100644 --- a/src/ZoneLoading/Zone/Stream/IZoneInputStream.h +++ b/src/ZoneLoading/Zone/Stream/ZoneInputStream.h @@ -1,11 +1,13 @@ #pragma once +#include "Loading/ILoadingStream.h" #include "Zone/Stream/IZoneStream.h" +#include "Zone/XBlock.h" -#include -#include +#include +#include -class IZoneInputStream : public IZoneStream +class ZoneInputStream : public IZoneStream { public: virtual void* Alloc(unsigned align) = 0; @@ -55,4 +57,6 @@ public: { return static_cast(ConvertOffsetToAlias(static_cast(offset))); } + + static std::unique_ptr Create(std::vector& blocks, ILoadingStream& stream, unsigned blockBitCount, block_t insertBlock); }; diff --git a/test/ObjLoadingTests/Game/IW4/Menu/LoaderMenuListIW4Test.cpp b/test/ObjLoadingTests/Game/IW4/Menu/LoaderMenuListIW4Test.cpp index c9029a9c..69021fe5 100644 --- a/test/ObjLoadingTests/Game/IW4/Menu/LoaderMenuListIW4Test.cpp +++ b/test/ObjLoadingTests/Game/IW4/Menu/LoaderMenuListIW4Test.cpp @@ -36,7 +36,7 @@ namespace test::game::iw4::menu::parsing::it m_ignored_asset_lookup(), m_context(m_zone, &m_creator_collection, &m_ignored_asset_lookup) { - m_asset_creator = CreateMenuListLoader(*m_zone.GetMemory(), m_search_path); + m_asset_creator = CreateMenuListLoader(m_zone.Memory(), m_search_path); } void AddFile(std::string fileName, std::string data) @@ -51,8 +51,8 @@ namespace test::game::iw4::menu::parsing::it Material* AddMaterial(const std::string& name) { - auto* material = m_zone.GetMemory()->Alloc(); - material->info.name = m_zone.GetMemory()->Dup(name.c_str()); + auto* material = m_zone.Memory().Alloc(); + material->info.name = m_zone.Memory().Dup(name.c_str()); m_context.AddAsset(name, material);