diff options
| author | KiritoDv <kiritodev01@gmail.com> | 2026-03-23 21:23:59 -0600 |
|---|---|---|
| committer | KiritoDv <kiritodev01@gmail.com> | 2026-03-23 21:23:59 -0600 |
| commit | 75f64161cb4addcbc6e29732df8d9b519a62c43f (patch) | |
| tree | 92e2b17bd8c41af42bdf24a6eb4b7b08b90254f6 /src | |
| parent | 654b451ddc6cf25db201b2c858948f430784cc5f (diff) | |
Implemented clang-format
Diffstat (limited to 'src')
97 files changed, 3312 insertions, 2686 deletions
diff --git a/src/Companion.cpp b/src/Companion.cpp index 5fa80a6..c61ab8a 100644 --- a/src/Companion.cpp +++ b/src/Companion.cpp @@ -122,12 +122,12 @@ using namespace std::chrono; namespace fs = std::filesystem; static const std::string regular = "[%Y-%m-%d %H:%M:%S.%e] [%l] %v"; -static const std::string line = "[%Y-%m-%d %H:%M:%S.%e] [%l] > %v"; +static const std::string line = "[%Y-%m-%d %H:%M:%S.%e] [%l] > %v"; static std::string ConvertType(std::string type) { int index = type.find(':'); - if(index != std::string::npos) { + if (index != std::string::npos) { type = type.substr(index + 1); } std::transform(type.begin(), type.end(), type.begin(), tolower); @@ -143,7 +143,7 @@ static std::string GetTypeNode(YAML::Node& node) { Companion* Companion::Instance; void Companion::Init(const ExportType type) { - std::atomic<size_t> assetCount{0}; + std::atomic<size_t> assetCount{ 0 }; Init(type, assetCount); } @@ -283,11 +283,11 @@ void Companion::ParseEnums(std::string& header) { continue; } - if(!inEnum) { + if (!inEnum) { continue; } - if(line.find('}') != std::string::npos) { + if (line.find('}') != std::string::npos) { inEnum = false; continue; } @@ -295,7 +295,7 @@ void Companion::ParseEnums(std::string& header) { // Remove any comments and non-alphanumeric characters line = std::regex_replace(line, std::regex(R"((/\*.*?\*/)|(//.*$)|([^a-zA-Z0-9=_\-\.]))"), ""); - if(line.find('=') != std::string::npos) { + if (line.find('=') != std::string::npos) { auto value = line.substr(line.find('=') + 1); auto name = line.substr(0, line.find('=')); enumIndex = static_cast<int32_t>(std::stoll(value, nullptr, 0)); @@ -304,7 +304,6 @@ void Companion::ParseEnums(std::string& header) { enumIndex++; this->gEnums[enumName][enumIndex] = line; } - } } @@ -312,7 +311,7 @@ std::optional<ParseResultData> Companion::ParseNode(YAML::Node& node, std::strin auto type = GetTypeNode(node); spdlog::set_pattern(regular); - if(node["offset"]) { + if (node["offset"]) { auto offset = node["offset"].as<uint32_t>(); SPDLOG_INFO("- [{}] Processing {} at 0x{:X}", type, name, offset); } else { @@ -322,27 +321,27 @@ std::optional<ParseResultData> Companion::ParseNode(YAML::Node& node, std::strin node["vpath"] = name; auto factory = this->GetFactory(type); - if(!factory.has_value()){ - throw std::runtime_error("No factory by the name '"+type+"' found for '"+name+"'"); + if (!factory.has_value()) { + throw std::runtime_error("No factory by the name '" + type + "' found for '" + name + "'"); } auto impl = factory->get(); auto exporter = impl->GetExporter(this->gConfig.exporterType); - if(!exporter.has_value() && !impl->HasModdedDependencies()){ + if (!exporter.has_value() && !impl->HasModdedDependencies()) { SPDLOG_WARN("No exporter found for {}", name); return std::nullopt; } bool executeDef = true; std::optional<std::shared_ptr<IParsedData>> result; - if(this->gConfig.modding && impl->SupportModdedAssets() && Torch::contains(this->gModdedAssetPaths, name)) { + if (this->gConfig.modding && impl->SupportModdedAssets() && Torch::contains(this->gModdedAssetPaths, name)) { auto path = fs::path(this->gConfig.moddingPath) / this->gModdedAssetPaths[name]; - if(!exists(path)) { + if (!exists(path)) { SPDLOG_ERROR("Modded asset {} not found", this->gModdedAssetPaths[name]); } else { std::ifstream input(path, std::ios::binary); - std::vector<uint8_t> data = std::vector<uint8_t>( std::istreambuf_iterator( input ), {}); + std::vector<uint8_t> data = std::vector<uint8_t>(std::istreambuf_iterator(input), {}); input.close(); result = impl->parse_modding(data, node); @@ -350,72 +349,77 @@ std::optional<ParseResultData> Companion::ParseNode(YAML::Node& node, std::strin } } - if(executeDef && this->gConfig.parseMode == ParseMode::Default) { + if (executeDef && this->gConfig.parseMode == ParseMode::Default) { result = impl->parse(this->gRomData, node); } - if(executeDef && this->gConfig.parseMode == ParseMode::Directory) { + if (executeDef && this->gConfig.parseMode == ParseMode::Directory) { auto path = GetSafeNode<std::string>(node, "path"); - std::ifstream input( path, std::ios::binary ); - auto data = std::vector<uint8_t>( std::istreambuf_iterator( input ), {} ); + std::ifstream input(path, std::ios::binary); + auto data = std::vector<uint8_t>(std::istreambuf_iterator(input), {}); result = impl->parse(data, node); input.close(); } - if(!result.has_value()){ + if (!result.has_value()) { SPDLOG_ERROR("Failed to process {}", name); return std::nullopt; } SPDLOG_INFO("Processed {}", name); - return ParseResultData { - name, type, node, result - }; + return ParseResultData{ name, type, node, result }; } void Companion::ParseModdingConfig() { auto path = fs::path(this->gConfig.moddingPath) / "modding.yml"; - if(!fs::exists(path)) { + if (!fs::exists(path)) { throw std::runtime_error("No modding config found, please run in export mode first"); } auto modding = YAML::LoadFile(path.string()); - for(auto assets = modding["assets"].begin(); assets != modding["assets"].end(); ++assets) { + for (auto assets = modding["assets"].begin(); assets != modding["assets"].end(); ++assets) { auto name = assets->first.as<std::string>(); auto asset = assets->second.as<std::string>(); this->gModdedAssetPaths[name] = asset; } } - void Companion::ParseCurrentFileConfig(YAML::Node node, std::atomic<size_t>& assetCount) { if (node["external_files"]) { auto externalFiles = node["external_files"]; if (externalFiles.IsSequence() && externalFiles.size()) { - for(size_t i = 0; i < externalFiles.size(); i++) { + for (size_t i = 0; i < externalFiles.size(); i++) { auto externalFile = externalFiles[i]; if (externalFile.size() == 0) { - this->gCurrentExternalFiles.push_back((this->gSourceDirectory / externalFile.as<std::string>()).string()); + this->gCurrentExternalFiles.push_back( + (this->gSourceDirectory / externalFile.as<std::string>()).string()); } else { SPDLOG_INFO("External File size {}", externalFile.size()); - throw std::runtime_error("Incorrect yaml syntax for external files.\n\nThe yaml expects:\n:config:\n external_files:\n - <external_files>\n\ne.g.:\nexternal_files:\n - actors/actor1.yaml"); + throw std::runtime_error( + "Incorrect yaml syntax for external files.\n\nThe yaml expects:\n:config:\n external_files:\n " + " - <external_files>\n\ne.g.:\nexternal_files:\n - actors/actor1.yaml"); } std::string externalFileName = (this->gSourceDirectory / externalFile.as<std::string>()).string(); - if (StringHelper::StartsWith(std::filesystem::relative(externalFileName, this->gAssetPath).string(), "../")) { - throw std::runtime_error("External File " + externalFileName + " Not In Asset Directory " + this->gAssetPath); + if (StringHelper::StartsWith(std::filesystem::relative(externalFileName, this->gAssetPath).string(), + "../")) { + throw std::runtime_error("External File " + externalFileName + " Not In Asset Directory " + + this->gAssetPath); } else if (std::filesystem::relative(externalFileName, this->gAssetPath).string() == "") { - throw std::runtime_error("External File " + externalFileName + " Not In Asset Directory " + this->gAssetPath); + throw std::runtime_error("External File " + externalFileName + " Not In Asset Directory " + + this->gAssetPath); } if (!Torch::contains(this->gAddrMap, externalFileName)) { - SPDLOG_INFO("Dependency on external file {}. Now processing {}", externalFileName, externalFileName); + SPDLOG_INFO("Dependency on external file {}. Now processing {}", externalFileName, + externalFileName); auto currentFile = this->gCurrentFile; auto currentDirectory = this->gCurrentDirectory; auto currentExternalFiles = this->gCurrentExternalFiles; this->gCurrentFile = externalFileName; - this->gCurrentDirectory = std::filesystem::relative(externalFileName, this->gAssetPath).replace_extension(""); + this->gCurrentDirectory = + std::filesystem::relative(externalFileName, this->gAssetPath).replace_extension(""); YAML::Node root = YAML::LoadFile(externalFileName); @@ -439,10 +443,10 @@ void Companion::ParseCurrentFileConfig(YAML::Node node, std::atomic<size_t>& ass } } - if(node["manual_segments"]) { + if (node["manual_segments"]) { auto manualSegments = node["manual_segments"]; if (manualSegments.IsSequence() && manualSegments.size()) { - for(size_t i = 0; i < manualSegments.size(); i++) { + for (size_t i = 0; i < manualSegments.size(); i++) { auto segment = manualSegments[i]; if (segment.IsSequence() && segment.size() == 2) { const auto id = segment[0].as<uint32_t>(); @@ -450,13 +454,16 @@ void Companion::ParseCurrentFileConfig(YAML::Node node, std::atomic<size_t>& ass this->gManualSegments[id] = replacement; SPDLOG_DEBUG("Manual Segment {} replaced with {}", id, replacement); } else { - throw std::runtime_error("Incorrect yaml syntax for manual segments.\n\nThe yaml expects:\n:config:\n manual_segments:\n - [<addr>, <replacement>]\n\nLike so:\nmanual_segments:\n - [0x05000000, \"textures/other_textures/texture_6447C4\"]"); + throw std::runtime_error( + "Incorrect yaml syntax for manual segments.\n\nThe yaml expects:\n:config:\n " + "manual_segments:\n - [<addr>, <replacement>]\n\nLike so:\nmanual_segments:\n - [0x05000000, " + "\"textures/other_textures/texture_6447C4\"]"); } } } } - if(node["segments"]) { + if (node["segments"]) { auto segments = node["segments"]; // Set global variables for segmented data @@ -465,16 +472,18 @@ void Companion::ParseCurrentFileConfig(YAML::Node node, std::atomic<size_t>& ass gCurrentSegmentNumber = segments[0][0].as<uint32_t>(); gCurrentFileOffset = segments[0][1].as<uint32_t>(); gCurrentCompressionType = Decompressor::GetCompressionType(this->gRomData, gCurrentFileOffset); - if(node["no_compression"]) { + if (node["no_compression"]) { gCurrentCompressionType = CompressionType::None; } } else { - throw std::runtime_error("Incorrect yaml syntax for segments.\n\nThe yaml expects:\n:config:\n segments:\n - [<segment>, <file_offset>]\n\nLike so:\nsegments:\n - [0x06, 0x821D10]"); + throw std::runtime_error( + "Incorrect yaml syntax for segments.\n\nThe yaml expects:\n:config:\n segments:\n - [<segment>, " + "<file_offset>]\n\nLike so:\nsegments:\n - [0x06, 0x821D10]"); } } // Set file offset for later use. - for(size_t i = 0; i < segments.size(); i++) { + for (size_t i = 0; i < segments.size(); i++) { auto segment = segments[i]; if (segment.IsSequence() && segment.size() == 2) { const auto id = segment[0].as<uint32_t>(); @@ -482,41 +491,45 @@ void Companion::ParseCurrentFileConfig(YAML::Node node, std::atomic<size_t>& ass this->gConfig.segment.local[id] = replacement; SPDLOG_DEBUG("Segment {} replaced with 0x{:X}", id, replacement); } else { - throw std::runtime_error("Incorrect yaml syntax for segments.\n\nThe yaml expects:\n:config:\n segments:\n - [<segment>, <file_offset>]\n\nLike so:\nsegments:\n - [0x06, 0x821D10]"); + throw std::runtime_error( + "Incorrect yaml syntax for segments.\n\nThe yaml expects:\n:config:\n segments:\n - [<segment>, " + "<file_offset>]\n\nLike so:\nsegments:\n - [0x06, 0x821D10]"); } } } if (node["virtual"]) { auto virtualAddrMap = node["virtual"]; - gVirtualAddrMap[gCurrentFile] = std::make_tuple<uint32_t, uint32_t>(virtualAddrMap[0].as<uint32_t>(), virtualAddrMap[1].as<uint32_t>()); + gVirtualAddrMap[gCurrentFile] = + std::make_tuple<uint32_t, uint32_t>(virtualAddrMap[0].as<uint32_t>(), virtualAddrMap[1].as<uint32_t>()); } - if(node["header"]) { + if (node["header"]) { auto header = node["header"]; switch (this->gConfig.exporterType) { case ExportType::Header: { - if(header["header"].IsSequence()) { - for(auto line = header["header"].begin(); line != header["header"].end(); ++line) { + if (header["header"].IsSequence()) { + for (auto line = header["header"].begin(); line != header["header"].end(); ++line) { this->gFileHeader += line->as<std::string>() + "\n"; } } break; } case ExportType::Code: { - if(header["code"].IsSequence()) { - for(auto line = header["code"].begin(); line != header["code"].end(); ++line) { + if (header["code"].IsSequence()) { + for (auto line = header["code"].begin(); line != header["code"].end(); ++line) { this->gFileHeader += line->as<std::string>() + "\n"; } } break; } - default: break; + default: + break; } } - if(node["tables"]){ - for(auto table = node["tables"].begin(); table != node["tables"].end(); ++table){ + if (node["tables"]) { + for (auto table = node["tables"].begin(); table != node["tables"].end(); ++table) { auto name = table->first.as<std::string>(); auto range = table->second["range"].as<std::vector<uint32_t>>(); auto start = gCurrentSegmentNumber ? gCurrentSegmentNumber << 24 | range[0] : range[0]; @@ -524,11 +537,11 @@ void Companion::ParseCurrentFileConfig(YAML::Node node, std::atomic<size_t>& ass auto mode = GetSafeNode<std::string>(table->second, "mode", "APPEND"); TableMode tMode = mode == "REFERENCE" ? TableMode::Reference : TableMode::Append; auto index_size = GetSafeNode<int32_t>(table->second, "index_size", -1); - this->gTables.push_back({name, start, end, tMode, index_size}); + this->gTables.push_back({ name, start, end, tMode, index_size }); } } - if(node["vram"]){ + if (node["vram"]) { auto vram = node["vram"]; const auto addr = GetSafeNode<uint32_t>(vram, "addr"); const auto offset = GetSafeNode<uint32_t>(vram, "offset"); @@ -544,7 +557,7 @@ void Companion::ParseCurrentFileConfig(YAML::Node node, std::atomic<size_t>& ass void Companion::ParseHash() { const auto out = this->gDestinationDirectory / "torch.hash.yml"; - if(fs::exists(out)) { + if (fs::exists(out)) { this->gHashNode = YAML::LoadFile(out.string()); } else { this->gHashNode = YAML::Node(); @@ -553,11 +566,16 @@ void Companion::ParseHash() { std::string ExportTypeToString(ExportType type) { switch (type) { - case ExportType::Binary: return "Binary"; - case ExportType::Header: return "Header"; - case ExportType::Code: return "Code"; - case ExportType::Modding: return "Modding"; - case ExportType::XML: return "XML"; + case ExportType::Binary: + return "Binary"; + case ExportType::Header: + return "Header"; + case ExportType::Code: + return "Code"; + case ExportType::Modding: + return "Modding"; + case ExportType::XML: + return "XML"; default: throw std::runtime_error("Invalid ExportType"); } @@ -565,36 +583,36 @@ std::string ExportTypeToString(ExportType type) { bool Companion::NodeHasChanges(const std::string& path) { - if(this->gConfig.modding) { + if (this->gConfig.modding) { return true; } std::ifstream yaml(path); - const std::vector<uint8_t> data = std::vector<uint8_t>(std::istreambuf_iterator( yaml ), {}); + const std::vector<uint8_t> data = std::vector<uint8_t>(std::istreambuf_iterator(yaml), {}); this->gCurrentHash = CalculateHash(data); bool needsInit = true; auto srcRelativePath = RelativePathToSrcDir(path); - if(this->gHashNode[srcRelativePath]) { + if (this->gHashNode[srcRelativePath]) { auto entry = GetSafeNode<YAML::Node>(this->gHashNode, srcRelativePath); const auto hash = GetSafeNode<std::string>(entry, "hash", "no-hash"); auto modes = GetSafeNode<YAML::Node>(entry, "extracted"); auto extracted = GetSafeNode<bool>(modes, ExportTypeToString(this->gConfig.exporterType)); - if(hash == this->gCurrentHash) { + if (hash == this->gCurrentHash) { needsInit = false; - if(extracted) { + if (extracted) { SPDLOG_INFO("Skipping {} as it has not changed", srcRelativePath); return false; } } } - if(needsInit) { + if (needsInit) { this->gHashNode[srcRelativePath] = YAML::Node(); this->gHashNode[srcRelativePath]["hash"] = this->gCurrentHash; this->gHashNode[srcRelativePath]["extracted"] = YAML::Node(); - for(size_t m = 0; m <= static_cast<size_t>(ExportType::Modding); m++) { + for (size_t m = 0; m <= static_cast<size_t>(ExportType::Modding); m++) { this->gHashNode[srcRelativePath]["extracted"][ExportTypeToString(static_cast<ExportType>(m))] = false; } } @@ -602,8 +620,8 @@ bool Companion::NodeHasChanges(const std::string& path) { return true; } -void Companion::LoadYAMLRecursively(const std::string &dirPath, std::vector<YAML::Node> &result, bool skipRoot) { - for (const auto &entry : std::filesystem::directory_iterator(dirPath)) { +void Companion::LoadYAMLRecursively(const std::string& dirPath, std::vector<YAML::Node>& result, bool skipRoot) { + for (const auto& entry : std::filesystem::directory_iterator(dirPath)) { if (entry.is_directory()) { // Skip the root directory if specified if (skipRoot && entry.path() == dirPath) { @@ -626,7 +644,7 @@ void Companion::LoadYAMLRecursively(const std::string &dirPath, std::vector<YAML void Companion::ProcessTables(YAML::Node& rom) { auto dirs = rom["metadata"].as<std::vector<std::string>>(); - for (const auto &dir : dirs) { + for (const auto& dir : dirs) { std::vector<YAML::Node> configNodes; LoadYAMLRecursively(dir, configNodes, true); gCourseMetadata[dir] = configNodes; @@ -635,7 +653,7 @@ void Companion::ProcessTables(YAML::Node& rom) { // Write yaml data to console if (this->IsDebug()) { SPDLOG_INFO("------ Metadata ouptut ------"); - for (auto &node : gCourseMetadata[dirs[0]]) { + for (auto& node : gCourseMetadata[dirs[0]]) { std::cout << node << std::endl; SPDLOG_INFO("------------"); } @@ -644,7 +662,7 @@ void Companion::ProcessTables(YAML::Node& rom) { } void Companion::ProcessFile(YAML::Node root) { - std::atomic<size_t> assetCount {0}; + std::atomic<size_t> assetCount{ 0 }; ProcessFile(root, assetCount); } @@ -657,39 +675,41 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { gCurrentSegmentNumber = segments[0][0].as<uint32_t>(); gCurrentFileOffset = segments[0][1].as<uint32_t>(); gCurrentCompressionType = Decompressor::GetCompressionType(this->gRomData, gCurrentFileOffset); - if(root[":config"]["no_compression"]) { + if (root[":config"]["no_compression"]) { gCurrentCompressionType = CompressionType::None; } } else { - throw std::runtime_error("Incorrect yaml syntax for segments.\n\nThe yaml expects:\n:config:\n segments:\n - [<segment>, <file_offset>]\n\nLike so:\nsegments:\n - [0x06, 0x821D10]"); + throw std::runtime_error( + "Incorrect yaml syntax for segments.\n\nThe yaml expects:\n:config:\n segments:\n - [<segment>, " + "<file_offset>]\n\nLike so:\nsegments:\n - [0x06, 0x821D10]"); } } } - for(auto asset = root.begin(); asset != root.end(); ++asset){ + for (auto asset = root.begin(); asset != root.end(); ++asset) { auto node = asset->second; auto entryName = asset->first.as<std::string>(); auto output = (this->gCurrentDirectory / entryName).string(); std::replace(output.begin(), output.end(), '\\', '/'); - if(node["type"]){ + if (node["type"]) { const auto type = GetTypeNode(node); - if(type == "NAUDIO:V0:SAMPLE"){ + if (type == "NAUDIO:V0:SAMPLE") { AudioManager::Instance->bind_sample(node, output); } } - if(!node["offset"]) { + if (!node["offset"]) { continue; } - if(gCurrentSegmentNumber) { + if (gCurrentSegmentNumber) { if (IS_SEGMENTED(node["offset"].as<uint32_t>()) == false) { node["offset"] = (gCurrentSegmentNumber << 24) | node["offset"].as<uint32_t>(); } } - if(!gCurrentVirtualPath.empty()) { + if (!gCurrentVirtualPath.empty()) { node["path"] = gCurrentVirtualPath; } @@ -711,11 +731,11 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { this->gManualSegments.clear(); GFXDOverride::ClearVtx(); - if(root[":config"]) { + if (root[":config"]) { this->ParseCurrentFileConfig(root[":config"], assetCount); } - if(!process || (!this->NodeHasChanges(this->gCurrentFile) && !this->gNodeForceProcessing)) { + if (!process || (!this->NodeHasChanges(this->gCurrentFile) && !this->gNodeForceProcessing)) { return; } @@ -723,23 +743,23 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { SPDLOG_INFO("------------------------------------------------"); spdlog::set_pattern(line); - for(auto asset = root.begin(); asset != root.end(); ++asset){ + for (auto asset = root.begin(); asset != root.end(); ++asset) { auto entryName = asset->first.as<std::string>(); auto assetNode = asset->second; - if(entryName.find(":config") != std::string::npos) { + if (entryName.find(":config") != std::string::npos) { continue; } - if(gCurrentFileOffset && assetNode["offset"]) { + if (gCurrentFileOffset && assetNode["offset"]) { const auto offset = assetNode["offset"].as<uint32_t>(); if (!IS_SEGMENTED(offset)) { assetNode["offset"] = (gCurrentSegmentNumber << 24) | offset; } } - if(!gCurrentVirtualPath.empty()) { + if (!gCurrentVirtualPath.empty()) { assetNode["path"] = gCurrentVirtualPath; } @@ -747,7 +767,7 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { std::replace(output.begin(), output.end(), '\\', '/'); this->gConfig.segment.temporal.clear(); auto result = this->ParseNode(assetNode, output); - if(result.has_value()) { + if (result.has_value()) { this->gParseResults[this->gCurrentFile].push_back(result.value()); } @@ -756,7 +776,7 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { spdlog::set_pattern(line); } - for(auto& result : this->gParseResults[this->gCurrentFile]){ + for (auto& result : this->gParseResults[this->gCurrentFile]) { std::ostringstream stream; ExportResult endptr = std::nullopt; WriteEntry wEntry; @@ -765,7 +785,7 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { const auto impl = this->GetFactory(result.type)->get(); const auto exporter = impl->GetExporter(this->gConfig.exporterType); - if(!exporter.has_value()) { + if (!exporter.has_value()) { continue; } @@ -777,7 +797,7 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { auto data = stream.str(); this->gCurrentWrapper->AddFile(result.name, std::vector(data.begin(), data.end())); - for(auto& entry : this->gCompanionFiles){ + for (auto& entry : this->gCompanionFiles) { auto output = (this->gCurrentDirectory / entry.first).string(); std::replace(output.begin(), output.end(), '\\', '/'); this->gCurrentWrapper->AddFile(output, entry.second); @@ -793,12 +813,12 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { exporter->get()->Export(stream, data, result.name, result.node, &result.name); auto data = stream.str(); - if(data.empty()) { + if (data.empty()) { break; } std::string dpath = Instance->GetOutputPath() + "/" + result.name; - if(!exists(fs::path(dpath).parent_path())){ + if (!exists(fs::path(dpath).parent_path())) { create_directories(fs::path(dpath).parent_path()); } @@ -808,10 +828,10 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { file.write(data.c_str(), data.size()); file.close(); - for(auto& entry : this->gCompanionFiles){ + for (auto& entry : this->gCompanionFiles) { auto cpath = (Instance->GetOutputPath() / this->gCurrentDirectory / entry.first).string(); std::replace(cpath.begin(), cpath.end(), '\\', '/'); - if(!exists(fs::path(cpath).parent_path())){ + if (!exists(fs::path(cpath).parent_path())) { create_directories(fs::path(cpath).parent_path()); } @@ -830,39 +850,27 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { this->gCompanionFiles.clear(); - if(result.node["offset"]) { + if (result.node["offset"]) { auto alignment = GetSafeNode<uint32_t>(result.node, "alignment", impl->GetAlignment()); - if(!endptr.has_value()) { - wEntry = { - result.name, - result.node["offset"].as<uint32_t>(), - alignment, - stream.str(), - GetNode<std::string>(result.node, "comment"), - std::nullopt - }; + if (!endptr.has_value()) { + wEntry = { result.name, result.node["offset"].as<uint32_t>(), alignment, + stream.str(), GetNode<std::string>(result.node, "comment"), std::nullopt }; } else { switch (endptr->index()) { case 0: wEntry = { - result.name, - result.node["offset"].as<uint32_t>(), - alignment, - stream.str(), - GetNode<std::string>(result.node, "comment"), - std::get<size_t>(endptr.value()) + result.name, result.node["offset"].as<uint32_t>(), alignment, + stream.str(), GetNode<std::string>(result.node, "comment"), std::get<size_t>(endptr.value()) }; break; case 1: { const auto oentry = std::get<OffsetEntry>(endptr.value()); - wEntry = { - result.name, - oentry.start, - alignment, - stream.str(), - GetNode<std::string>(result.node, "comment"), - oentry.end - }; + wEntry = { result.name, + oentry.start, + alignment, + stream.str(), + GetNode<std::string>(result.node, "comment"), + oentry.end }; break; } default: @@ -878,7 +886,7 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { auto fsout = fs::path(this->gConfig.outputPath); - if(this->gConfig.exporterType == ExportType::Modding || this->gConfig.exporterType == ExportType::XML) { + if (this->gConfig.exporterType == ExportType::Modding || this->gConfig.exporterType == ExportType::XML) { fsout /= "modding.yml"; YAML::Node modding; @@ -889,7 +897,7 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { std::ofstream file(fsout.string(), std::ios::binary); file << modding; file.close(); - } else if(this->gConfig.exporterType != ExportType::Binary){ + } else if (this->gConfig.exporterType != ExportType::Binary) { std::string filename = this->gCurrentDirectory.filename().string(); switch (this->gConfig.exporterType) { @@ -901,37 +909,32 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { fsout /= this->gCurrentDirectory / (filename + ".c"); break; } - default: break; + default: + break; } std::ostringstream stream; std::vector<WriteEntry> entries; - if(std::holds_alternative<std::string>(this->gWriteOrder)) { + if (std::holds_alternative<std::string>(this->gWriteOrder)) { auto sort = std::get<std::string>(this->gWriteOrder); for (const auto& [type, raw] : this->gWriteMap[this->gCurrentFile]) { entries.insert(entries.end(), raw.begin(), raw.end()); } - if(sort == "OFFSET") { - std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { - return a.addr < b.addr; - }); - } else if(sort == "ROFFSET") { - std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { - return a.addr > b.addr; - }); - } else if(sort != "LINEAR") { + if (sort == "OFFSET") { + std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { return a.addr < b.addr; }); + } else if (sort == "ROFFSET") { + std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { return a.addr > b.addr; }); + } else if (sort != "LINEAR") { throw std::runtime_error("Invalid write order"); } } else { for (const auto& type : std::get<std::vector<std::string>>(this->gWriteOrder)) { entries = this->gWriteMap[this->gCurrentFile][type]; - std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { - return a.addr > b.addr; - }); + std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { return a.addr > b.addr; }); } } @@ -939,7 +942,7 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { const auto result = entries[i]; const auto hasSize = result.endptr.has_value(); - if(result.comment.has_value()){ + if (result.comment.has_value()) { stream << "// " << result.comment.value() << "\n"; } @@ -953,50 +956,55 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { stream << "// 0x" << std::hex << std::uppercase << ASSET_PTR(result.endptr.value()) << "\n\n"; } - if(hasSize && i < entries.size() - 1 && this->gConfig.exporterType == ExportType::Code && !this->gIndividualIncludes){ + if (hasSize && i < entries.size() - 1 && this->gConfig.exporterType == ExportType::Code && + !this->gIndividualIncludes) { int32_t startptr = ASSET_PTR(result.endptr.value()); int32_t end = ASSET_PTR(entries[i + 1].addr); uint32_t alignment = entries[i + 1].alignment; int32_t gap = end - startptr; - if(gap < 0) { - stream << "// WARNING: Overlap detected between 0x" << std::hex << startptr << " and 0x" << end << " with size 0x" << std::abs(gap) << "\n"; - SPDLOG_WARN("Overlap detected between 0x{:X} and 0x{:X} with size 0x{:X} on file {}", startptr, end, gap, this->gCurrentFile); - } else if(gap < 0x10 && gap >= alignment && end % alignment == 0 && this->gEnablePadGen) { - SPDLOG_WARN("Gap detected between 0x{:X} and 0x{:X} with size 0x{:X} on file {}", startptr, end, gap, this->gCurrentFile); + if (gap < 0) { + stream << "// WARNING: Overlap detected between 0x" << std::hex << startptr << " and 0x" << end + << " with size 0x" << std::abs(gap) << "\n"; + SPDLOG_WARN("Overlap detected between 0x{:X} and 0x{:X} with size 0x{:X} on file {}", startptr, end, + gap, this->gCurrentFile); + } else if (gap < 0x10 && gap >= alignment && end % alignment == 0 && this->gEnablePadGen) { + SPDLOG_WARN("Gap detected between 0x{:X} and 0x{:X} with size 0x{:X} on file {}", startptr, end, + gap, this->gCurrentFile); SPDLOG_WARN("Creating pad of 0x{:X} bytes", gap); const auto padfile = this->gCurrentDirectory.filename().string(); - if(this->IsDebug()){ + if (this->IsDebug()) { stream << "// 0x" << std::hex << std::uppercase << startptr << "\n"; } stream << "char pad_" << padfile << "_" << std::to_string(gCurrentPad++) << "[] = {\n" << tab_t; auto gapSize = gap & ~3; - for(size_t j = 0; j < gapSize; j++){ + for (size_t j = 0; j < gapSize; j++) { stream << "0x00, "; } stream << "\n};\n"; - if(this->IsDebug()){ + if (this->IsDebug()) { stream << "// 0x" << std::hex << std::uppercase << end << "\n\n"; } else { stream << "\n"; } - } else if(gap >= 0x10) { - stream << "// WARNING: Gap detected between 0x" << std::hex << startptr << " and 0x" << end << " with size 0x" << gap << "\n"; + } else if (gap >= 0x10) { + stream << "// WARNING: Gap detected between 0x" << std::hex << startptr << " and 0x" << end + << " with size 0x" << gap << "\n"; } } if (this->gConfig.exporterType == ExportType::Code && this->gIndividualIncludes) { fs::path outinc = fs::path(this->gConfig.outputPath) / this->gCurrentDirectory.parent_path() / - fs::relative(fs::path(result.name + ".inc.c"), this->gCurrentDirectory.parent_path()); + fs::relative(fs::path(result.name + ".inc.c"), this->gCurrentDirectory.parent_path()); - if(!exists(outinc.parent_path())){ + if (!exists(outinc.parent_path())) { create_directories(outinc.parent_path()); } std::ofstream file(outinc, std::ios::binary); - if(!this->gFileHeader.empty()) { + if (!this->gFileHeader.empty()) { file << this->gFileHeader << std::endl; } file << stream.str(); @@ -1011,39 +1019,39 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { if (this->gConfig.exporterType != ExportType::Code || !this->gIndividualIncludes) { std::string buffer = stream.str(); - if(buffer.empty()) { + if (buffer.empty()) { SPDLOG_WARN("No data to write for {}", this->gCurrentFile); return; } std::string output = fsout.string(); std::replace(output.begin(), output.end(), '\\', '/'); - if(!exists(fs::path(output).parent_path())){ + if (!exists(fs::path(output).parent_path())) { create_directories(fs::path(output).parent_path()); } std::ofstream file(output, std::ios::binary); SPDLOG_INFO("Writing {} to {}", this->gCurrentFile, output); - if(this->gConfig.exporterType == ExportType::Header) { + if (this->gConfig.exporterType == ExportType::Header) { fs::path entryPath = this->gCurrentFile; std::string symbol = entryPath.stem().string(); std::transform(symbol.begin(), symbol.end(), symbol.begin(), toupper); - if(this->IsOTRMode()){ + if (this->IsOTRMode()) { file << "#pragma once\n\n"; } else { file << "#ifndef " << symbol << "_H" << std::endl; file << "#define " << symbol << "_H" << std::endl << std::endl; } - if(!this->gFileHeader.empty()) { + if (!this->gFileHeader.empty()) { file << this->gFileHeader << std::endl; } file << buffer; - if(!this->IsOTRMode()){ + if (!this->IsOTRMode()) { file << std::endl << "#endif" << std::endl; } } else { - if(!this->gFileHeader.empty()) { + if (!this->gFileHeader.empty()) { file << this->gFileHeader << std::endl; } file << buffer; @@ -1053,15 +1061,16 @@ void Companion::ProcessFile(YAML::Node root, std::atomic<size_t>& assetCount) { } } - if(this->gConfig.exporterType != ExportType::Binary) { - this->gHashNode[RelativePathToSrcDir(this->gCurrentFile)]["extracted"][ExportTypeToString(this->gConfig.exporterType)] = true; + if (this->gConfig.exporterType != ExportType::Binary) { + this->gHashNode[RelativePathToSrcDir(this->gCurrentFile)]["extracted"] + [ExportTypeToString(this->gConfig.exporterType)] = true; } } void Companion::Process(std::atomic<size_t>& assetCount) { auto configPath = this->gSourceDirectory / "config.yml"; - if(!fs::exists(configPath)) { + if (!fs::exists(configPath)) { SPDLOG_ERROR("No config file found"); return; } @@ -1071,17 +1080,17 @@ void Companion::Process(std::atomic<size_t>& assetCount) { bool isDirectoryMode = config["mode"] && config["mode"].as<std::string>() == "directory"; - if(!isDirectoryMode) { - if(this->gRomPath.has_value()){ - std::ifstream input( this->gRomPath.value(), std::ios::binary ); - this->gRomData = std::vector<uint8_t>( std::istreambuf_iterator( input ), {} ); + if (!isDirectoryMode) { + if (this->gRomPath.has_value()) { + std::ifstream input(this->gRomPath.value(), std::ios::binary); + this->gRomData = std::vector<uint8_t>(std::istreambuf_iterator(input), {}); input.close(); } this->gCartridge = std::make_shared<N64::Cartridge>(this->gRomData); this->gCartridge->Initialize(); - if(!config[this->gCartridge->GetHash()]){ + if (!config[this->gCartridge->GetHash()]) { SPDLOG_ERROR("No config found for {}", this->gCartridge->GetHash()); return; } @@ -1093,9 +1102,9 @@ void Companion::Process(std::atomic<size_t>& assetCount) { auto rom = !isDirectoryMode ? config[this->gCartridge->GetHash()] : config; - if(rom["preprocess"]) { + if (rom["preprocess"]) { auto preprocess = rom["preprocess"]; - for(auto job = preprocess.begin(); job != preprocess.end(); job++) { + for (auto job = preprocess.begin(); job != preprocess.end(); job++) { auto name = job->first.as<std::string>(); auto item = job->second; auto method = GetSafeNode<std::string>(item, "method"); @@ -1117,7 +1126,7 @@ void Companion::Process(std::atomic<size_t>& assetCount) { throw std::runtime_error("Hash mismatch"); } - if(restart){ + if (restart) { rom = config[this->gCartridge->GetHash()]; } } else { @@ -1130,8 +1139,9 @@ void Companion::Process(std::atomic<size_t>& assetCount) { } auto cfg = rom["config"]; - if(!cfg) { - SPDLOG_ERROR("No config found for {}", !isDirectoryMode ? this->gCartridge->GetHash() : GetSafeNode<std::string>(config, "folder")); + if (!cfg) { + SPDLOG_ERROR("No config found for {}", + !isDirectoryMode ? this->gCartridge->GetHash() : GetSafeNode<std::string>(config, "folder")); return; } @@ -1139,7 +1149,7 @@ void Companion::Process(std::atomic<size_t>& assetCount) { ProcessTables(rom); } - if(rom["segments"]) { + if (rom["segments"]) { auto segments = rom["segments"].as<std::vector<uint32_t>>(); for (int i = 0; i < segments.size(); i++) { this->gConfig.segment.global[i + 1] = segments[i]; @@ -1189,21 +1199,21 @@ void Companion::Process(std::atomic<size_t>& assetCount) { } this->gConfig.outputPath = output_path.string(); - if(gbi) { + if (gbi) { auto key = gbi.as<std::string>(); - if(key == "F3D") { + if (key == "F3D") { this->gConfig.gbi.version = GBIVersion::f3d; - } else if(key == "F3DEX") { + } else if (key == "F3DEX") { this->gConfig.gbi.version = GBIVersion::f3dex; - } else if(key == "F3DB") { + } else if (key == "F3DB") { this->gConfig.gbi.version = GBIVersion::f3db; - } else if(key == "F3DEX2") { + } else if (key == "F3DEX2") { this->gConfig.gbi.version = GBIVersion::f3dex2; - } else if(key == "F3DEX2_PM64") { + } else if (key == "F3DEX2_PM64") { this->gConfig.gbi.version = GBIVersion::f3dex2; this->gConfig.gbi.subversion = GBIMinorVersion::PM64; - } else if(key == "F3DEXB") { + } else if (key == "F3DEXB") { this->gConfig.gbi.version = GBIVersion::f3dexb; } else if (key == "F3DEX_MK64") { this->gConfig.gbi.version = GBIVersion::f3dex; @@ -1213,32 +1223,31 @@ void Companion::Process(std::atomic<size_t>& assetCount) { return; } - if(gbi_floats) { + if (gbi_floats) { this->gConfig.gbi.useFloats = gbi_floats.as<bool>(); } } - if(auto sort = cfg["sort"]) { - if(sort.IsSequence()) { + if (auto sort = cfg["sort"]) { + if (sort.IsSequence()) { this->gWriteOrder = sort.as<std::vector<std::string>>(); } else { this->gWriteOrder = sort.as<std::string>(); } } else { - this->gWriteOrder = std::vector<std::string> { - "LIGHTS", "TEXTURE", "VTX", "GFX" - }; + this->gWriteOrder = std::vector<std::string>{ "LIGHTS", "TEXTURE", "VTX", "GFX" }; } - if((this->gConfig.exporterType == ExportType::Code || this->gConfig.exporterType == ExportType::Binary) && this->gConfig.modding) { + if ((this->gConfig.exporterType == ExportType::Code || this->gConfig.exporterType == ExportType::Binary) && + this->gConfig.modding) { this->ParseModdingConfig(); } - if(std::holds_alternative<std::vector<std::string>>(this->gWriteOrder)) { + if (std::holds_alternative<std::vector<std::string>>(this->gWriteOrder)) { for (auto& [key, _] : this->gFactories) { auto entries = std::get<std::vector<std::string>>(this->gWriteOrder); - if(std::find(entries.begin(), entries.end(), key) != entries.end()) { + if (std::find(entries.begin(), entries.end(), key) != entries.end()) { continue; } @@ -1246,7 +1255,7 @@ void Companion::Process(std::atomic<size_t>& assetCount) { } } #ifdef STANDALONE - if(cfg["enums"]) { + if (cfg["enums"]) { auto enums = GetSafeNode<std::vector<std::string>>(cfg, "enums"); for (auto& file : enums) { file = (this->gSourceDirectory / file).string(); @@ -1255,24 +1264,25 @@ void Companion::Process(std::atomic<size_t>& assetCount) { } #endif - if(cfg["logging"]){ + if (cfg["logging"]) { auto level = cfg["logging"].as<std::string>(); - if(level == "TRACE") { + if (level == "TRACE") { spdlog::set_level(spdlog::level::trace); - } else if(level == "DEBUG") { + } else if (level == "DEBUG") { spdlog::set_level(spdlog::level::debug); - } else if(level == "INFO") { + } else if (level == "INFO") { spdlog::set_level(spdlog::level::info); - } else if(level == "WARN") { + } else if (level == "WARN") { spdlog::set_level(spdlog::level::warn); - } else if(level == "ERROR") { + } else if (level == "ERROR") { spdlog::set_level(spdlog::level::err); - } else if(level == "CRITICAL") { + } else if (level == "CRITICAL") { spdlog::set_level(spdlog::level::critical); - } else if(level == "OFF") { + } else if (level == "OFF") { spdlog::set_level(spdlog::level::off); } else { - throw std::runtime_error("Invalid logging level, please use TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL or OFF"); + throw std::runtime_error( + "Invalid logging level, please use TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL or OFF"); } } @@ -1285,7 +1295,7 @@ void Companion::Process(std::atomic<size_t>& assetCount) { SPDLOG_CRITICAL("Starting Torch..."); - if(this->gConfig.parseMode == ParseMode::Default) { + if (this->gConfig.parseMode == ParseMode::Default) { SPDLOG_CRITICAL("Game: {}", this->gCartridge->GetGameTitle()); SPDLOG_CRITICAL("CRC: {}", this->gCartridge->GetCRC()); SPDLOG_CRITICAL("Version: {}", this->gCartridge->GetVersion()); @@ -1320,35 +1330,34 @@ void Companion::Process(std::atomic<size_t>& assetCount) { } this->gCurrentWrapper = wrapper; - for(auto& entry : this->gCompanionFiles) { + for (auto& entry : this->gCompanionFiles) { auto output = entry.first; std::replace(output.begin(), output.end(), '\\', '/'); this->gCurrentWrapper->AddFile(output, entry.second); } - auto vWriter = LUS::BinaryWriter(); vWriter.SetEndianness(Torch::Endianness::Big); vWriter.Write(static_cast<uint8_t>(Torch::Endianness::Big)); - if(this->gConfig.parseMode == ParseMode::Default) { + if (this->gConfig.parseMode == ParseMode::Default) { vWriter.Write(this->gCartridge->GetCRC()); } else { - vWriter.Write((uint32_t) 0); + vWriter.Write((uint32_t)0); } - for (const auto & entry : Torch::getRecursiveEntries(this->gAssetPath)){ - if(entry.is_directory()) { + for (const auto& entry : Torch::getRecursiveEntries(this->gAssetPath)) { + if (entry.is_directory()) { continue; } const auto yamlPath = entry.path().generic_string(); - if(yamlPath.find(".yaml") == std::string::npos && yamlPath.find(".yml") == std::string::npos) { + if (yamlPath.find(".yaml") == std::string::npos && yamlPath.find(".yml") == std::string::npos) { continue; } - if(yamlPath.find("config.yml") != std::string::npos) { + if (yamlPath.find("config.yml") != std::string::npos) { continue; } @@ -1364,7 +1373,7 @@ void Companion::Process(std::atomic<size_t>& assetCount) { } } - if(wrapper != nullptr) { + if (wrapper != nullptr) { // Add additional files specified by the user for (const auto& filePath : this->gAdditionalFiles) { std::ifstream input(this->gSourceDirectory / filePath, std::ios::binary); @@ -1379,7 +1388,7 @@ void Companion::Process(std::atomic<size_t>& assetCount) { } } - if(!this->gVersion.empty()) { + if (!this->gVersion.empty()) { auto data = ParseVersionString(this->gVersion); wrapper->AddFile("portVersion", data); } @@ -1408,7 +1417,8 @@ void Companion::Process(std::atomic<size_t>& assetCount) { Instance = nullptr; } -void Companion::Pack(const std::string& folder, const std::string& output, const ArchiveType otrMode, const std::string& version) { +void Companion::Pack(const std::string& folder, const std::string& output, const ArchiveType otrMode, + const std::string& version) { spdlog::set_level(spdlog::level::debug); spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] %v"); @@ -1420,13 +1430,13 @@ void Companion::Pack(const std::string& folder, const std::string& output, const auto start = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); std::unordered_map<std::string, std::vector<char>> files; - for (const auto & entry : Torch::getRecursiveEntries(folder)){ - if(entry.is_directory()) { + for (const auto& entry : Torch::getRecursiveEntries(folder)) { + if (entry.is_directory()) { continue; } - std::ifstream input( entry.path(), std::ios::binary ); - auto data = std::vector( std::istreambuf_iterator( input ), {} ); + std::ifstream input(entry.path(), std::ios::binary); + auto data = std::vector(std::istreambuf_iterator(input), {}); input.close(); files[entry.path().generic_string()] = data; } @@ -1444,7 +1454,7 @@ void Companion::Pack(const std::string& folder, const std::string& output, const } wrapper->CreateArchive(); - for(auto& [path, data] : files){ + for (auto& [path, data] : files) { std::string normalized = path; std::replace(normalized.begin(), normalized.end(), '\\', '/'); // Remove parent folder @@ -1453,7 +1463,7 @@ void Companion::Pack(const std::string& folder, const std::string& output, const SPDLOG_CRITICAL("> Added {}", normalized); } - if(!version.empty()) { + if (!version.empty()) { SPDLOG_CRITICAL("Adding version file"); auto data = ParseVersionString(version); wrapper->AddFile("portVersion", data); @@ -1469,7 +1479,7 @@ void Companion::Pack(const std::string& folder, const std::string& output, const } std::optional<std::tuple<std::string, YAML::Node>> Companion::RegisterAsset(const std::string& name, YAML::Node& node) { - if(!node["offset"]) { + if (!node["offset"]) { return std::nullopt; } @@ -1479,7 +1489,7 @@ std::optional<std::tuple<std::string, YAML::Node>> Companion::RegisterAsset(cons auto entry = std::make_tuple(output, node); this->gAddrMap[this->gCurrentFile][node["offset"].as<uint32_t>()] = entry; auto dResult = this->ParseNode(node, output); - if(dResult.has_value()) { + if (dResult.has_value()) { this->gParseResults[this->gCurrentFile].push_back(dResult.value()); } spdlog::set_pattern(regular); @@ -1494,17 +1504,17 @@ void Companion::RegisterFactory(const std::string& type, const std::shared_ptr<B SPDLOG_INFO("Registered factory for {}", type); } -std::optional<std::shared_ptr<BaseFactory>> Companion::GetFactory(const std::string &type) { - if(!Torch::contains(this->gFactories, type)){ +std::optional<std::shared_ptr<BaseFactory>> Companion::GetFactory(const std::string& type) { + if (!Torch::contains(this->gFactories, type)) { return std::nullopt; } return this->gFactories[type]; } -std::optional<Table> Companion::SearchTable(uint32_t addr){ - for(auto& table : this->gTables){ - if(addr >= table.start && addr <= table.end){ +std::optional<Table> Companion::SearchTable(uint32_t addr) { + for (auto& table : this->gTables) { + if (addr >= table.start && addr <= table.end) { return table; } } @@ -1513,11 +1523,11 @@ std::optional<Table> Companion::SearchTable(uint32_t addr){ } std::optional<std::string> Companion::GetEnumFromValue(const std::string& key, int32_t id) { - if(!Torch::contains(this->gEnums, key)){ + if (!Torch::contains(this->gEnums, key)) { return std::nullopt; } - if(!Torch::contains(this->gEnums[key], id)){ + if (!Torch::contains(this->gEnums[key], id)) { return std::nullopt; } @@ -1528,15 +1538,15 @@ std::optional<std::uint32_t> Companion::GetFileOffsetFromSegmentedAddr(const uin auto segments = this->gConfig.segment; - if(Torch::contains(segments.temporal, segment)) { + if (Torch::contains(segments.temporal, segment)) { return segments.temporal[segment]; } - if(Torch::contains(segments.local, segment)) { + if (Torch::contains(segments.local, segment)) { return segments.local[segment]; } - if(Torch::contains(segments.global, segment)) { + if (Torch::contains(segments.global, segment)) { return segments.global[segment]; } @@ -1554,16 +1564,16 @@ uint32_t Companion::PatchVirtualAddr(uint32_t addr) { return addr; } -std::optional<std::tuple<std::string, YAML::Node>> Companion::GetNodeByAddr(uint32_t addr){ - if(!Torch::contains(this->gAddrMap, this->gCurrentFile)){ +std::optional<std::tuple<std::string, YAML::Node>> Companion::GetNodeByAddr(uint32_t addr) { + if (!Torch::contains(this->gAddrMap, this->gCurrentFile)) { return std::nullopt; } // HACK: Adjust address to rom address if virtual address addr = PatchVirtualAddr(addr); - if(!Torch::contains(this->gAddrMap[this->gCurrentFile], addr)){ - for (auto &file : this->gCurrentExternalFiles) { + if (!Torch::contains(this->gAddrMap[this->gCurrentFile], addr)) { + for (auto& file : this->gCurrentExternalFiles) { if (!Torch::contains(this->gAddrMap, file)) { SPDLOG_WARN("GetNodeByAddr: External File {} Not Found.", file); continue; @@ -1581,13 +1591,13 @@ std::optional<std::tuple<std::string, YAML::Node>> Companion::GetNodeByAddr(uint } std::optional<std::string> Companion::GetStringByAddr(const uint32_t addr) { - if(Torch::contains(this->gManualSegments, addr)) { + if (Torch::contains(this->gManualSegments, addr)) { return this->gManualSegments[addr]; } auto node = this->GetNodeByAddr(addr); - if(!node.has_value()) { + if (!node.has_value()) { return std::nullopt; } @@ -1597,37 +1607,38 @@ std::optional<std::string> Companion::GetStringByAddr(const uint32_t addr) { std::optional<std::tuple<std::string, YAML::Node>> Companion::GetSafeNodeByAddr(const uint32_t addr, std::string type) { auto node = this->GetNodeByAddr(addr); - if(!node.has_value()) { + if (!node.has_value()) { return std::nullopt; } auto [name, n] = node.value(); auto n_type = GetTypeNode(n); - if(n_type != type) { - throw std::runtime_error("Requested node type does not match with the target node type at " + Torch::to_hex(addr, false) + " Found: " + n_type + " Expected: " + type); + if (n_type != type) { + throw std::runtime_error("Requested node type does not match with the target node type at " + + Torch::to_hex(addr, false) + " Found: " + n_type + " Expected: " + type); } return node; - } std::optional<std::string> Companion::GetSafeStringByAddr(const uint32_t addr, std::string type) { - if(Torch::contains(this->gManualSegments, addr)) { + if (Torch::contains(this->gManualSegments, addr)) { return this->gManualSegments[addr]; } auto node = this->GetNodeByAddr(addr); - if(!node.has_value()) { + if (!node.has_value()) { return std::nullopt; } auto [name, n] = node.value(); auto n_type = GetTypeNode(n); - if(n_type != type) { - throw std::runtime_error("Requested node type does not match with the target node type at " + Torch::to_hex(addr, false) + " Found: " + n_type + " Expected: " + type); + if (n_type != type) { + throw std::runtime_error("Requested node type does not match with the target node type at " + + Torch::to_hex(addr, false) + " Found: " + n_type + " Expected: " + type); } return std::get<0>(node.value()); @@ -1637,7 +1648,7 @@ std::string Companion::GetSymbolFromAddr(uint32_t address, bool validZero) { auto dec = Companion::Instance->GetNodeByAddr(address); std::ostringstream outSymbol; - if(address == 0 && !validZero) { + if (address == 0 && !validZero) { outSymbol << "NULL"; } else if (dec.has_value()) { auto node = std::get<1>(dec.value()); @@ -1659,7 +1670,7 @@ std::optional<ParseResultData> Companion::GetParseDataByAddr(uint32_t addr) { } } - for (auto &file : this->gCurrentExternalFiles) { + for (auto& file : this->gCurrentExternalFiles) { if (!CONTAINS(this->gParseResults, this->gCurrentFile)) { SPDLOG_INFO("GetParseDataByAddr: External File {} Not Found.", file); continue; @@ -1675,7 +1686,6 @@ std::optional<ParseResultData> Companion::GetParseDataByAddr(uint32_t addr) { return std::nullopt; } - std::optional<ParseResultData> Companion::GetParseDataBySymbol(const std::string& symbol) { if (CONTAINS(this->gParseResults, this->gCurrentFile)) { for (auto& result : this->gParseResults[this->gCurrentFile]) { @@ -1687,7 +1697,7 @@ std::optional<ParseResultData> Companion::GetParseDataBySymbol(const std::string } } - for (auto &file : this->gCurrentExternalFiles) { + for (auto& file : this->gCurrentExternalFiles) { if (!CONTAINS(this->gParseResults, this->gCurrentFile)) { SPDLOG_INFO("GetParseDataBySymbol: External File {} Not Found.", file); continue; @@ -1705,27 +1715,26 @@ std::optional<ParseResultData> Companion::GetParseDataBySymbol(const std::string return std::nullopt; } -std::optional<std::vector<std::tuple<std::string, YAML::Node>>> Companion::GetNodesByType(const std::string& type){ +std::optional<std::vector<std::tuple<std::string, YAML::Node>>> Companion::GetNodesByType(const std::string& type) { std::vector<std::tuple<std::string, YAML::Node>> nodes; - if(!Torch::contains(this->gAddrMap, this->gCurrentFile)){ + if (!Torch::contains(this->gAddrMap, this->gCurrentFile)) { return nodes; } - for(auto& [addr, tpl] : this->gAddrMap[this->gCurrentFile]){ + for (auto& [addr, tpl] : this->gAddrMap[this->gCurrentFile]) { auto [name, node] = tpl; const auto n_type = GetTypeNode(node); - if(node["autogen"]){ + if (node["autogen"]) { SPDLOG_DEBUG("Skipping autogenerated asset {}", name); continue; } - if(n_type == type){ + if (n_type == type) { nodes.push_back(tpl); } } return nodes; - } void Companion::SetProcess(bool shouldProcess) { @@ -1773,9 +1782,7 @@ std::string Companion::CalculateHash(const std::vector<uint8_t>& data) { s.getDigest(hash); char buf[41]; - std::snprintf(buf, sizeof(buf), - "%08x%08x%08x%08x%08x", - hash[0], hash[1], hash[2], hash[3], hash[4]); + std::snprintf(buf, sizeof(buf), "%08x%08x%08x%08x%08x", hash[0], hash[1], hash[2], hash[3], hash[4]); return std::string(buf); } @@ -1798,7 +1805,7 @@ std::vector<char> Companion::ParseVersionString(const std::string& version) { } std::optional<YAML::Node> Companion::AddAsset(YAML::Node asset) { - if(!asset["offset"] || !asset["type"]) { + if (!asset["offset"] || !asset["type"]) { return std::nullopt; } asset["offset"] = PatchVirtualAddr(GetSafeNode<uint32_t>(asset, "offset")); @@ -1807,9 +1814,9 @@ std::optional<YAML::Node> Companion::AddAsset(YAML::Node asset) { const auto symbol = GetSafeNode<std::string>(asset, "symbol", ""); const auto decl = this->GetNodeByAddr(offset); - if(decl.has_value()) { + if (decl.has_value()) { auto found = std::get<1>(decl.value()); - if(GetTypeNode(found) != type) { + if (GetTypeNode(found) != type) { SPDLOG_ERROR("Asset clash detected {} vs {} at 0x{:X}", type, GetTypeNode(found), offset); } else { return found; @@ -1819,17 +1826,18 @@ std::optional<YAML::Node> Companion::AddAsset(YAML::Node asset) { auto rom = this->GetRomData(); auto factory = this->GetFactory(type); - if(!factory.has_value()) { + if (!factory.has_value()) { return std::nullopt; } std::string output; std::string typeId = ConvertType(type); - if(!symbol.empty()) { + if (!symbol.empty()) { output = symbol; - } else if(Decompressor::IsSegmented(offset)){ - output = this->NormalizeAsset("seg" + std::to_string(SEGMENT_NUMBER(offset)) +"_" + typeId + "_" + Torch::to_hex(SEGMENT_OFFSET(offset), false)); + } else if (Decompressor::IsSegmented(offset)) { + output = this->NormalizeAsset("seg" + std::to_string(SEGMENT_NUMBER(offset)) + "_" + typeId + "_" + + Torch::to_hex(SEGMENT_OFFSET(offset), false)); } else { output = this->NormalizeAsset(typeId + "_" + Torch::to_hex(offset, false)); } @@ -1841,11 +1849,11 @@ std::optional<YAML::Node> Companion::AddAsset(YAML::Node asset) { auto result = this->RegisterAsset(output, asset); - if(!gCurrentVirtualPath.empty()) { + if (!gCurrentVirtualPath.empty()) { asset["path"] = gCurrentVirtualPath; } - if(result.has_value()){ + if (result.has_value()) { asset["vpath"] = std::get<0>(result.value()); return std::get<1>(result.value()); diff --git a/src/archive/BinaryWrapper.cpp b/src/archive/BinaryWrapper.cpp index 0a4b06d..a401676 100644 --- a/src/archive/BinaryWrapper.cpp +++ b/src/archive/BinaryWrapper.cpp @@ -1,3 +1,4 @@ #include "BinaryWrapper.h" -BinaryWrapper::BinaryWrapper(const std::string& path) : mPath(path) {} +BinaryWrapper::BinaryWrapper(const std::string& path) : mPath(path) { +} diff --git a/src/archive/SWrapper.cpp b/src/archive/SWrapper.cpp index fab0caf..951b21f 100644 --- a/src/archive/SWrapper.cpp +++ b/src/archive/SWrapper.cpp @@ -16,11 +16,12 @@ int32_t SWrapper::CreateArchive() { #ifndef USE_STORMLIB throw std::runtime_error("StormLib is not enabled. Cannot create archive"); #else - if(fs::exists(mPath)) { + if (fs::exists(mPath)) { fs::remove(mPath); } - if(!SFileCreateArchive(mPath.c_str(), MPQ_CREATE_LISTFILE | MPQ_CREATE_ATTRIBUTES | MPQ_CREATE_ARCHIVE_V2, 16 * 1024, &this->hMpq)){ + if (!SFileCreateArchive(mPath.c_str(), MPQ_CREATE_LISTFILE | MPQ_CREATE_ATTRIBUTES | MPQ_CREATE_ARCHIVE_V2, + 16 * 1024, &this->hMpq)) { SPDLOG_ERROR("Failed to create archive {} with error code {}", mPath, GetLastError()); return -1; } @@ -33,10 +34,10 @@ bool SWrapper::AddFile(const std::string& path, std::vector<char> data) { #ifndef USE_STORMLIB throw std::runtime_error("StormLib is not enabled. Cannot create file"); #else - if(Companion::Instance != nullptr && Companion::Instance->IsDebug()){ + if (Companion::Instance != nullptr && Companion::Instance->IsDebug()) { SPDLOG_INFO("Creating debug file: debug/{}", path); std::string dpath = "debug/" + path; - if(!fs::exists(fs::path(dpath).parent_path())){ + if (!fs::exists(fs::path(dpath).parent_path())) { fs::create_directories(fs::path(dpath).parent_path()); } std::ofstream stream(dpath, std::ios::binary); @@ -59,25 +60,27 @@ bool SWrapper::AddFile(const std::string& path, std::vector<char> data) { char* raw = data.data(); size_t size = data.size(); - if(size == 0){ + if (size == 0) { SPDLOG_ERROR("File at path {} is empty", path); return false; } - if(size >> 32){ + if (size >> 32) { throw std::runtime_error("File at path " + path + " is too large with size " + std::to_string(size)); } - if(!SFileCreateFile(this->hMpq, path.c_str(), theTime, size, 0, MPQ_FILE_COMPRESS, &hFile)){ + if (!SFileCreateFile(this->hMpq, path.c_str(), theTime, size, 0, MPQ_FILE_COMPRESS, &hFile)) { return false; } - if(!SFileWriteFile(hFile, (void*) raw, size, MPQ_COMPRESSION_ZLIB)){ - throw std::runtime_error("Failed to write file at path " + path + " with error " + std::to_string(GetLastError())); + if (!SFileWriteFile(hFile, (void*)raw, size, MPQ_COMPRESSION_ZLIB)) { + throw std::runtime_error("Failed to write file at path " + path + " with error " + + std::to_string(GetLastError())); } - if(!SFileCloseFile(hFile)){ - throw std::runtime_error("Failed to close file at path " + path + " with error " + std::to_string(GetLastError())); + if (!SFileCloseFile(hFile)) { + throw std::runtime_error("Failed to close file at path " + path + " with error " + + std::to_string(GetLastError())); } return true; @@ -88,7 +91,7 @@ int32_t SWrapper::Close(void) { #ifndef USE_STORMLIB throw std::runtime_error("StormLib is not enabled. Cannot close archive"); #else - if(this->hMpq == nullptr) { + if (this->hMpq == nullptr) { SPDLOG_ERROR("Archive already closed"); return -1; } diff --git a/src/archive/ZWrapper.cpp b/src/archive/ZWrapper.cpp index 6440b62..330d35e 100644 --- a/src/archive/ZWrapper.cpp +++ b/src/archive/ZWrapper.cpp @@ -23,10 +23,10 @@ bool ZWrapper::AddFile(const std::string& path, std::vector<char> data) { char* fileData = data.data(); size_t fileSize = data.size(); - if(Companion::Instance != nullptr && Companion::Instance->IsDebug()){ + if (Companion::Instance != nullptr && Companion::Instance->IsDebug()) { SPDLOG_INFO("Creating debug file: debug/{}", path); std::string dpath = "debug/" + path; - if(!fs::exists(fs::path(dpath).parent_path())){ + if (!fs::exists(fs::path(dpath).parent_path())) { fs::create_directories(fs::path(dpath).parent_path()); } std::ofstream stream(dpath, std::ios::binary); diff --git a/src/factories/AssetArrayFactory.cpp b/src/factories/AssetArrayFactory.cpp index 9e01139..abef9c0 100644 --- a/src/factories/AssetArrayFactory.cpp +++ b/src/factories/AssetArrayFactory.cpp @@ -8,11 +8,12 @@ #define FORMAT_HEX(ptr) (ptr) -ExportResult AssetArrayHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult AssetArrayHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto data = std::static_pointer_cast<AssetArrayData>(raw); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -21,7 +22,8 @@ ExportResult AssetArrayHeaderExporter::Export(std::ostream &write, std::shared_p return std::nullopt; } -ExportResult AssetArrayCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult AssetArrayCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -50,7 +52,8 @@ ExportResult AssetArrayCodeExporter::Export(std::ostream &write, std::shared_ptr return offset + size; } -ExportResult AssetArrayBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult AssetArrayBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<AssetArrayData>(raw); @@ -95,7 +98,7 @@ std::optional<std::shared_ptr<IParsedData>> AssetArrayFactory::parse(std::vector YAML::Node assetNode; assetNode["type"] = factoryType; assetNode["offset"] = ptr; - if(additional_info) { + if (additional_info) { for (const auto& it : additional_info) { assetNode[it.first.as<std::string>()] = it.second; } diff --git a/src/factories/BaseFactory.cpp b/src/factories/BaseFactory.cpp index b5050ea..62f46a9 100644 --- a/src/factories/BaseFactory.cpp +++ b/src/factories/BaseFactory.cpp @@ -1,16 +1,16 @@ #include "BaseFactory.h" -void BaseExporter::WriteHeader(LUS::BinaryWriter &writer, Torch::ResourceType resType, int32_t version) { +void BaseExporter::WriteHeader(LUS::BinaryWriter& writer, Torch::ResourceType resType, int32_t version) { writer.Write((int8_t)(Torch::Endianness::Native)); // 0x00 - Endianness - writer.Write((int8_t)0); // 0x01 - Is Asset Custom - writer.Write((int8_t)0); // 0x02 - - writer.Write((int8_t)0); // 0x03 - writer.Write((uint32_t) resType); // 0x04 - writer.Write((uint32_t) version); // 0x08 - writer.Write((uint64_t) 0xDEADBEEFDEADBEEF); // id, 0x0C - writer.Write((uint32_t) 0); // 0x10 - writer.Write((uint64_t) 0); // ROM CRC, 0x14 - writer.Write((uint32_t) 0); // ROM Enum, 0x1C + writer.Write((int8_t)0); // 0x01 - Is Asset Custom + writer.Write((int8_t)0); // 0x02 - + writer.Write((int8_t)0); // 0x03 + writer.Write((uint32_t)resType); // 0x04 + writer.Write((uint32_t)version); // 0x08 + writer.Write((uint64_t)0xDEADBEEFDEADBEEF); // id, 0x0C + writer.Write((uint32_t)0); // 0x10 + writer.Write((uint64_t)0); // ROM CRC, 0x14 + writer.Write((uint32_t)0); // ROM Enum, 0x1C while (writer.GetBaseAddress() < 0x40) writer.Write((uint32_t)0); // To be used at a later date! diff --git a/src/factories/BlobFactory.cpp b/src/factories/BlobFactory.cpp index 8f6830b..7e69cf0 100644 --- a/src/factories/BlobFactory.cpp +++ b/src/factories/BlobFactory.cpp @@ -3,10 +3,11 @@ #include "utils/Decompressor.h" #include <iomanip> -ExportResult BlobHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult BlobHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -16,12 +17,13 @@ ExportResult BlobHeaderExporter::Export(std::ostream &write, std::shared_ptr<IPa return std::nullopt; } -ExportResult BlobCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult BlobCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -33,7 +35,7 @@ ExportResult BlobCodeExporter::Export(std::ostream &write, std::shared_ptr<IPars write << "\n" << tab_t; } - write << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int) data[i] << ", "; + write << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)data[i] << ", "; } write << "\n};\n"; @@ -44,13 +46,14 @@ ExportResult BlobCodeExporter::Export(std::ostream &write, std::shared_ptr<IPars return offset + data.size(); } -ExportResult BlobBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult BlobBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; WriteHeader(writer, Torch::ResourceType::Blob, 0); - writer.Write((uint32_t) data.size()); - writer.Write((char*) data.data(), data.size()); + writer.Write((uint32_t)data.size()); + writer.Write((char*)data.data(), data.size()); writer.Finish(write); return std::nullopt; } diff --git a/src/factories/CompressedTextureFactory.cpp b/src/factories/CompressedTextureFactory.cpp index 685bc53..fdc7b7b 100644 --- a/src/factories/CompressedTextureFactory.cpp +++ b/src/factories/CompressedTextureFactory.cpp @@ -17,50 +17,52 @@ extern "C" { static bool isTable = false; static std::vector<std::string> tableEntries; -static const std::unordered_map <std::string, TextureFormat> sTextureFormats = { +static const std::unordered_map<std::string, TextureFormat> sTextureFormats = { { "RGBA16", { TextureType::RGBA16bpp, 16 } }, { "RGBA32", { TextureType::RGBA32bpp, 32 } }, - { "CI4", { TextureType::Palette4bpp, 4 } }, - { "CI8", { TextureType::Palette8bpp, 8 } }, - { "I4", { TextureType::Grayscale4bpp, 4 } }, - { "I8", { TextureType::Grayscale8bpp, 8 } }, - { "IA1", { TextureType::GrayscaleAlpha1bpp, 1 } }, - { "IA4", { TextureType::GrayscaleAlpha4bpp, 4 } }, - { "IA8", { TextureType::GrayscaleAlpha8bpp, 8 } }, - { "IA16", { TextureType::GrayscaleAlpha16bpp, 16 } }, - { "TLUT", { TextureType::TLUT, 16 } }, + { "CI4", { TextureType::Palette4bpp, 4 } }, + { "CI8", { TextureType::Palette8bpp, 8 } }, + { "I4", { TextureType::Grayscale4bpp, 4 } }, + { "I8", { TextureType::Grayscale8bpp, 8 } }, + { "IA1", { TextureType::GrayscaleAlpha1bpp, 1 } }, + { "IA4", { TextureType::GrayscaleAlpha4bpp, 4 } }, + { "IA8", { TextureType::GrayscaleAlpha8bpp, 8 } }, + { "IA16", { TextureType::GrayscaleAlpha16bpp, 16 } }, + { "TLUT", { TextureType::TLUT, 16 } }, }; -static const std::unordered_map <std::string, CompressionType> sCompressionTypes = { +static const std::unordered_map<std::string, CompressionType> sCompressionTypes = { { "MIO0", CompressionType::MIO0 }, { "YAY0", CompressionType::YAY0 }, { "YAY1", CompressionType::YAY1 }, { "YAZ0", CompressionType::YAZ0 }, }; -ExportResult CompressedTextureHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult CompressedTextureHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto format = GetSafeNode<std::string>(node, "format"); auto texture = std::static_pointer_cast<CompressedTextureData>(raw); auto data = texture->mBuffer; auto isOTR = Companion::Instance->IsOTRMode(); - size_t byteSize = std::max(1, (int) (texture->mFormat.depth / 8)); + size_t byteSize = std::max(1, (int)(texture->mFormat.depth / 8)); const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); unsigned int isize = index_size > -1 ? index_size : data.size() / byteSize; - if(isOTR){ + if (isOTR) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; tableEntries.push_back(symbol); - if(end == offset){ + if (end == offset) { write << "static const char* " << name << "[] = {\n"; - for(auto& entry : tableEntries){ + for (auto& entry : tableEntries) { write << tab_t << entry << ",\n"; } write << "};\n\n"; @@ -70,7 +72,7 @@ ExportResult CompressedTextureHeaderExporter::Export(std::ostream &write, std::s write << "extern " << "u8 " << name << "[][" << isize << "];\n"; } } else { - if(isOTR){ + if (isOTR) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; if (Companion::Instance->AddTextureDefines()) { write << "#define _" << symbol << "_WIDTH 0x" << std::hex << texture->mWidth << std::dec << "\n"; @@ -86,17 +88,17 @@ ExportResult CompressedTextureHeaderExporter::Export(std::ostream &write, std::s switch (texture->mCompressionType) { case CompressionType::MIO0: - worstSize = MIO0_HEADER_LENGTH + ((data.size()+7)/8) + data.size(); + worstSize = MIO0_HEADER_LENGTH + ((data.size() + 7) / 8) + data.size(); compressedData = static_cast<uint8_t*>(std::calloc(worstSize, sizeof(uint8_t))); compressedSize = mio0_encode(data.data(), data.size(), compressedData); break; case CompressionType::YAY0: - worstSize = YAY0_HEADER_LENGTH + ((data.size()+7)/8) + data.size(); + worstSize = YAY0_HEADER_LENGTH + ((data.size() + 7) / 8) + data.size(); compressedData = static_cast<uint8_t*>(std::calloc(worstSize, sizeof(uint8_t))); compressedSize = yay0_encode(data.data(), data.size(), compressedData); break; case CompressionType::YAY1: - worstSize = YAY1_HEADER_LENGTH + ((data.size()+7)/8) + data.size(); + worstSize = YAY1_HEADER_LENGTH + ((data.size() + 7) / 8) + data.size(); compressedData = static_cast<uint8_t*>(std::calloc(worstSize, sizeof(uint8_t))); compressedSize = yay1_encode(data.data(), data.size(), compressedData); break; @@ -105,7 +107,8 @@ ExportResult CompressedTextureHeaderExporter::Export(std::ostream &write, std::s throw std::runtime_error("Unsupported Compressed Texture Type"); break; } - write << "#define _" << symbol << "_COMPRESSED_SIZE 0x" << std::hex << compressedSize << std::dec << "\n"; + write << "#define _" << symbol << "_COMPRESSED_SIZE 0x" << std::hex << compressedSize << std::dec + << "\n"; write << "#define _" << symbol << "_WIDTH 0x" << std::hex << texture->mWidth << std::dec << "\n"; write << "#define _" << symbol << "_HEIGHT 0x" << std::hex << texture->mHeight << std::dec << "\n"; } @@ -115,7 +118,8 @@ ExportResult CompressedTextureHeaderExporter::Export(std::ostream &write, std::s return std::nullopt; } -ExportResult CompressedTextureCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult CompressedTextureCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto texture = std::static_pointer_cast<CompressedTextureData>(raw); auto data = texture->mBuffer; auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -126,16 +130,16 @@ ExportResult CompressedTextureCodeExporter::Export(std::ostream &write, std::sha (*replacement) += "." + format; std::string dpath = Companion::Instance->GetOutputPath() + "/" + (*replacement); - if(!exists(fs::path(dpath).parent_path())){ + if (!exists(fs::path(dpath).parent_path())) { create_directories(fs::path(dpath).parent_path()); } std::ostringstream imgstream; - size_t byteSize = std::max(1, (int) (texture->mFormat.depth / 8)); + size_t byteSize = std::max(1, (int)(texture->mFormat.depth / 8)); size_t isize = texture->mBuffer.size() / byteSize; - for (int i = 0; i < data.size(); i+=byteSize) { + for (int i = 0; i < data.size(); i += byteSize) { if (i % 16 == 0 && i != 0) { imgstream << std::endl; } @@ -161,17 +165,17 @@ ExportResult CompressedTextureCodeExporter::Export(std::ostream &write, std::sha switch (texture->mCompressionType) { case CompressionType::MIO0: - worstSize = MIO0_HEADER_LENGTH + ((data.size()+7)/8) + data.size(); + worstSize = MIO0_HEADER_LENGTH + ((data.size() + 7) / 8) + data.size(); compressedData = static_cast<uint8_t*>(std::calloc(worstSize, sizeof(uint8_t))); compressedSize = mio0_encode(data.data(), data.size(), compressedData); break; case CompressionType::YAY0: - worstSize = YAY0_HEADER_LENGTH + ((data.size()+7)/8) + data.size(); + worstSize = YAY0_HEADER_LENGTH + ((data.size() + 7) / 8) + data.size(); compressedData = static_cast<uint8_t*>(std::calloc(worstSize, sizeof(uint8_t))); compressedSize = yay0_encode(data.data(), data.size(), compressedData); break; case CompressionType::YAY1: - worstSize = YAY1_HEADER_LENGTH + ((data.size()+7)/8) + data.size(); + worstSize = YAY1_HEADER_LENGTH + ((data.size() + 7) / 8) + data.size(); compressedData = static_cast<uint8_t*>(std::calloc(worstSize, sizeof(uint8_t))); compressedSize = yay1_encode(data.data(), data.size(), compressedData); break; @@ -202,10 +206,10 @@ ExportResult CompressedTextureCodeExporter::Export(std::ostream &write, std::sha const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); - if(mode != TableMode::Append){ + if (mode != TableMode::Append) { throw std::runtime_error("Reference mode is not supported for now"); } @@ -213,26 +217,29 @@ ExportResult CompressedTextureCodeExporter::Export(std::ostream &write, std::sha isize = index_size; } - if(start == offset){ + if (start == offset) { write << "u8 " << name << "[][" << isize << "] = {\n"; } write << tab_t << "{\n"; - write << tab_t << tab_t << "#include \"" << Companion::Instance->GetDestRelativeOutputPath() + "/" << *replacement << ".incbin.c\"\n"; + write << tab_t << tab_t << "#include \"" << Companion::Instance->GetDestRelativeOutputPath() + "/" + << *replacement << ".incbin.c\"\n"; write << tab_t << "},\n"; - if(end == offset){ + if (end == offset) { write << "};\n"; if (Companion::Instance->IsDebug()) { - write << "// size: 0x" << std::hex << std::uppercase << ASSET_PTR((end - start) + isize * byteSize) << "\n"; + write << "// size: 0x" << std::hex << std::uppercase << ASSET_PTR((end - start) + isize * byteSize) + << "\n"; } } } else { - write << "u8 " << symbol << "[] = {\n"; + write << "u8 " << symbol << "[] = {\n"; - write << tab_t << "#include \"" << Companion::Instance->GetDestRelativeOutputPath() + "/" << *replacement << ".incbin.c\"\n"; + write << tab_t << "#include \"" << Companion::Instance->GetDestRelativeOutputPath() + "/" << *replacement + << ".incbin.c\"\n"; write << "};\n"; @@ -246,7 +253,9 @@ ExportResult CompressedTextureCodeExporter::Export(std::ostream &write, std::sha return offset + compressedSize; } -ExportResult CompressedTextureBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult CompressedTextureBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); auto texture = std::static_pointer_cast<CompressedTextureData>(raw); auto data = texture->mBuffer; @@ -255,21 +264,23 @@ ExportResult CompressedTextureBinaryExporter::Export(std::ostream &write, std::s WriteHeader(writer, Torch::ResourceType::Texture, 0); - if(texture->mFormat.type == TextureType::TLUT) { + if (texture->mFormat.type == TextureType::TLUT) { texture->mFormat.type = TextureType::RGBA16bpp; } - writer.Write((uint32_t) texture->mFormat.type); + writer.Write((uint32_t)texture->mFormat.type); writer.Write(texture->mWidth); writer.Write(texture->mHeight); - writer.Write((uint32_t) data.size()); - writer.Write((char*) data.data(), data.size()); + writer.Write((uint32_t)data.size()); + writer.Write((char*)data.data(), data.size()); writer.Finish(write); return std::nullopt; } -ExportResult CompressedTextureModdingExporter::Export(std::ostream&write, std::shared_ptr<IParsedData> data, std::string&entryName, YAML::Node&node, std::string* replacement) { +ExportResult CompressedTextureModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto texture = std::static_pointer_cast<CompressedTextureData>(data); auto format = texture->mFormat; uint8_t* raw = new uint8_t[TextureUtils::CalculateTextureSize(format.type, texture->mWidth, texture->mHeight) * 2]; @@ -285,7 +296,7 @@ ExportResult CompressedTextureModdingExporter::Export(std::ostream&write, std::s case TextureType::RGBA16bpp: case TextureType::RGBA32bpp: { rgba* imgr = raw2rgba(texture->mBuffer.data(), texture->mWidth, texture->mHeight, format.depth); - if(rgba2png(&raw, &size, imgr, texture->mWidth, texture->mHeight)) { + if (rgba2png(&raw, &size, imgr, texture->mWidth, texture->mHeight)) { throw std::runtime_error("Failed to convert texture to PNG"); } break; @@ -295,7 +306,7 @@ ExportResult CompressedTextureModdingExporter::Export(std::ostream&write, std::s case TextureType::GrayscaleAlpha4bpp: case TextureType::GrayscaleAlpha1bpp: { ia* imgia = raw2ia(texture->mBuffer.data(), texture->mWidth, texture->mHeight, format.depth); - if(ia2png(&raw, &size, imgia, texture->mWidth, texture->mHeight)) { + if (ia2png(&raw, &size, imgia, texture->mWidth, texture->mHeight)) { throw std::runtime_error("Failed to convert texture to PNG"); } break; @@ -303,29 +314,35 @@ ExportResult CompressedTextureModdingExporter::Export(std::ostream&write, std::s case TextureType::Palette8bpp: case TextureType::Palette4bpp: { if (node["tlut_symbol"]) { - auto tlut = GetSafeNode<std::string>(node,"tlut_symbol"); + auto tlut = GetSafeNode<std::string>(node, "tlut_symbol"); auto palette = Companion::Instance->GetParseDataBySymbol(tlut); if (palette.has_value()) { auto palTexture = std::static_pointer_cast<TextureData>(palette.value().data.value()); - convert_raw_to_ci8(&raw, &size, texture->mBuffer.data(), (uint8_t *)palTexture->mBuffer.data(), 0, texture->mWidth, texture->mHeight, texture->mFormat.depth, palTexture->mFormat.depth); + convert_raw_to_ci8(&raw, &size, texture->mBuffer.data(), (uint8_t*)palTexture->mBuffer.data(), 0, + texture->mWidth, texture->mHeight, texture->mFormat.depth, + palTexture->mFormat.depth); } else { auto symbol = GetSafeNode<std::string>(node, "symbol"); - throw std::runtime_error("Could not convert ci8 '"+symbol+"' the tlut symbol name is probably wrong for tlut_symbol node"); + throw std::runtime_error("Could not convert ci8 '" + symbol + + "' the tlut symbol name is probably wrong for tlut_symbol node"); } break; } if (node["tlut"]) { - auto tlut = GetSafeNode<uint32_t>(node,"tlut"); + auto tlut = GetSafeNode<uint32_t>(node, "tlut"); auto palette = Companion::Instance->GetParseDataByAddr(tlut); if (palette.has_value()) { auto palTexture = std::static_pointer_cast<TextureData>(palette.value().data.value()); - convert_raw_to_ci8(&raw, &size, texture->mBuffer.data(), (uint8_t *)palTexture->mBuffer.data(), 0, texture->mWidth, texture->mHeight, texture->mFormat.depth, palTexture->mFormat.depth); + convert_raw_to_ci8(&raw, &size, texture->mBuffer.data(), (uint8_t*)palTexture->mBuffer.data(), 0, + texture->mWidth, texture->mHeight, texture->mFormat.depth, + palTexture->mFormat.depth); } else { auto symbol = GetSafeNode<std::string>(node, "symbol"); - throw std::runtime_error("Could not convert ci8 '"+symbol+"' the address is probably wrong for tlut address node"); + throw std::runtime_error("Could not convert ci8 '" + symbol + + "' the address is probably wrong for tlut address node"); } break; } @@ -333,7 +350,7 @@ ExportResult CompressedTextureModdingExporter::Export(std::ostream&write, std::s case TextureType::Grayscale8bpp: case TextureType::Grayscale4bpp: { ia* imgi = raw2i(texture->mBuffer.data(), texture->mWidth, texture->mHeight, format.depth); - if(ia2png(&raw, &size, imgi, texture->mWidth, texture->mHeight)) { + if (ia2png(&raw, &size, imgi, texture->mWidth, texture->mHeight)) { throw std::runtime_error("Failed to convert texture to PNG"); } break; @@ -364,7 +381,8 @@ std::string getcomptype(CompressionType type) { return "None"; } -std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto offset = GetSafeNode<uint32_t>(node, "offset"); auto format = GetSafeNode<std::string>(node, "format"); auto symbol = GetSafeNode<std::string>(node, "symbol"); @@ -376,37 +394,42 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse(std: if (!Torch::contains(sCompressionTypes, compression)) { SPDLOG_ERROR("Compresed Texture entry at {:X} in yaml missing compression type\n\ Please add one of the following compression types\n\ - MIO0, YAY0, YAY1, YAZ0 (Unsupported)", offset); + MIO0, YAY0, YAY1, YAZ0 (Unsupported)", + offset); return std::nullopt; } compressionType = sCompressionTypes.at(compression); - CompressionType realCompressionType = Decompressor::GetCompressionType(buffer, Decompressor::TranslateAddr(offset, false)); + CompressionType realCompressionType = + Decompressor::GetCompressionType(buffer, Decompressor::TranslateAddr(offset, false)); if (realCompressionType != compressionType) { SPDLOG_ERROR("Compressed Texture entry at {:X} in yaml uses mismatching compression type\n\ - Passed In {}, expected {}", offset, getcomptype(compressionType), getcomptype(realCompressionType)); + Passed In {}, expected {}", + offset, getcomptype(compressionType), getcomptype(realCompressionType)); return std::nullopt; } - DataChunk* uncompressedData = Decompressor::Decode(buffer, Decompressor::TranslateAddr(offset, false), compressionType); + DataChunk* uncompressedData = + Decompressor::Decode(buffer, Decompressor::TranslateAddr(offset, false), compressionType); std::transform(format.begin(), format.end(), format.begin(), ::toupper); if (format.empty()) { SPDLOG_ERROR("Texture entry at {:X} in yaml missing format node\n\ Please add one of the following formats\n\ - rgba16, rgba32, ia16, ia8, ia4, i8, i4, ci8, ci4, 1bpp, tlut", offset); + rgba16, rgba32, ia16, ia8, ia4, i8, i4, ci8, ci4, 1bpp, tlut", + offset); return std::nullopt; } - if(!Torch::contains(sTextureFormats, format)) { + if (!Torch::contains(sTextureFormats, format)) { return std::nullopt; } TextureFormat fmt = sTextureFormats.at(format); - if(fmt.type == TextureType::TLUT){ + if (fmt.type == TextureType::TLUT) { width = GetSafeNode<uint32_t>(node, "colors"); height = 1; } else { @@ -414,7 +437,7 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse(std: height = GetSafeNode<uint32_t>(node, "height"); } - if((format == "CI4" || format == "CI8") && node["tlut"] && node["colors"]) { + if ((format == "CI4" || format == "CI8") && node["tlut"] && node["colors"]) { YAML::Node tlutNode; const auto tlutOffset = GetSafeNode<uint32_t>(node, "tlut"); const auto tlutSymbol = GetSafeNode(node, "tlut_symbol", symbol + "_tlut"); @@ -426,23 +449,24 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse(std: tlutNode["offset"] = tlutOffset; tlutNode["colors"] = GetSafeNode<uint32_t>(node, "colors"); node["tlut"] = tlutOffset; - if(node["tlut_ctype"]) { + if (node["tlut_ctype"]) { tlutNode["ctype"] = GetSafeNode<std::string>(node, "tlut_ctype"); } Companion::Instance->AddAsset(tlutNode); } - size = GetSafeNode<uint32_t>(node, "size", TextureUtils::CalculateTextureSize(sTextureFormats.at(format).type, width, height)); + size = GetSafeNode<uint32_t>(node, "size", + TextureUtils::CalculateTextureSize(sTextureFormats.at(format).type, width, height)); std::vector<uint8_t> result; - if(fmt.type == TextureType::GrayscaleAlpha1bpp){ + if (fmt.type == TextureType::GrayscaleAlpha1bpp) { result = TextureUtils::alloc_ia8_text_from_i1(reinterpret_cast<uint16_t*>(uncompressedData->data), 8, 16); } else { result = std::vector(uncompressedData->data, uncompressedData->data + uncompressedData->size); } SPDLOG_INFO("Texture: {}", format); - if(fmt.type == TextureType::TLUT){ + if (fmt.type == TextureType::TLUT) { SPDLOG_INFO("Colors: {}", width); } else { SPDLOG_INFO("Width: {}", width); @@ -451,18 +475,19 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse(std: SPDLOG_INFO("Size: {}", size); SPDLOG_INFO("Offset: 0x{:X}", offset); - if(result.size() == 0){ + if (result.size() == 0) { return std::nullopt; } - if(result.size() == 0){ + if (result.size() == 0) { return std::nullopt; } return std::make_shared<CompressedTextureData>(fmt, width, height, result, compressionType); } -std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modding(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modding(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto format = GetSafeNode<std::string>(node, "format"); int width; int height; @@ -473,7 +498,8 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modd if (!Torch::contains(sCompressionTypes, compression)) { SPDLOG_ERROR("Compresed Texture entry at {:X} in yaml missing compression type\n\ Please add one of the following compression types\n\ - MIO0, YAY0, YAY1, YAZ0 (Unsupported)", offset); + MIO0, YAY0, YAY1, YAZ0 (Unsupported)", + offset); return std::nullopt; } compressionType = sCompressionTypes.at(compression); @@ -481,16 +507,17 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modd if (format.empty()) { SPDLOG_ERROR("Texture entry at {:X} in yaml missing format node\n\ Please add one of the following formats\n\ - rgba16, rgba32, ia16, ia8, ia4, i8, i4, ci8, ci4, 1bpp, tlut", offset); + rgba16, rgba32, ia16, ia8, ia4, i8, i4, ci8, ci4, 1bpp, tlut", + offset); return std::nullopt; } - if(!Torch::contains(sTextureFormats, format)) { + if (!Torch::contains(sTextureFormats, format)) { return std::nullopt; } TextureFormat fmt = sTextureFormats.at(format); - if(fmt.type == TextureType::TLUT){ + if (fmt.type == TextureType::TLUT) { width = GetSafeNode<uint32_t>(node, "colors"); height = 1; } else { @@ -506,7 +533,7 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modd const auto imgr = png2rgba(buffer.data(), buffer.size(), &width, &height); size = width * height * fmt.depth / 8; raw = new uint8_t[size]; - if(rgba2raw(raw, imgr, width, height, fmt.depth) <= 0){ + if (rgba2raw(raw, imgr, width, height, fmt.depth) <= 0) { throw std::runtime_error("Failed to convert PNG to texture"); } break; @@ -518,7 +545,7 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modd const auto imgia = png2ia(buffer.data(), buffer.size(), &width, &height); size = width * height * fmt.depth / 8; raw = new uint8_t[size]; - if(ia2raw(raw, imgia, width, height, fmt.depth) <= 0){ + if (ia2raw(raw, imgia, width, height, fmt.depth) <= 0) { throw std::runtime_error("Failed to convert PNG to texture"); } break; @@ -539,7 +566,8 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modd // if (palettePtr) { // auto imgi = png2rgba(buffer.data(), buffer.size(), &width, &height); - // auto pal = png2rgba(palettePtr->mBuffer.data(), (palettePtr->mWidth * palettePtr->mWidth * palettePtr->mFormat.depth * 2), &width, &height); + // auto pal = png2rgba(palettePtr->mBuffer.data(), (palettePtr->mWidth * palettePtr->mWidth * + // palettePtr->mFormat.depth * 2), &width, &height); // size = width * height * fmt.depth / 8; // raw = new uint8_t[size]; @@ -558,7 +586,7 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modd const auto imgi = png2ia(buffer.data(), buffer.size(), &width, &height); size = width * height * fmt.depth / 8; raw = new uint8_t[size]; - if(i2raw(raw, imgi, width, height, fmt.depth) <= 0){ + if (i2raw(raw, imgi, width, height, fmt.depth) <= 0) { throw std::runtime_error("Failed to convert PNG to texture"); } break; @@ -572,7 +600,7 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modd auto result = std::vector(raw, raw + size); SPDLOG_INFO("Texture: {}", format); - if(fmt.type == TextureType::TLUT){ + if (fmt.type == TextureType::TLUT) { SPDLOG_INFO("Colors: {}", width); } else { SPDLOG_INFO("Width: {}", width); @@ -581,7 +609,7 @@ std::optional<std::shared_ptr<IParsedData>> CompressedTextureFactory::parse_modd SPDLOG_INFO("Size: {}", size); SPDLOG_INFO("Offset: 0x{:X}", offset); - if(result.size() == 0){ + if (result.size() == 0) { return std::nullopt; } diff --git a/src/factories/DisplayListFactory.cpp b/src/factories/DisplayListFactory.cpp index 2ee3fbf..a0f268c 100644 --- a/src/factories/DisplayListFactory.cpp +++ b/src/factories/DisplayListFactory.cpp @@ -14,45 +14,21 @@ #define ALIGN16(val) (((val) + 0xF) & ~0xF) std::unordered_map<std::string, uint8_t> gF3DTable = { - { "G_VTX", 0x04 }, - { "G_DL", 0x06 }, - { "G_MTX", 0x1 }, - { "G_ENDDL", 0xB8 }, - { "G_SETTIMG", 0xFD }, - { "G_MOVEMEM", 0x03 }, - { "G_MV_L0", 0x86 }, - { "G_MV_L1", 0x88 }, - { "G_MV_LIGHT", 0xA }, - { "G_TRI2", 0xB1 }, - { "G_QUAD", -1 } + { "G_VTX", 0x04 }, { "G_DL", 0x06 }, { "G_MTX", 0x1 }, { "G_ENDDL", 0xB8 }, + { "G_SETTIMG", 0xFD }, { "G_MOVEMEM", 0x03 }, { "G_MV_L0", 0x86 }, { "G_MV_L1", 0x88 }, + { "G_MV_LIGHT", 0xA }, { "G_TRI2", 0xB1 }, { "G_QUAD", -1 } }; std::unordered_map<std::string, uint8_t> gF3DExTable = { - { "G_VTX", 0x04 }, - { "G_DL", 0x06 }, - { "G_MTX", 0x1 }, - { "G_ENDDL", 0xB8 }, - { "G_SETTIMG", 0xFD }, - { "G_MOVEMEM", 0x03 }, - { "G_MV_L0", 0x86 }, - { "G_MV_L1", 0x88 }, - { "G_MV_LIGHT", 0xA }, - { "G_TRI2", 0xB1 }, - { "G_QUAD", 0xB5 } + { "G_VTX", 0x04 }, { "G_DL", 0x06 }, { "G_MTX", 0x1 }, { "G_ENDDL", 0xB8 }, + { "G_SETTIMG", 0xFD }, { "G_MOVEMEM", 0x03 }, { "G_MV_L0", 0x86 }, { "G_MV_L1", 0x88 }, + { "G_MV_LIGHT", 0xA }, { "G_TRI2", 0xB1 }, { "G_QUAD", 0xB5 } }; std::unordered_map<std::string, uint8_t> gF3DEx2Table = { - { "G_VTX", 0x01 }, - { "G_DL", 0xDE }, - { "G_MTX", 0xDA }, - { "G_ENDDL", 0xDF }, - { "G_SETTIMG", 0xFD }, - { "G_MOVEMEM", 0xDC }, - { "G_MV_L0", 0x86 }, - { "G_MV_L1", 0x88 }, - { "G_MV_LIGHT", 0xA }, - { "G_TRI2", 0x06 }, - { "G_QUAD", 0x07 } + { "G_VTX", 0x01 }, { "G_DL", 0xDE }, { "G_MTX", 0xDA }, { "G_ENDDL", 0xDF }, + { "G_SETTIMG", 0xFD }, { "G_MOVEMEM", 0xDC }, { "G_MV_L0", 0x86 }, { "G_MV_L1", 0x88 }, + { "G_MV_LIGHT", 0xA }, { "G_TRI2", 0x06 }, { "G_QUAD", 0x07 } }; std::unordered_map<GBIVersion, std::unordered_map<std::string, uint8_t>> gGBITable = { @@ -64,7 +40,7 @@ std::unordered_map<GBIVersion, std::unordered_map<std::string, uint8_t>> gGBITab #define GBI(cmd) gGBITable[Companion::Instance->GetGBIVersion()][#cmd] #ifdef STANDALONE -void GFXDSetGBIVersion(){ +void GFXDSetGBIVersion() { switch (Companion::Instance->GetGBIVersion()) { case GBIVersion::f3d: gfxd_target(gfxd_f3d); @@ -85,10 +61,11 @@ void GFXDSetGBIVersion(){ } #endif -ExportResult DListHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult DListHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -99,7 +76,8 @@ ExportResult DListHeaderExporter::Export(std::ostream &write, std::shared_ptr<IP #ifdef STANDALONE bool hasTable = false; -ExportResult DListCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult DListCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto cmds = std::static_pointer_cast<DListData>(raw)->mGfxs; const auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -109,7 +87,7 @@ ExportResult DListCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar size_t isize = cmds.size(); - char out[0xFFFF] = {0}; + char out[0xFFFF] = { 0 }; gfxd_input_buffer(cmds.data(), sizeof(uint32_t) * cmds.size()); gfxd_output_buffer(out, sizeof(out)); @@ -119,17 +97,17 @@ ExportResult DListCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar auto gfx = static_cast<const N64Gfx*>(gfxd_macro_data()); const uint8_t opcode = (gfx->words.w0 >> 24) & 0xFF; - if(hasTable) { + if (hasTable) { gfxd_puts(fourSpaceTab fourSpaceTab); } else { gfxd_puts(fourSpaceTab); } // For mk64 only - if(opcode == GBI(G_QUAD) && Companion::Instance->GetGBIMinorVersion() == GBIMinorVersion::Mk64) { + if (opcode == GBI(G_QUAD) && Companion::Instance->GetGBIMinorVersion() == GBIMinorVersion::Mk64) { GFXDOverride::Quadrangle(gfx); - // Prevents mix and matching of quadrangle commands. Forces 2TRI only. - } else if(opcode == GBI(G_TRI2)) { + // Prevents mix and matching of quadrangle commands. Forces 2TRI only. + } else if (opcode == GBI(G_TRI2)) { GFXDOverride::Triangle2(gfx); } else { gfxd_macro_dflt(); @@ -149,10 +127,10 @@ ExportResult DListCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar gfxd_mtx_callback(GFXDOverride::Matrix); GFXDSetGBIVersion(); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); - if(mode != TableMode::Append){ + if (mode != TableMode::Append) { throw std::runtime_error("Reference mode is not supported for now"); } @@ -160,7 +138,7 @@ ExportResult DListCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar isize = index_size; } - if(start == offset){ + if (start == offset) { gfxd_puts(("Gfx " + name + "[][" + std::to_string(isize / 2) + "] = {\n").c_str()); gfxd_puts("\t{\n"); } else { @@ -168,12 +146,12 @@ ExportResult DListCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar } gfxd_execute(); write << std::string(out); - if(end == offset){ + if (end == offset) { write << fourSpaceTab << "}\n"; write << "};\n"; if (Companion::Instance->IsDebug()) { write << "// count: " << std::to_string(sz / 8) << " Gfx\n"; - }else { + } else { write << "\n"; } } else { @@ -195,12 +173,12 @@ ExportResult DListCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar return offset + sz; } -void DebugDisplayList(uint32_t w0, uint32_t w1){ - uint32_t dlist[] = {w0, w1}; +void DebugDisplayList(uint32_t w0, uint32_t w1) { + uint32_t dlist[] = { w0, w1 }; gfxd_input_buffer(dlist, sizeof(dlist)); gfxd_output_fd(fileno(stdout)); gfxd_endian(gfxd_endian_host, sizeof(uint32_t)); - gfxd_macro_fn([](){ + gfxd_macro_fn([]() { gfxd_puts("> "); gfxd_macro_dflt(); gfxd_puts("\n"); @@ -210,27 +188,27 @@ void DebugDisplayList(uint32_t w0, uint32_t w1){ gfxd_timg_callback(GFXDOverride::Texture); gfxd_dl_callback(GFXDOverride::DisplayList); gfxd_tlut_callback(GFXDOverride::Palette); - //gfxd_light_callback(GFXDOverride::Light); + // gfxd_light_callback(GFXDOverride::Light); GFXDSetGBIVersion(); gfxd_execute(); } #endif -std::optional<std::tuple<std::string, YAML::Node>> SearchVtx(uint32_t ptr){ +std::optional<std::tuple<std::string, YAML::Node>> SearchVtx(uint32_t ptr) { auto decs = Companion::Instance->GetNodesByType("VTX"); - if(!decs.has_value()){ + if (!decs.has_value()) { return std::nullopt; } - for(auto& dec : decs.value()){ + for (auto& dec : decs.value()) { auto [name, node] = dec; auto offset = GetSafeNode<uint32_t>(node, "offset"); auto count = GetSafeNode<uint32_t>(node, "count"); auto end = ALIGN16((count * sizeof(N64Vtx_t))); - if(ptr > offset && ptr < offset + end){ + if (ptr > offset && ptr < offset + end) { return std::make_tuple(GetSafeNode<std::string>(node, "symbol", name), node); } } @@ -238,15 +216,16 @@ std::optional<std::tuple<std::string, YAML::Node>> SearchVtx(uint32_t ptr){ return std::nullopt; } -ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult DListBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto gbi = Companion::Instance->GetGBIVersion(); auto cmds = std::static_pointer_cast<DListData>(raw)->mGfxs; auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::DisplayList, 0); - writer.Write((int8_t) gbi); - + writer.Write((int8_t)gbi); + while (writer.GetBaseAddress() % 8 != 0) writer.Write(static_cast<int8_t>(0xFF)); @@ -256,12 +235,12 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP writer.Write(static_cast<uint32_t>(bhash >> 32)); writer.Write(static_cast<uint32_t>(bhash & 0xFFFFFFFF)); - for(size_t i = 0; i < cmds.size(); i+=2){ + for (size_t i = 0; i < cmds.size(); i += 2) { auto w0 = cmds[i]; auto w1 = cmds[i + 1]; uint8_t opcode = w0 >> 24; - if(opcode == GBI(G_VTX)) { + if (opcode == GBI(G_VTX)) { size_t nvtx; size_t didx; @@ -284,12 +263,12 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP auto ptr = w1; auto overlap = GFXDOverride::GetVtxOverlap(ptr); - if(overlap.has_value()){ + if (overlap.has_value()) { auto ovnode = std::get<1>(overlap.value()); auto path = Companion::Instance->RelativePath(std::get<0>(overlap.value())); uint64_t hash = CRC64(path.c_str()); - if(hash == 0) { + if (hash == 0) { throw std::runtime_error("Vtx hash is 0 for " + std::get<0>(overlap.value())); } @@ -313,9 +292,9 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP w1 = hash & 0xFFFFFFFF; } else { auto dec = Companion::Instance->GetSafeStringByAddr(ptr, "VTX"); - if(dec.has_value()){ + if (dec.has_value()) { uint64_t hash = CRC64(dec.value().c_str()); - if(hash == 0) { + if (hash == 0) { throw std::runtime_error("Vtx hash is 0 for " + dec.value()); } @@ -339,7 +318,7 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP } } - if(opcode == GBI(G_DL)) { + if (opcode == GBI(G_DL)) { N64Gfx value; auto ptr = w1; auto dec = Companion::Instance->GetSafeStringByAddr(ptr, "GFX"); @@ -353,7 +332,7 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP writer.Write(w0); writer.Write(w1); - if(dec.has_value()){ + if (dec.has_value()) { uint64_t hash = CRC64(dec.value().c_str()); SPDLOG_INFO("Found display list: 0x{:X} Hash: 0x{:X} Path: {}", ptr, hash, dec.value()); w0 = hash >> 32; @@ -362,7 +341,7 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP SPDLOG_WARN("Could not find display list at 0x{:X}", ptr); } - if(branch){ + if (branch) { writer.Write(w0); writer.Write(w1); @@ -373,7 +352,7 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP } // TODO: Fix this opcode - if(opcode == GBI(G_MOVEMEM)) { + if (opcode == GBI(G_MOVEMEM)) { auto ptr = w1; uint8_t index = 0; @@ -394,16 +373,16 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP offset = C0(8, 8) * 8; break; } - + auto res = Companion::Instance->GetStringByAddr(ptr); - if(!res.has_value()){ + if (!res.has_value()) { res = Companion::Instance->GetStringByAddr(ptr - 0x8); hasOffset = res.has_value(); - if(!hasOffset){ + if (!hasOffset) { SPDLOG_INFO("Could not find light {:X}", ptr); - // throw std::runtime_error("Could not find light"); + // throw std::runtime_error("Could not find light"); } } @@ -414,7 +393,7 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP writer.Write(w0); writer.Write(w1); - if(res.has_value()){ + if (res.has_value()) { uint64_t hash = CRC64(res.value().c_str()); SPDLOG_INFO("Found movemem: 0x{:X} Hash: 0x{:X} Path: {}", ptr, hash, res.value()); w0 = hash >> 32; @@ -424,7 +403,7 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP } } - if(opcode == GBI(G_SETTIMG)) { + if (opcode == GBI(G_SETTIMG)) { auto ptr = w1; auto dec = Companion::Instance->GetSafeStringByAddr(ptr, "TEXTURE"); @@ -443,10 +422,10 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP writer.Write(w1); } - if(dec.has_value()){ + if (dec.has_value()) { uint64_t hash = CRC64(dec.value().c_str()); - if(hash == 0){ + if (hash == 0) { throw std::runtime_error("Texture hash is 0 for " + dec.value()); } @@ -458,7 +437,7 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP } } - if(opcode == GBI(G_MTX)) { + if (opcode == GBI(G_MTX)) { auto ptr = w1; auto dec = Companion::Instance->GetSafeStringByAddr(ptr, "MTX"); @@ -469,10 +448,10 @@ ExportResult DListBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP writer.Write(w0); writer.Write(w1); - if(dec.has_value()){ + if (dec.has_value()) { uint64_t hash = CRC64(dec.value().c_str()); - if(hash == 0){ + if (hash == 0) { throw std::runtime_error("Matrix hash is 0 for " + dec.value()); } @@ -504,17 +483,17 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint auto processing = true; size_t length = 0; - while (processing){ + while (processing) { auto w0 = reader.ReadUInt32(); auto w1 = reader.ReadUInt32(); uint8_t opcode = w0 >> 24; - if(opcode == GBI(G_ENDDL)) { + if (opcode == GBI(G_ENDDL)) { processing = false; } - if(opcode == GBI(G_DL)) { + if (opcode == GBI(G_DL)) { if (C0(16, 1) == G_DL_NO_PUSH) { SPDLOG_INFO("Branch List Command Found"); processing = false; @@ -533,20 +512,20 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint // This opcode is generally used as part of multiple macros such as gsSPSetLights1. // We need to process gsSPLight which is a subcommand inside G_MOVEMEM (0x03). - if(opcode == GBI(G_MOVEMEM)) { - // 0x03860000 or 0x03880000 subcommand will contain 0x86/0x88 for G_MV_L0 and G_MV_L1. Other subcommands also exist. + if (opcode == GBI(G_MOVEMEM)) { + // 0x03860000 or 0x03880000 subcommand will contain 0x86/0x88 for G_MV_L0 and G_MV_L1. Other subcommands + // also exist. uint8_t subcommand = (w0 >> 16) & 0xFF; uint8_t index = 0; uint8_t offset = 0; bool light = false; switch (Companion::Instance->GetGBIVersion()) { - // If needing light generation on G_MV_L0 then we'll need to walk the DL ptr forward/backward to check for 0xBC - // Otherwise mk64 will break. - // PD: Mega, this works for sm64 too, why you didn't implement it? >:( - // PD: Im jk, <3 - case GBIVersion::f3d: - case GBIVersion::f3dex: + // If needing light generation on G_MV_L0 then we'll need to walk the DL ptr forward/backward to check + // for 0xBC Otherwise mk64 will break. PD: Mega, this works for sm64 too, why you didn't implement it? + // >:( PD: Im jk, <3 + case GBIVersion::f3d: + case GBIVersion::f3dex: /* * Only generate lights on the second gsSPLight. * gsSPSetLights1(name) outputs three macros: @@ -554,7 +533,7 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint * gsSPNumLights(NUMLIGHTS_1) * gsSPLight(&name.l[0], G_MV_L0) * gsSPLight(&name.a, G_MV_L1) <-- This ptr is used to generate the lights - */ + */ if (subcommand == GBI(G_MV_L1)) { light = true; } @@ -563,7 +542,7 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint offset = C0(8, 8) * 8; // same thing as above; see macro gSPLight at gbi.h - if(index == GBI(G_MV_LIGHT) && offset == (2 * 24 + 24)) { + if (index == GBI(G_MV_LIGHT) && offset == (2 * 24 + 24)) { light = true; } break; @@ -571,7 +550,7 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint throw std::runtime_error("Unsupported GBI version"); } - if(light){ + if (light) { YAML::Node lnode; lnode["type"] = "LIGHTS"; lnode["offset"] = w1; @@ -579,28 +558,28 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint } } - if(opcode == GBI(G_VTX)) { + if (opcode == GBI(G_VTX)) { uint32_t nvtx; switch (gbi) { case GBIVersion::f3dex2: nvtx = C0(12, 8); - break; + break; case GBIVersion::f3dex: case GBIVersion::f3dexb: nvtx = C0(10, 6); - break; + break; default: nvtx = (C0(0, 16)) / sizeof(N64Vtx_t); - break; + break; } const auto decl = Companion::Instance->GetNodeByAddr(w1); - if(!decl.has_value()){ + if (!decl.has_value()) { auto adjPtr = Companion::Instance->PatchVirtualAddr(w1); auto search = SearchVtx(adjPtr); - if(search.has_value()){ + if (search.has_value()) { auto [path, vtx] = search.value(); SPDLOG_INFO("Path: {}", path); @@ -609,7 +588,7 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint auto lCount = GetSafeNode<uint32_t>(vtx, "count"); auto lSize = ALIGN16(lCount * sizeof(N64Vtx_t)); - if(adjPtr > lOffset && adjPtr <= lOffset + lSize){ + if (adjPtr > lOffset && adjPtr <= lOffset + lSize) { SPDLOG_INFO("Found vtx at 0x{:X} matching last vtx at 0x{:X}", adjPtr, lOffset); GFXDOverride::RegisterVTXOverlap(adjPtr, search.value()); } @@ -625,7 +604,7 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint } } - if(count != -1 && length++ >= count){ + if (count != -1 && length++ >= count) { break; } @@ -633,7 +612,5 @@ std::optional<std::shared_ptr<IParsedData>> DListFactory::parse(std::vector<uint gfxs.push_back(w1); } - - return std::make_shared<DListData>(gfxs); } diff --git a/src/factories/DisplayListOverrides.cpp b/src/factories/DisplayListOverrides.cpp index 5dc6086..45bd1a9 100644 --- a/src/factories/DisplayListOverrides.cpp +++ b/src/factories/DisplayListOverrides.cpp @@ -20,13 +20,13 @@ void Triangle2(const N64Gfx* gfx) { auto w0 = gfx->words.w0; auto w1 = gfx->words.w1; - auto v1 = std::to_string( ((w0 >> 16) & 0xFF) / 2 ); - auto v2 = std::to_string( ((w0 >> 8) & 0xFF) / 2 ); - auto v3 = std::to_string( (w0 & 0xFF) / 2 ); + auto v1 = std::to_string(((w0 >> 16) & 0xFF) / 2); + auto v2 = std::to_string(((w0 >> 8) & 0xFF) / 2); + auto v3 = std::to_string((w0 & 0xFF) / 2); - auto v4 = std::to_string( ((w1 >> 16) & 0xFF) / 2 ); - auto v5 = std::to_string( ((w1 >> 8) & 0xFF) / 2 ); - auto v6 = std::to_string( (w1 & 0xFF) / 2 ); + auto v4 = std::to_string(((w1 >> 16) & 0xFF) / 2); + auto v5 = std::to_string(((w1 >> 8) & 0xFF) / 2); + auto v6 = std::to_string((w1 & 0xFF) / 2); auto flag = "0"; const auto str = v1 + ", " + v2 + ", " + v3 + ", " + flag + ", " + v4 + ", " + v5 + ", " + v6 + ", " + flag; @@ -39,10 +39,10 @@ void Triangle2(const N64Gfx* gfx) { void Quadrangle(const N64Gfx* gfx) { auto w1 = gfx->words.w1; - auto v1 = std::to_string( ((w1 >> 16) & 0xFF) / 2 ); - auto v2 = std::to_string( ((w1 >> 8) & 0xFF) / 2 ); - auto v3 = std::to_string( (w1 & 0xFF) / 2 ); - auto v4 = std::to_string( ((w1 >> 24) & 0xFF) / 2 ); + auto v1 = std::to_string(((w1 >> 16) & 0xFF) / 2); + auto v2 = std::to_string(((w1 >> 8) & 0xFF) / 2); + auto v3 = std::to_string((w1 & 0xFF) / 2); + auto v4 = std::to_string(((w1 >> 24) & 0xFF) / 2); auto flag = "0"; const auto str = v1 + ", " + v2 + ", " + v3 + ", " + v4 + ", " + flag; @@ -56,7 +56,7 @@ int Vtx(uint32_t ptr, int32_t num) { ptr = Companion::Instance->PatchVirtualAddr(ptr); auto vtx = GetVtxOverlap(ptr); - if(vtx.has_value()){ + if (vtx.has_value()) { auto symbol = std::get<0>(vtx.value()); auto node = std::get<1>(vtx.value()); @@ -75,7 +75,7 @@ int Vtx(uint32_t ptr, int32_t num) { auto dec = Companion::Instance->GetSafeNodeByAddr(ptr, "VTX"); - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found Vtx: 0x{:X} Symbol: {}", ptr, symbol); @@ -90,7 +90,7 @@ int Vtx(uint32_t ptr, int32_t num) { int Texture(uint32_t ptr, int32_t fmt, int32_t siz, int32_t width, int32_t height, int32_t pal) { auto dec = Companion::Instance->GetSafeNodeByAddr(ptr, "TEXTURE"); - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found Texture: 0x{:X} Symbol: {}", ptr, symbol); @@ -105,7 +105,7 @@ int Texture(uint32_t ptr, int32_t fmt, int32_t siz, int32_t width, int32_t heigh int Palette(uint32_t ptr, int32_t idx, int32_t count) { auto dec = Companion::Instance->GetSafeNodeByAddr(ptr, "TEXTURE"); - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found TLUT: 0x{:X} Symbol: {}", ptr, symbol); @@ -120,7 +120,7 @@ int Palette(uint32_t ptr, int32_t idx, int32_t count) { int Lights(uint32_t ptr, int32_t count) { auto dec = Companion::Instance->GetSafeNodeByAddr(ptr, "LIGHTS"); - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found Lightsn: 0x{:X} Symbol: {}", ptr, symbol); @@ -135,7 +135,7 @@ int Lights(uint32_t ptr, int32_t count) { int Light(uint32_t ptr) { auto res = Companion::Instance->GetSafeNodeByAddr(ptr, "LIGHTS"); - if(res.has_value()){ + if (res.has_value()) { auto node = std::get<1>(res.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found Light A Ptr: 0x{:X} Symbol: {}", ptr, symbol); @@ -145,7 +145,7 @@ int Light(uint32_t ptr) { res = Companion::Instance->GetSafeNodeByAddr(ptr - 0x8, "LIGHTS"); - if(res.has_value()){ + if (res.has_value()) { auto node = std::get<1>(res.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found Light L Ptr: 0x{:X} Symbol: {}", ptr, symbol); @@ -160,7 +160,7 @@ int Light(uint32_t ptr) { int DisplayList(uint32_t ptr) { auto dec = Companion::Instance->GetSafeNodeByAddr(ptr, "GFX"); - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found Display List: 0x{:X} Symbol: {}", ptr, symbol); @@ -175,7 +175,7 @@ int DisplayList(uint32_t ptr) { int Viewport(uint32_t ptr) { auto dec = Companion::Instance->GetSafeNodeByAddr(ptr, "VP"); - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found Viewport: 0x{:X} Symbol: {}", ptr, symbol); @@ -190,7 +190,7 @@ int Viewport(uint32_t ptr) { int Matrix(uint32_t ptr) { auto dec = Companion::Instance->GetSafeNodeByAddr(ptr, "MTX"); - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); SPDLOG_INFO("Found Matrix: 0x{:X} Symbol: {}", ptr, symbol); @@ -203,8 +203,8 @@ int Matrix(uint32_t ptr) { } #endif -std::optional<std::tuple<std::string, YAML::Node>> GetVtxOverlap(uint32_t ptr){ - if(Torch::contains(mVtxOverlaps, ptr)){ +std::optional<std::tuple<std::string, YAML::Node>> GetVtxOverlap(uint32_t ptr) { + if (Torch::contains(mVtxOverlaps, ptr)) { SPDLOG_INFO("Found overlap for ptr 0x{:X}", ptr); return mVtxOverlaps[ptr]; } @@ -214,12 +214,12 @@ std::optional<std::tuple<std::string, YAML::Node>> GetVtxOverlap(uint32_t ptr){ return std::nullopt; } -void RegisterVTXOverlap(uint32_t ptr, std::tuple<std::string, YAML::Node>& vtx){ +void RegisterVTXOverlap(uint32_t ptr, std::tuple<std::string, YAML::Node>& vtx) { mVtxOverlaps[ptr] = vtx; SPDLOG_INFO("Register overlap for ptr 0x{:X}", ptr); } -void ClearVtx(){ +void ClearVtx() { mVtxOverlaps.clear(); } -} +} // namespace GFXDOverride diff --git a/src/factories/FloatFactory.cpp b/src/factories/FloatFactory.cpp index b213499..f7dcd9e 100644 --- a/src/factories/FloatFactory.cpp +++ b/src/factories/FloatFactory.cpp @@ -7,10 +7,11 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) std::dec << std::setfill(' ') << std::setw(3) << c -ExportResult FloatHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FloatHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -19,7 +20,8 @@ ExportResult FloatHeaderExporter::Export(std::ostream &write, std::shared_ptr<IP return std::nullopt; } -ExportResult FloatCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult FloatCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto f = std::static_pointer_cast<FloatData>(raw)->mFloats; const auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -42,7 +44,7 @@ ExportResult FloatCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar * 0.1, 0.2, 0.3, * }; * - */ + */ for (int i = 0; i < f.size(); ++i) { // Make a new line every fourth iteration @@ -69,13 +71,14 @@ ExportResult FloatCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar return offset + f.size() * sizeof(float); } -ExportResult FloatBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult FloatBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto f = std::static_pointer_cast<FloatData>(raw); auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::Float, 0); - writer.Write((uint32_t) f->mFloats.size()); - for(auto fl : f->mFloats) { + writer.Write((uint32_t)f->mFloats.size()); + for (auto fl : f->mFloats) { writer.Write(fl); } throw std::runtime_error("Float factory untested for otr/o2r exporter"); @@ -92,7 +95,7 @@ std::optional<std::shared_ptr<IParsedData>> FloatFactory::parse(std::vector<uint reader.SetEndianness(Torch::Endianness::Big); std::vector<float> floats; - for(size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { auto f = reader.ReadFloat(); floats.push_back(f); diff --git a/src/factories/GenericArrayFactory.cpp b/src/factories/GenericArrayFactory.cpp index 12b698f..ccff544 100644 --- a/src/factories/GenericArrayFactory.cpp +++ b/src/factories/GenericArrayFactory.cpp @@ -11,60 +11,26 @@ #define GET_MAG_U(num) ((uint32_t)((num > 1) ? std::log10(num) + 1 : 1)) std::unordered_map<std::string, ArrayType> arrayTypeMap = { - { "u8", ArrayType::u8 }, - { "s8", ArrayType::s8 }, - { "u16", ArrayType::u16 }, - { "s16", ArrayType::s16 }, - { "u32", ArrayType::u32 }, - { "s32", ArrayType::s32 }, - { "u64", ArrayType::u64 }, - { "f32", ArrayType::f32 }, - { "f64", ArrayType::f64 }, - { "Vec2f", ArrayType::Vec2f }, - { "Vec3f", ArrayType::Vec3f }, - { "Vec3s", ArrayType::Vec3s }, - { "Vec3i", ArrayType::Vec3i }, - { "Vec3iu", ArrayType::Vec3iu }, - { "Vec4f", ArrayType::Vec4f }, + { "u8", ArrayType::u8 }, { "s8", ArrayType::s8 }, { "u16", ArrayType::u16 }, + { "s16", ArrayType::s16 }, { "u32", ArrayType::u32 }, { "s32", ArrayType::s32 }, + { "u64", ArrayType::u64 }, { "f32", ArrayType::f32 }, { "f64", ArrayType::f64 }, + { "Vec2f", ArrayType::Vec2f }, { "Vec3f", ArrayType::Vec3f }, { "Vec3s", ArrayType::Vec3s }, + { "Vec3i", ArrayType::Vec3i }, { "Vec3iu", ArrayType::Vec3iu }, { "Vec4f", ArrayType::Vec4f }, { "Vec4s", ArrayType::Vec4s }, }; std::unordered_map<ArrayType, size_t> typeSizeMap = { - { ArrayType::u8, 1 }, - { ArrayType::s8, 1 }, - { ArrayType::u16, 2 }, - { ArrayType::s16, 2 }, - { ArrayType::u32, 4 }, - { ArrayType::s32, 4 }, - { ArrayType::u64, 8 }, - { ArrayType::f32, 4 }, - { ArrayType::f64, 8 }, - { ArrayType::Vec2f, 8 }, - { ArrayType::Vec3f, 12 }, - { ArrayType::Vec3s, 6 }, - { ArrayType::Vec3i, 12 }, - { ArrayType::Vec3iu, 12 }, - { ArrayType::Vec4f, 16 }, - { ArrayType::Vec4s, 8 }, + { ArrayType::u8, 1 }, { ArrayType::s8, 1 }, { ArrayType::u16, 2 }, { ArrayType::s16, 2 }, + { ArrayType::u32, 4 }, { ArrayType::s32, 4 }, { ArrayType::u64, 8 }, { ArrayType::f32, 4 }, + { ArrayType::f64, 8 }, { ArrayType::Vec2f, 8 }, { ArrayType::Vec3f, 12 }, { ArrayType::Vec3s, 6 }, + { ArrayType::Vec3i, 12 }, { ArrayType::Vec3iu, 12 }, { ArrayType::Vec4f, 16 }, { ArrayType::Vec4s, 8 }, }; std::unordered_map<ArrayType, size_t> structCountMap = { - { ArrayType::u8, 1 }, - { ArrayType::s8, 1 }, - { ArrayType::u16, 1 }, - { ArrayType::s16, 1 }, - { ArrayType::u32, 1 }, - { ArrayType::s32, 1 }, - { ArrayType::u64, 1 }, - { ArrayType::f32, 1 }, - { ArrayType::f64, 1 }, - { ArrayType::Vec2f, 2 }, - { ArrayType::Vec3f, 3 }, - { ArrayType::Vec3s, 3 }, - { ArrayType::Vec3i, 3 }, - { ArrayType::Vec3iu, 3 }, - { ArrayType::Vec4f, 4 }, - { ArrayType::Vec4s, 4 }, + { ArrayType::u8, 1 }, { ArrayType::s8, 1 }, { ArrayType::u16, 1 }, { ArrayType::s16, 1 }, + { ArrayType::u32, 1 }, { ArrayType::s32, 1 }, { ArrayType::u64, 1 }, { ArrayType::f32, 1 }, + { ArrayType::f64, 1 }, { ArrayType::Vec2f, 2 }, { ArrayType::Vec3f, 3 }, { ArrayType::Vec3s, 3 }, + { ArrayType::Vec3i, 3 }, { ArrayType::Vec3iu, 3 }, { ArrayType::Vec4f, 4 }, { ArrayType::Vec4s, 4 }, }; static int GetPrecision(float f) { @@ -72,7 +38,7 @@ static int GetPrecision(float f) { int shift = 1; float approx = std::round(f); - while(f != approx && p < 12 ){ + while (f != approx && p < 12) { shift *= 10; p++; approx = std::round(f * shift) / shift; @@ -83,7 +49,7 @@ static int GetPrecision(float f) { GenericArray::GenericArray(std::vector<ArrayDatum> data) : mData(std::move(data)) { mMaxWidth = 1; mMaxPrec = 1; - for (auto &datum : mData) { + for (auto& datum : mData) { switch (static_cast<ArrayType>(datum.index())) { case ArrayType::u8: { mMaxWidth = std::max(mMaxWidth, GET_MAG_U((uint32_t)std::get<uint8_t>(datum))); @@ -148,7 +114,7 @@ GenericArray::GenericArray(std::vector<ArrayDatum> data) : mData(std::move(data) break; } case ArrayType::Vec4f: { - mMaxWidth = std::max(mMaxWidth,(uint32_t)std::get<Vec4f>(datum).width()); + mMaxWidth = std::max(mMaxWidth, (uint32_t)std::get<Vec4f>(datum).width()); mMaxPrec = std::max(mMaxPrec, (uint32_t)std::get<Vec4f>(datum).precision()); break; } @@ -160,11 +126,12 @@ GenericArray::GenericArray(std::vector<ArrayDatum> data) : mData(std::move(data) } } -ExportResult ArrayHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult ArrayHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto type = GetSafeNode<std::string>(node, "array_type"); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -173,7 +140,8 @@ ExportResult ArrayHeaderExporter::Export(std::ostream &write, std::shared_ptr<IP return std::nullopt; } -ExportResult ArrayCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult ArrayCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto type = GetSafeNode<std::string>(node, "array_type"); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -188,12 +156,11 @@ ExportResult ArrayCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar size_t typeSize = typeSizeMap.at(arrayType); - write << type << " " << symbol << "[] = {"; int columnCount = 120 / (structCountMap.at(arrayType) * array->mMaxWidth + 8); int i = 0; - for (auto &datum : array->mData) { + for (auto& datum : array->mData) { if ((i++ % columnCount) == 0) { write << "\n" << fourSpaceTab; } @@ -258,7 +225,8 @@ ExportResult ArrayCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar return offset + array->mData.size() * typeSize; } -ExportResult ArrayBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult ArrayBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto type = GetSafeNode<std::string>(node, "array_type"); auto array = std::static_pointer_cast<GenericArray>(raw); @@ -273,9 +241,9 @@ ExportResult ArrayBinaryExporter::Export(std::ostream &write, std::shared_ptr<IP WriteHeader(writer, Torch::ResourceType::GenericArray, 0); writer.Write(static_cast<uint32_t>(arrayType)); - writer.Write((uint32_t) array->mData.size()); + writer.Write((uint32_t)array->mData.size()); - for (auto &datum : array->mData) { + for (auto& datum : array->mData) { switch (static_cast<ArrayType>(datum.index())) { case ArrayType::u8: { writer.Write(std::get<uint8_t>(datum)); diff --git a/src/factories/IncludeFactory.cpp b/src/factories/IncludeFactory.cpp index d816d7d..ca40792 100644 --- a/src/factories/IncludeFactory.cpp +++ b/src/factories/IncludeFactory.cpp @@ -7,11 +7,12 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) std::dec << std::setfill(' ') << std::setw(3) << c -ExportResult IncludeHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult IncludeHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto ctype = GetSafeNode<std::string>(node, "ctype"); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -20,11 +21,12 @@ ExportResult IncludeHeaderExporter::Export(std::ostream &write, std::shared_ptr< return std::nullopt; } -ExportResult IncludeCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult IncludeCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto file = GetSafeNode<std::string>(node, "file_path"); const auto ctype = GetSafeNode<std::string>(node, "ctype"); - SPDLOG_INFO("writing INC"); + SPDLOG_INFO("writing INC"); write << ctype << " " << symbol << "[] = {\n"; write << fourSpaceTab << "#include \"" << file << "\"\n"; diff --git a/src/factories/LightsFactory.cpp b/src/factories/LightsFactory.cpp index cb5d9b5..6b21643 100644 --- a/src/factories/LightsFactory.cpp +++ b/src/factories/LightsFactory.cpp @@ -4,10 +4,11 @@ #include "spdlog/spdlog.h" #include "Companion.h" -ExportResult LightsHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult LightsHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -15,10 +16,10 @@ ExportResult LightsHeaderExporter::Export(std::ostream &write, std::shared_ptr<I const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); - if(start != offset){ + if (start != offset) { return std::nullopt; } @@ -29,34 +30,34 @@ ExportResult LightsHeaderExporter::Export(std::ostream &write, std::shared_ptr<I return std::nullopt; } -ExportResult LightsCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult LightsCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto light = std::static_pointer_cast<LightsData>(raw)->mLights; auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); - - if(start == offset){ + if (start == offset) { write << "Lights1 " << name << "[] = {\n"; } // Ambient - auto r = (int16_t) light.a.l.col[0]; - auto g = (int16_t) light.a.l.col[1]; - auto b = (int16_t) light.a.l.col[2]; + auto r = (int16_t)light.a.l.col[0]; + auto g = (int16_t)light.a.l.col[1]; + auto b = (int16_t)light.a.l.col[2]; // Diffuse - auto r2 = (int16_t) light.l[0].l.col[0]; - auto g2 = (int16_t) light.l[0].l.col[1]; - auto b2 = (int16_t) light.l[0].l.col[2]; + auto r2 = (int16_t)light.l[0].l.col[0]; + auto g2 = (int16_t)light.l[0].l.col[1]; + auto b2 = (int16_t)light.l[0].l.col[2]; // Direction - auto x = (int16_t) light.l[0].l.dir[0]; - auto y = (int16_t) light.l[0].l.dir[1]; - auto z = (int16_t) light.l[0].l.dir[2]; + auto x = (int16_t)light.l[0].l.dir[0]; + auto y = (int16_t)light.l[0].l.dir[1]; + auto z = (int16_t)light.l[0].l.dir[2]; SPDLOG_INFO("Read light: {:X} {:X} {:X} {:X} {:X}", r, g, b, r2, g2); @@ -77,19 +78,19 @@ ExportResult LightsCodeExporter::Export(std::ostream &write, std::shared_ptr<IPa write << "Lights1 " << symbol << " = gdSPDefLights1(\n"; // Ambient - auto r = (int16_t) light.a.l.col[0]; - auto g = (int16_t) light.a.l.col[1]; - auto b = (int16_t) light.a.l.col[2]; + auto r = (int16_t)light.a.l.col[0]; + auto g = (int16_t)light.a.l.col[1]; + auto b = (int16_t)light.a.l.col[2]; // Diffuse - auto r2 = (int16_t) light.l[0].l.col[0]; - auto g2 = (int16_t) light.l[0].l.col[1]; - auto b2 = (int16_t) light.l[0].l.col[2]; + auto r2 = (int16_t)light.l[0].l.col[0]; + auto g2 = (int16_t)light.l[0].l.col[1]; + auto b2 = (int16_t)light.l[0].l.col[2]; // Direction - auto x = (int16_t) light.l[0].l.dir[0]; - auto y = (int16_t) light.l[0].l.dir[1]; - auto z = (int16_t) light.l[0].l.dir[2]; + auto x = (int16_t)light.l[0].l.dir[0]; + auto y = (int16_t)light.l[0].l.dir[1]; + auto z = (int16_t)light.l[0].l.dir[2]; SPDLOG_INFO("Read light: {:X} {:X} {:X} {:X} {:X}", r, g, b, r2, g2); @@ -103,7 +104,8 @@ ExportResult LightsCodeExporter::Export(std::ostream &write, std::shared_ptr<IPa return std::nullopt; } -ExportResult LightsBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult LightsBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto light = std::static_pointer_cast<LightsData>(raw)->mLights; auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::Lights, 0); @@ -118,6 +120,6 @@ std::optional<std::shared_ptr<IParsedData>> LightsFactory::parse(std::vector<uin auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, sizeof(Lights1Raw)); Lights1Raw lights; - reader.Read((char*) &lights, sizeof(Lights1Raw)); + reader.Read((char*)&lights, sizeof(Lights1Raw)); return std::make_shared<LightsData>(lights); } diff --git a/src/factories/MtxFactory.cpp b/src/factories/MtxFactory.cpp index 1ad30dc..9bc4b28 100644 --- a/src/factories/MtxFactory.cpp +++ b/src/factories/MtxFactory.cpp @@ -7,10 +7,11 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) std::dec << std::setfill(' ') << std::setw(3) << c -ExportResult MtxHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MtxHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -19,7 +20,8 @@ ExportResult MtxHeaderExporter::Export(std::ostream &write, std::shared_ptr<IPar return std::nullopt; } -ExportResult MtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MtxCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto m = std::static_pointer_cast<MtxData>(raw)->mMtxs; const auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -35,7 +37,7 @@ ExportResult MtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParse write << "// 0x" << std::hex << std::uppercase << offset << "\n"; } - #define fiveFourSpaceTabs fourSpaceTab << fourSpaceTab << fourSpaceTab << fourSpaceTab << fourSpaceTab << " " +#define fiveFourSpaceTabs fourSpaceTab << fourSpaceTab << fourSpaceTab << fourSpaceTab << fourSpaceTab << " " /** * toFixedPointMatrix(1.0, 0.0, 0.0, 0.0, @@ -53,7 +55,7 @@ ExportResult MtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParse for (int j = 0; j < 16; ++j) { // Turn 1, 3, and 6 into 1.0, 3.0, and 6.0. Unless it has a decimal number then leave it alone. - SPDLOG_INFO(m[i].mtx[j]); + SPDLOG_INFO(m[i].mtx[j]); if (std::abs(m[i].mtx[j] - static_cast<int>(m[i].mtx[j])) < 1e-6) { write << std::fixed << std::setprecision(1) << m[i].mtx[j]; } else { @@ -97,21 +99,22 @@ ExportResult MtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParse write << "\n"; - #undef fiveFourSpaceTabs +#undef fiveFourSpaceTabs return offset + sizeof(MtxRaw); } -ExportResult MtxBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MtxBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto mtx = std::static_pointer_cast<MtxData>(raw); auto writer = LUS::BinaryWriter(); auto floats = Companion::Instance->GetConfig().gbi.useFloats; WriteHeader(writer, Torch::ResourceType::Matrix, 0); - for(size_t i = 0; i < 4; i++){ - for(size_t j = 0; j < 4; j++){ - if(floats){ + for (size_t i = 0; i < 4; i++) { + for (size_t j = 0; j < 4; j++) { + if (floats) { writer.Write(mtx->mMtxs[0].mtx[i * 4 + j]); } else { writer.Write(mtx->mMtxs[0].mt.mint[i][j]); @@ -123,7 +126,7 @@ ExportResult MtxBinaryExporter::Export(std::ostream &write, std::shared_ptr<IPar } std::optional<std::shared_ptr<IParsedData>> MtxFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { - //auto count = GetSafeNode<size_t>(node, "count"); + // auto count = GetSafeNode<size_t>(node, "count"); auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, 1 * sizeof(MtxRaw)); @@ -131,21 +134,22 @@ std::optional<std::shared_ptr<IParsedData>> MtxFactory::parse(std::vector<uint8_ reader.SetEndianness(Torch::Endianness::Big); std::vector<MtxRaw> matrix; - #define FIXTOF(x) ((float)((x) / 65536.0f)) +#define FIXTOF(x) ((float)((x) / 65536.0f)) - // Reads the inteer portion, the fractional portion, puts each together into a fixed-point value, and finally converts to float. - for(size_t i = 0; i < 1; i++) { + // Reads the inteer portion, the fractional portion, puts each together into a fixed-point value, and finally + // converts to float. + for (size_t i = 0; i < 1; i++) { // Read the integer portion of the fixed-point value (ex. 4) - auto i1 = reader.ReadUInt16(); - auto i2 = reader.ReadUInt16(); - auto i3 = reader.ReadUInt16(); - auto i4 = reader.ReadUInt16(); - auto i5 = reader.ReadUInt16(); - auto i6 = reader.ReadUInt16(); - auto i7 = reader.ReadUInt16(); - auto i8 = reader.ReadUInt16(); - auto i9 = reader.ReadUInt16(); + auto i1 = reader.ReadUInt16(); + auto i2 = reader.ReadUInt16(); + auto i3 = reader.ReadUInt16(); + auto i4 = reader.ReadUInt16(); + auto i5 = reader.ReadUInt16(); + auto i6 = reader.ReadUInt16(); + auto i7 = reader.ReadUInt16(); + auto i8 = reader.ReadUInt16(); + auto i9 = reader.ReadUInt16(); auto i10 = reader.ReadUInt16(); auto i11 = reader.ReadUInt16(); auto i12 = reader.ReadUInt16(); @@ -155,15 +159,15 @@ std::optional<std::shared_ptr<IParsedData>> MtxFactory::parse(std::vector<uint8_ auto i16 = reader.ReadUInt16(); // Read the fractional portion of the fixed-point value (ex. 0.45) - auto f1 = reader.ReadUInt16(); - auto f2 = reader.ReadUInt16(); - auto f3 = reader.ReadUInt16(); - auto f4 = reader.ReadUInt16(); - auto f5 = reader.ReadUInt16(); - auto f6 = reader.ReadUInt16(); - auto f7 = reader.ReadUInt16(); - auto f8 = reader.ReadUInt16(); - auto f9 = reader.ReadUInt16(); + auto f1 = reader.ReadUInt16(); + auto f2 = reader.ReadUInt16(); + auto f3 = reader.ReadUInt16(); + auto f4 = reader.ReadUInt16(); + auto f5 = reader.ReadUInt16(); + auto f6 = reader.ReadUInt16(); + auto f7 = reader.ReadUInt16(); + auto f8 = reader.ReadUInt16(); + auto f9 = reader.ReadUInt16(); auto f10 = reader.ReadUInt16(); auto f11 = reader.ReadUInt16(); auto f12 = reader.ReadUInt16(); @@ -173,22 +177,22 @@ std::optional<std::shared_ptr<IParsedData>> MtxFactory::parse(std::vector<uint8_ auto f16 = reader.ReadUInt16(); // Place the integer and fractional portions together (ex 4.45) and convert to floating-point - auto m1 = FIXTOF( (int32_t) ( (i1 << 16) | f1 ) ); - auto m2 = FIXTOF( (int32_t) ( (i2 << 16) | f2 ) ); - auto m3 = FIXTOF( (int32_t) ( (i3 << 16) | f3 ) ); - auto m4 = FIXTOF( (int32_t) ( (i4 << 16) | f4 ) ); - auto m5 = FIXTOF( (int32_t) ( (i5 << 16) | f5 ) ); - auto m6 = FIXTOF( (int32_t) ( (i6 << 16) | f6 ) ); - auto m7 = FIXTOF( (int32_t) ( (i7 << 16) | f7 ) ); - auto m8 = FIXTOF( (int32_t) ( (i8 << 16) | f8 ) ); - auto m9 = FIXTOF( (int32_t) ( (i9 << 16) | f9 ) ); - auto m10 = FIXTOF( (int32_t) ( (i10 << 16) | f10 ) ); - auto m11 = FIXTOF( (int32_t) ( (i11 << 16) | f11 ) ); - auto m12 = FIXTOF( (int32_t) ( (i12 << 16) | f12 ) ); - auto m13 = FIXTOF( (int32_t) ( (i13 << 16) | f13 ) ); - auto m14 = FIXTOF( (int32_t) ( (i14 << 16) | f14 ) ); - auto m15 = FIXTOF( (int32_t) ( (i15 << 16) | f15 ) ); - auto m16 = FIXTOF( (int32_t) ( (i16 << 16) | f16 ) ); + auto m1 = FIXTOF((int32_t)((i1 << 16) | f1)); + auto m2 = FIXTOF((int32_t)((i2 << 16) | f2)); + auto m3 = FIXTOF((int32_t)((i3 << 16) | f3)); + auto m4 = FIXTOF((int32_t)((i4 << 16) | f4)); + auto m5 = FIXTOF((int32_t)((i5 << 16) | f5)); + auto m6 = FIXTOF((int32_t)((i6 << 16) | f6)); + auto m7 = FIXTOF((int32_t)((i7 << 16) | f7)); + auto m8 = FIXTOF((int32_t)((i8 << 16) | f8)); + auto m9 = FIXTOF((int32_t)((i9 << 16) | f9)); + auto m10 = FIXTOF((int32_t)((i10 << 16) | f10)); + auto m11 = FIXTOF((int32_t)((i11 << 16) | f11)); + auto m12 = FIXTOF((int32_t)((i12 << 16) | f12)); + auto m13 = FIXTOF((int32_t)((i13 << 16) | f13)); + auto m14 = FIXTOF((int32_t)((i14 << 16) | f14)); + auto m15 = FIXTOF((int32_t)((i15 << 16) | f15)); + auto m16 = FIXTOF((int32_t)((i16 << 16) | f16)); matrix.push_back(MtxRaw({ .mtx = { @@ -214,7 +218,7 @@ std::optional<std::shared_ptr<IParsedData>> MtxFactory::parse(std::vector<uint8_ })); } - #undef FIXTOF +#undef FIXTOF return std::make_shared<MtxData>(matrix); } diff --git a/src/factories/TextureFactory.cpp b/src/factories/TextureFactory.cpp index b7d555b..c436ca6 100644 --- a/src/factories/TextureFactory.cpp +++ b/src/factories/TextureFactory.cpp @@ -14,53 +14,55 @@ extern "C" { static bool isTable = false; static std::vector<std::string> tableEntries; -static const std::unordered_map <std::string, TextureFormat> sTextureFormats = { +static const std::unordered_map<std::string, TextureFormat> sTextureFormats = { { "RGBA16", { TextureType::RGBA16bpp, 16 } }, { "RGBA32", { TextureType::RGBA32bpp, 32 } }, - { "CI4", { TextureType::Palette4bpp, 4 } }, - { "CI8", { TextureType::Palette8bpp, 8 } }, - { "I4", { TextureType::Grayscale4bpp, 4 } }, - { "I8", { TextureType::Grayscale8bpp, 8 } }, - { "IA1", { TextureType::GrayscaleAlpha1bpp, 1 } }, - { "IA4", { TextureType::GrayscaleAlpha4bpp, 4 } }, - { "IA8", { TextureType::GrayscaleAlpha8bpp, 8 } }, - { "IA16", { TextureType::GrayscaleAlpha16bpp, 16 } }, - { "TLUT", { TextureType::TLUT, 16 } }, + { "CI4", { TextureType::Palette4bpp, 4 } }, + { "CI8", { TextureType::Palette8bpp, 8 } }, + { "I4", { TextureType::Grayscale4bpp, 4 } }, + { "I8", { TextureType::Grayscale8bpp, 8 } }, + { "IA1", { TextureType::GrayscaleAlpha1bpp, 1 } }, + { "IA4", { TextureType::GrayscaleAlpha4bpp, 4 } }, + { "IA8", { TextureType::GrayscaleAlpha8bpp, 8 } }, + { "IA16", { TextureType::GrayscaleAlpha16bpp, 16 } }, + { "TLUT", { TextureType::TLUT, 16 } }, }; -ExportResult TextureHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult TextureHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto format = GetSafeNode<std::string>(node, "format"); auto texture = std::static_pointer_cast<TextureData>(raw); auto data = texture->mBuffer; auto isOTR = Companion::Instance->IsOTRMode(); - size_t byteSize = std::max(1, (int) (texture->mFormat.depth / 8)); + size_t byteSize = std::max(1, (int)(texture->mFormat.depth / 8)); const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); unsigned int isize = index_size > -1 ? index_size : data.size() / byteSize; - if(isOTR){ + if (isOTR) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; tableEntries.push_back(symbol); - if(end == offset){ + if (end == offset) { write << "static const char* " << name << "[] = {\n"; - for(auto& entry : tableEntries){ + for (auto& entry : tableEntries) { write << tab_t << entry << ",\n"; } write << "};\n\n"; tableEntries.clear(); } } else { - write << "extern " << GetSafeNode<std::string>(node, "ctype", "u8") << " " << name << "[][" << isize << "];\n"; + write << "extern " << GetSafeNode<std::string>(node, "ctype", "u8") << " " << name << "[][" << isize + << "];\n"; } } else { - if(isOTR){ + if (isOTR) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; if (Companion::Instance->AddTextureDefines()) { write << "#define _" << symbol << "_WIDTH 0x" << std::hex << texture->mWidth << std::dec << "\n"; @@ -78,7 +80,8 @@ ExportResult TextureHeaderExporter::Export(std::ostream &write, std::shared_ptr< return std::nullopt; } -ExportResult TextureCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult TextureCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto texture = std::static_pointer_cast<TextureData>(raw); auto data = texture->mBuffer; auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -89,16 +92,16 @@ ExportResult TextureCodeExporter::Export(std::ostream &write, std::shared_ptr<IP (*replacement) += "." + format; std::string dpath = Companion::Instance->GetOutputPath() + "/" + (*replacement); - if(!exists(fs::path(dpath).parent_path())){ + if (!exists(fs::path(dpath).parent_path())) { create_directories(fs::path(dpath).parent_path()); } std::ostringstream imgstream; - size_t byteSize = std::max(1, (int) (texture->mFormat.depth / 8)); + size_t byteSize = std::max(1, (int)(texture->mFormat.depth / 8)); size_t isize = texture->mBuffer.size() / byteSize; - for (int i = 0; i < data.size(); i+=byteSize) { + for (int i = 0; i < data.size(); i += byteSize) { if (i % 16 == 0 && i != 0) { imgstream << std::endl; } @@ -113,7 +116,7 @@ ExportResult TextureCodeExporter::Export(std::ostream &write, std::shared_ptr<IP } imgstream << std::endl; - if (!Companion::Instance->IsUsingIndividualIncludes()){ + if (!Companion::Instance->IsUsingIndividualIncludes()) { std::ofstream file(dpath + ".inc.c", std::ios::binary); file << imgstream.str(); file.close(); @@ -121,10 +124,10 @@ ExportResult TextureCodeExporter::Export(std::ostream &write, std::shared_ptr<IP const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); - if(mode != TableMode::Append){ + if (mode != TableMode::Append) { throw std::runtime_error("Reference mode is not supported for now"); } @@ -132,29 +135,32 @@ ExportResult TextureCodeExporter::Export(std::ostream &write, std::shared_ptr<IP isize = index_size; } - if(start == offset){ + if (start == offset) { write << GetSafeNode<std::string>(node, "ctype", "u8") << " " << name << "[][" << isize << "] = {\n"; } write << tab_t << "{\n"; - if (!Companion::Instance->IsUsingIndividualIncludes()){ - write << tab_t << tab_t << "#include \"" << Companion::Instance->GetDestRelativeOutputPath() + "/" << *replacement << ".inc.c\"\n"; + if (!Companion::Instance->IsUsingIndividualIncludes()) { + write << tab_t << tab_t << "#include \"" << Companion::Instance->GetDestRelativeOutputPath() + "/" + << *replacement << ".inc.c\"\n"; } else { write << imgstream.str(); } write << tab_t << "},\n"; - if(end == offset){ + if (end == offset) { write << "};\n"; if (Companion::Instance->IsDebug()) { - write << "// size: 0x" << std::hex << std::uppercase << ASSET_PTR((end - start) + isize * byteSize) << "\n"; + write << "// size: 0x" << std::hex << std::uppercase << ASSET_PTR((end - start) + isize * byteSize) + << "\n"; } } } else { - write << GetSafeNode<std::string>(node, "ctype", "u8") << " " << symbol << "[] = {\n"; + write << GetSafeNode<std::string>(node, "ctype", "u8") << " " << symbol << "[] = {\n"; - if (!Companion::Instance->IsUsingIndividualIncludes()){ - write << tab_t << "#include \"" << Companion::Instance->GetDestRelativeOutputPath() + "/" << *replacement << ".inc.c\"\n"; + if (!Companion::Instance->IsUsingIndividualIncludes()) { + write << tab_t << "#include \"" << Companion::Instance->GetDestRelativeOutputPath() + "/" << *replacement + << ".inc.c\"\n"; } else { write << imgstream.str(); } @@ -170,28 +176,30 @@ ExportResult TextureCodeExporter::Export(std::ostream &write, std::shared_ptr<IP return offset + isize * byteSize; } -ExportResult TextureBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult TextureBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto texture = std::static_pointer_cast<TextureData>(raw); auto data = texture->mBuffer; WriteHeader(writer, Torch::ResourceType::Texture, 0); - if(texture->mFormat.type == TextureType::TLUT) { + if (texture->mFormat.type == TextureType::TLUT) { texture->mFormat.type = TextureType::RGBA16bpp; } - writer.Write((uint32_t) texture->mFormat.type); + writer.Write((uint32_t)texture->mFormat.type); writer.Write(texture->mWidth); writer.Write(texture->mHeight); - writer.Write((uint32_t) data.size()); - writer.Write((char*) data.data(), data.size()); + writer.Write((uint32_t)data.size()); + writer.Write((char*)data.data(), data.size()); writer.Finish(write); return std::nullopt; } -ExportResult TextureModdingExporter::Export(std::ostream&write, std::shared_ptr<IParsedData> data, std::string&entryName, YAML::Node&node, std::string* replacement) { +ExportResult TextureModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto texture = std::static_pointer_cast<TextureData>(data); auto format = texture->mFormat; uint8_t* raw = new uint8_t[TextureUtils::CalculateTextureSize(format.type, texture->mWidth, texture->mHeight) * 2]; @@ -207,7 +215,7 @@ ExportResult TextureModdingExporter::Export(std::ostream&write, std::shared_ptr< case TextureType::RGBA16bpp: case TextureType::RGBA32bpp: { rgba* imgr = raw2rgba(texture->mBuffer.data(), texture->mWidth, texture->mHeight, format.depth); - if(rgba2png(&raw, &size, imgr, texture->mWidth, texture->mHeight)) { + if (rgba2png(&raw, &size, imgr, texture->mWidth, texture->mHeight)) { throw std::runtime_error("Failed to convert texture to PNG"); } break; @@ -217,7 +225,7 @@ ExportResult TextureModdingExporter::Export(std::ostream&write, std::shared_ptr< case TextureType::GrayscaleAlpha4bpp: case TextureType::GrayscaleAlpha1bpp: { ia* imgia = raw2ia(texture->mBuffer.data(), texture->mWidth, texture->mHeight, format.depth); - if(ia2png(&raw, &size, imgia, texture->mWidth, texture->mHeight)) { + if (ia2png(&raw, &size, imgia, texture->mWidth, texture->mHeight)) { throw std::runtime_error("Failed to convert texture to PNG"); } break; @@ -225,29 +233,35 @@ ExportResult TextureModdingExporter::Export(std::ostream&write, std::shared_ptr< case TextureType::Palette8bpp: case TextureType::Palette4bpp: { if (node["tlut_symbol"]) { - auto tlut = GetSafeNode<std::string>(node,"tlut_symbol"); + auto tlut = GetSafeNode<std::string>(node, "tlut_symbol"); auto palette = Companion::Instance->GetParseDataBySymbol(tlut); if (palette.has_value()) { auto palTexture = std::static_pointer_cast<TextureData>(palette.value().data.value()); - convert_raw_to_ci8(&raw, &size, texture->mBuffer.data(), (uint8_t *)palTexture->mBuffer.data(), 0, texture->mWidth, texture->mHeight, texture->mFormat.depth, palTexture->mFormat.depth); + convert_raw_to_ci8(&raw, &size, texture->mBuffer.data(), (uint8_t*)palTexture->mBuffer.data(), 0, + texture->mWidth, texture->mHeight, texture->mFormat.depth, + palTexture->mFormat.depth); } else { auto symbol = GetSafeNode<std::string>(node, "symbol"); - throw std::runtime_error("Could not convert ci8 '"+symbol+"' the tlut symbol name is probably wrong for tlut_symbol node"); + throw std::runtime_error("Could not convert ci8 '" + symbol + + "' the tlut symbol name is probably wrong for tlut_symbol node"); } break; } if (node["tlut"]) { - auto tlut = GetSafeNode<uint32_t>(node,"tlut"); + auto tlut = GetSafeNode<uint32_t>(node, "tlut"); auto palette = Companion::Instance->GetParseDataByAddr(tlut); if (palette.has_value()) { auto palTexture = std::static_pointer_cast<TextureData>(palette.value().data.value()); - convert_raw_to_ci8(&raw, &size, texture->mBuffer.data(), (uint8_t *)palTexture->mBuffer.data(), 0, texture->mWidth, texture->mHeight, texture->mFormat.depth, palTexture->mFormat.depth); + convert_raw_to_ci8(&raw, &size, texture->mBuffer.data(), (uint8_t*)palTexture->mBuffer.data(), 0, + texture->mWidth, texture->mHeight, texture->mFormat.depth, + palTexture->mFormat.depth); } else { auto symbol = GetSafeNode<std::string>(node, "symbol"); - throw std::runtime_error("Could not convert ci8 '"+symbol+"' the address is probably wrong for tlut address node"); + throw std::runtime_error("Could not convert ci8 '" + symbol + + "' the address is probably wrong for tlut address node"); } break; } @@ -255,7 +269,7 @@ ExportResult TextureModdingExporter::Export(std::ostream&write, std::shared_ptr< case TextureType::Grayscale8bpp: case TextureType::Grayscale4bpp: { ia* imgi = raw2i(texture->mBuffer.data(), texture->mWidth, texture->mHeight, format.depth); - if(ia2png(&raw, &size, imgi, texture->mWidth, texture->mHeight)) { + if (ia2png(&raw, &size, imgi, texture->mWidth, texture->mHeight)) { throw std::runtime_error("Failed to convert texture to PNG"); } break; @@ -269,7 +283,6 @@ ExportResult TextureModdingExporter::Export(std::ostream&write, std::shared_ptr< return std::nullopt; } - std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { auto offset = GetSafeNode<uint32_t>(node, "offset"); auto format = GetSafeNode<std::string>(node, "format"); @@ -283,17 +296,18 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse(std::vector<ui if (format.empty()) { SPDLOG_ERROR("Texture entry at {:X} in yaml missing format node\n\ Please add one of the following formats\n\ - rgba16, rgba32, ia16, ia8, ia4, i8, i4, ci8, ci4, 1bpp, tlut", offset); + rgba16, rgba32, ia16, ia8, ia4, i8, i4, ci8, ci4, 1bpp, tlut", + offset); return std::nullopt; } - if(!Torch::contains(sTextureFormats, format)) { + if (!Torch::contains(sTextureFormats, format)) { return std::nullopt; } TextureFormat fmt = sTextureFormats.at(format); - if(fmt.type == TextureType::TLUT){ + if (fmt.type == TextureType::TLUT) { width = GetSafeNode<uint32_t>(node, "colors"); height = 1; } else { @@ -301,7 +315,7 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse(std::vector<ui height = GetSafeNode<uint32_t>(node, "height"); } - if((format == "CI4" || format == "CI8") && node["tlut"] && node["colors"]) { + if ((format == "CI4" || format == "CI8") && node["tlut"] && node["colors"]) { YAML::Node tlutNode; const auto tlutOffset = GetSafeNode<uint32_t>(node, "tlut"); const auto tlutSymbol = GetSafeNode(node, "tlut_symbol", symbol + "_tlut"); @@ -313,23 +327,24 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse(std::vector<ui tlutNode["offset"] = tlutOffset; tlutNode["colors"] = GetSafeNode<uint32_t>(node, "colors"); node["tlut"] = tlutOffset; - if(node["tlut_ctype"]) { + if (node["tlut_ctype"]) { tlutNode["ctype"] = GetSafeNode<std::string>(node, "tlut_ctype"); } Companion::Instance->AddAsset(tlutNode); } - size = GetSafeNode<uint32_t>(node, "size", TextureUtils::CalculateTextureSize(sTextureFormats.at(format).type, width, height)); + size = GetSafeNode<uint32_t>(node, "size", + TextureUtils::CalculateTextureSize(sTextureFormats.at(format).type, width, height)); auto [_, segment] = Decompressor::AutoDecode(node, buffer, size); std::vector<uint8_t> result; - if(fmt.type == TextureType::GrayscaleAlpha1bpp){ + if (fmt.type == TextureType::GrayscaleAlpha1bpp) { result = TextureUtils::alloc_ia8_text_from_i1(reinterpret_cast<uint16_t*>(segment.data), 8, 16); } else { result = std::vector(segment.data, segment.data + segment.size); } SPDLOG_INFO("Texture: {}", format); - if(fmt.type == TextureType::TLUT){ + if (fmt.type == TextureType::TLUT) { SPDLOG_INFO("Colors: {}", width); } else { SPDLOG_INFO("Width: {}", width); @@ -338,18 +353,19 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse(std::vector<ui SPDLOG_INFO("Size: {}", size); SPDLOG_INFO("Offset: 0x{:X}", offset); - if(result.size() == 0){ + if (result.size() == 0) { return std::nullopt; } - if(result.size() == 0){ + if (result.size() == 0) { return std::nullopt; } return std::make_shared<TextureData>(fmt, width, height, result); } -std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto format = GetSafeNode<std::string>(node, "format"); int width; int height; @@ -359,16 +375,17 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::v if (format.empty()) { SPDLOG_ERROR("Texture entry at {:X} in yaml missing format node\n\ Please add one of the following formats\n\ - rgba16, rgba32, ia16, ia8, ia4, i8, i4, ci8, ci4, 1bpp, tlut", offset); + rgba16, rgba32, ia16, ia8, ia4, i8, i4, ci8, ci4, 1bpp, tlut", + offset); return std::nullopt; } - if(!Torch::contains(sTextureFormats, format)) { + if (!Torch::contains(sTextureFormats, format)) { return std::nullopt; } TextureFormat fmt = sTextureFormats.at(format); - if(fmt.type == TextureType::TLUT){ + if (fmt.type == TextureType::TLUT) { width = GetSafeNode<uint32_t>(node, "colors"); height = 1; } else { @@ -384,7 +401,7 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::v const auto imgr = png2rgba(buffer.data(), buffer.size(), &width, &height); size = width * height * fmt.depth / 8; raw = new uint8_t[size]; - if(rgba2raw(raw, imgr, width, height, fmt.depth) <= 0){ + if (rgba2raw(raw, imgr, width, height, fmt.depth) <= 0) { throw std::runtime_error("Failed to convert PNG to texture"); } break; @@ -396,7 +413,7 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::v const auto imgia = png2ia(buffer.data(), buffer.size(), &width, &height); size = width * height * fmt.depth / 8; raw = new uint8_t[size]; - if(ia2raw(raw, imgia, width, height, fmt.depth) <= 0){ + if (ia2raw(raw, imgia, width, height, fmt.depth) <= 0) { throw std::runtime_error("Failed to convert PNG to texture"); } break; @@ -417,7 +434,8 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::v // if (palettePtr) { // auto imgi = png2rgba(buffer.data(), buffer.size(), &width, &height); - // auto pal = png2rgba(palettePtr->mBuffer.data(), (palettePtr->mWidth * palettePtr->mWidth * palettePtr->mFormat.depth * 2), &width, &height); + // auto pal = png2rgba(palettePtr->mBuffer.data(), (palettePtr->mWidth * palettePtr->mWidth * + // palettePtr->mFormat.depth * 2), &width, &height); // size = width * height * fmt.depth / 8; // raw = new uint8_t[size]; @@ -436,7 +454,7 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::v const auto imgi = png2ia(buffer.data(), buffer.size(), &width, &height); size = width * height * fmt.depth / 8; raw = new uint8_t[size]; - if(i2raw(raw, imgi, width, height, fmt.depth) <= 0){ + if (i2raw(raw, imgi, width, height, fmt.depth) <= 0) { throw std::runtime_error("Failed to convert PNG to texture"); } break; @@ -450,7 +468,7 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::v auto result = std::vector(raw, raw + size); SPDLOG_INFO("Texture: {}", format); - if(fmt.type == TextureType::TLUT){ + if (fmt.type == TextureType::TLUT) { SPDLOG_INFO("Colors: {}", width); } else { SPDLOG_INFO("Width: {}", width); @@ -459,7 +477,7 @@ std::optional<std::shared_ptr<IParsedData>> TextureFactory::parse_modding(std::v SPDLOG_INFO("Size: {}", size); SPDLOG_INFO("Offset: 0x{:X}", offset); - if(result.size() == 0){ + if (result.size() == 0) { return std::nullopt; } diff --git a/src/factories/Vec3fFactory.cpp b/src/factories/Vec3fFactory.cpp index c101ca4..b2c650a 100644 --- a/src/factories/Vec3fFactory.cpp +++ b/src/factories/Vec3fFactory.cpp @@ -7,19 +7,20 @@ #define FORMAT_FLOAT(x, w, p) std::dec << std::setfill(' ') << std::fixed << std::setprecision(p) << std::setw(w) << x -Vec3fData::Vec3fData(std::vector<Vec3f> vecs): mVecs(vecs) { +Vec3fData::Vec3fData(std::vector<Vec3f> vecs) : mVecs(vecs) { mMaxPrec = 1; mMaxWidth = 3; - for(Vec3f v : vecs) { + for (Vec3f v : vecs) { mMaxPrec = std::max(mMaxPrec, v.precision()); mMaxWidth = std::max(mMaxWidth, v.width()); } } -ExportResult Vec3fHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult Vec3fHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -28,12 +29,12 @@ ExportResult Vec3fHeaderExporter::Export(std::ostream &write, std::shared_ptr<IP return std::nullopt; } - int GetPrecision(Vec3f v) { return std::max(std::max(GetPrecision(v.x), GetPrecision(v.y)), GetPrecision(v.z)); } -ExportResult Vec3fCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult Vec3fCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto vecData = std::static_pointer_cast<Vec3fData>(raw); @@ -42,8 +43,8 @@ ExportResult Vec3fCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar write << "Vec3f " << symbol << "[] = {"; int cols = 120 / (3 * vecData->mMaxWidth + 8); - for(Vec3f v : vecData->mVecs) { - if((i++ % cols) == 0) { + for (Vec3f v : vecData->mVecs) { + if ((i++ % cols) == 0) { write << "\n" << fourSpaceTab; } write << FORMAT_FLOAT(v, vecData->mMaxWidth, vecData->mMaxPrec) << ", "; @@ -58,14 +59,15 @@ ExportResult Vec3fCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar return offset + vecData->mVecs.size() * sizeof(Vec3f); } -ExportResult Vec3fBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult Vec3fBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto vecData = std::static_pointer_cast<Vec3fData>(raw); WriteHeader(writer, Torch::ResourceType::Vec3f, 0); - writer.Write((uint32_t) vecData->mVecs.size()); + writer.Write((uint32_t)vecData->mVecs.size()); - for(Vec3f v : vecData->mVecs) { + for (Vec3f v : vecData->mVecs) { auto [x, y, z] = v; writer.Write(x); writer.Write(y); @@ -83,7 +85,7 @@ std::optional<std::shared_ptr<IParsedData>> Vec3fFactory::parse(std::vector<uint LUS::BinaryReader reader(segment.data, segment.size); reader.SetEndianness(Torch::Endianness::Big); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { auto vx = reader.ReadFloat(); auto vy = reader.ReadFloat(); auto vz = reader.ReadFloat(); diff --git a/src/factories/Vec3sFactory.cpp b/src/factories/Vec3sFactory.cpp index c868363..11fa8fb 100644 --- a/src/factories/Vec3sFactory.cpp +++ b/src/factories/Vec3sFactory.cpp @@ -7,17 +7,18 @@ #define FORMAT_INT(x, w) std::dec << std::setfill(' ') << std::setw(w) << x -Vec3sData::Vec3sData(std::vector<Vec3s> vecs): mVecs(vecs) { +Vec3sData::Vec3sData(std::vector<Vec3s> vecs) : mVecs(vecs) { mMaxWidth = 3; - for(Vec3s v : vecs) { + for (Vec3s v : vecs) { mMaxWidth = std::max(mMaxWidth, v.width()); } } -ExportResult Vec3sHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult Vec3sHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -26,12 +27,12 @@ ExportResult Vec3sHeaderExporter::Export(std::ostream &write, std::shared_ptr<IP return std::nullopt; } - int GetPrecision(Vec3s v) { return std::max(std::max(GetPrecision(v.x), GetPrecision(v.y)), GetPrecision(v.z)); } -ExportResult Vec3sCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult Vec3sCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto vecData = std::static_pointer_cast<Vec3sData>(raw); @@ -40,8 +41,8 @@ ExportResult Vec3sCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar write << "Vec3s " << symbol << "[] = {"; int cols = 120 / (3 * vecData->mMaxWidth + 8); - for(Vec3s v : vecData->mVecs) { - if((i++ % cols) == 0) { + for (Vec3s v : vecData->mVecs) { + if ((i++ % cols) == 0) { write << "\n" << fourSpaceTab; } write << FORMAT_INT(v, vecData->mMaxWidth) << ", "; @@ -56,14 +57,15 @@ ExportResult Vec3sCodeExporter::Export(std::ostream &write, std::shared_ptr<IPar return offset + vecData->mVecs.size() * sizeof(Vec3s); } -ExportResult Vec3sBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult Vec3sBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto vecData = std::static_pointer_cast<Vec3sData>(raw); WriteHeader(writer, Torch::ResourceType::Vec3s, 0); - writer.Write((uint32_t) vecData->mVecs.size()); + writer.Write((uint32_t)vecData->mVecs.size()); - for(Vec3s v : vecData->mVecs) { + for (Vec3s v : vecData->mVecs) { auto [x, y, z] = v; writer.Write(x); writer.Write(y); @@ -81,7 +83,7 @@ std::optional<std::shared_ptr<IParsedData>> Vec3sFactory::parse(std::vector<uint LUS::BinaryReader reader(segment.data, segment.size); reader.SetEndianness(Torch::Endianness::Big); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { auto vx = reader.ReadInt16(); auto vy = reader.ReadInt16(); auto vz = reader.ReadInt16(); diff --git a/src/factories/ViewportFactory.cpp b/src/factories/ViewportFactory.cpp index beed8b8..db99222 100644 --- a/src/factories/ViewportFactory.cpp +++ b/src/factories/ViewportFactory.cpp @@ -4,10 +4,11 @@ #include "spdlog/spdlog.h" #include "Companion.h" -ExportResult ViewportHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult ViewportHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -17,7 +18,8 @@ ExportResult ViewportHeaderExporter::Export(std::ostream &write, std::shared_ptr return std::nullopt; } -ExportResult ViewportCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult ViewportCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto viewport = std::static_pointer_cast<VpData>(raw); @@ -47,7 +49,8 @@ ExportResult ViewportCodeExporter::Export(std::ostream &write, std::shared_ptr<I return offset + sizeof(VpRaw); } -ExportResult ViewportBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult ViewportBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto viewport = std::static_pointer_cast<VpData>(raw); diff --git a/src/factories/VtxFactory.cpp b/src/factories/VtxFactory.cpp index b0bd9b3..de9395a 100644 --- a/src/factories/VtxFactory.cpp +++ b/src/factories/VtxFactory.cpp @@ -7,23 +7,24 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) std::dec << std::setfill(' ') << std::setw(3) << c -ExportResult VtxHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult VtxHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto vtx = std::static_pointer_cast<VtxData>(raw)->mVtxs; const auto offset = GetSafeNode<uint32_t>(node, "offset"); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); // We will ignore the overriden index_size for now... - if(start != offset){ + if (start != offset) { return std::nullopt; } @@ -35,17 +36,17 @@ ExportResult VtxHeaderExporter::Export(std::ostream &write, std::shared_ptr<IPar return std::nullopt; } -ExportResult VtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult VtxCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto vtx = std::static_pointer_cast<VtxData>(raw)->mVtxs; const auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); - - if(start == offset){ + if (start == offset) { write << "Vtx " << name << "[][" << vtx.size() << "] = {\n"; } @@ -63,21 +64,23 @@ ExportResult VtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParse auto tc1 = v.tc[0]; auto tc2 = v.tc[1]; - auto c1 = (uint16_t) v.cn[0]; - auto c2 = (uint16_t) v.cn[1]; - auto c3 = (uint16_t) v.cn[2]; - auto c4 = (uint16_t) v.cn[3]; + auto c1 = (uint16_t)v.cn[0]; + auto c2 = (uint16_t)v.cn[1]; + auto c3 = (uint16_t)v.cn[2]; + auto c4 = (uint16_t)v.cn[3]; - if(i <= vtx.size() - 1) { + if (i <= vtx.size() - 1) { write << "\n" << fourSpaceTab; } // {{{ x, y, z }, f, { tc1, tc2 }, { c1, c2, c3, c4 }}} - write << fourSpaceTab << "{{{" << NUM(x) << ", " << NUM(y) << ", " << NUM(z) << "}, " << flag << ", {" << NUM(tc1) << ", " << NUM(tc2) << "}, {" << COL(c1) << ", " << COL(c2) << ", " << COL(c3) << ", " << COL(c4) << "}}},"; + write << fourSpaceTab << "{{{" << NUM(x) << ", " << NUM(y) << ", " << NUM(z) << "}, " << flag << ", {" + << NUM(tc1) << ", " << NUM(tc2) << "}, {" << COL(c1) << ", " << COL(c2) << ", " << COL(c3) << ", " + << COL(c4) << "}}},"; } write << "\n" << fourSpaceTab << "},\n"; - if(end == offset){ + if (end == offset) { write << "};\n\n"; } } else { @@ -96,17 +99,18 @@ ExportResult VtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParse auto tc1 = v.tc[0]; auto tc2 = v.tc[1]; - auto c1 = (uint16_t) v.cn[0]; - auto c2 = (uint16_t) v.cn[1]; - auto c3 = (uint16_t) v.cn[2]; - auto c4 = (uint16_t) v.cn[3]; + auto c1 = (uint16_t)v.cn[0]; + auto c2 = (uint16_t)v.cn[1]; + auto c3 = (uint16_t)v.cn[2]; + auto c4 = (uint16_t)v.cn[3]; - if(i <= vtx.size() - 1) { + if (i <= vtx.size() - 1) { write << fourSpaceTab; } // {{{ x, y, z }, f, { tc1, tc2 }, { c1, c2, c3, c4 }}} - write << "{{{" << NUM(x) << ", " << NUM(y) << ", " << NUM(z) << "}, " << flag << ", {" << NUM(tc1) << ", " << NUM(tc2) << "}, {" << COL(c1) << ", " << COL(c2) << ", " << COL(c3) << ", " << COL(c4) << "}}},\n"; + write << "{{{" << NUM(x) << ", " << NUM(y) << ", " << NUM(z) << "}, " << flag << ", {" << NUM(tc1) << ", " + << NUM(tc2) << "}, {" << COL(c1) << ", " << COL(c2) << ", " << COL(c3) << ", " << COL(c4) << "}}},\n"; } write << "};\n"; @@ -121,21 +125,22 @@ ExportResult VtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParse return offset + vtx.size() * sizeof(VtxRaw); } -ExportResult VtxBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult VtxBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto vtx = std::static_pointer_cast<VtxData>(raw); auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::Vertex, 0); - writer.Write((uint32_t) vtx->mVtxs.size()); - for(auto v : vtx->mVtxs) { - if(false && Companion::Instance->GetConfig().gbi.useFloats){ - writer.Write((float) v.ob[0]); - writer.Write((float) v.ob[1]); - writer.Write((float) v.ob[2]); + writer.Write((uint32_t)vtx->mVtxs.size()); + for (auto v : vtx->mVtxs) { + if (false && Companion::Instance->GetConfig().gbi.useFloats) { + writer.Write((float)v.ob[0]); + writer.Write((float)v.ob[1]); + writer.Write((float)v.ob[2]); } else { - writer.Write((int16_t) v.ob[0]); - writer.Write((int16_t) v.ob[1]); - writer.Write((int16_t) v.ob[2]); + writer.Write((int16_t)v.ob[0]); + writer.Write((int16_t)v.ob[1]); + writer.Write((int16_t)v.ob[2]); } writer.Write(v.flag); writer.Write(v.tc[0]); @@ -159,7 +164,7 @@ std::optional<std::shared_ptr<IParsedData>> VtxFactory::parse(std::vector<uint8_ reader.SetEndianness(Torch::Endianness::Big); std::vector<VtxRaw> vertices; - for(size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { auto x = reader.ReadInt16(); auto y = reader.ReadInt16(); auto z = reader.ReadInt16(); @@ -171,9 +176,7 @@ std::optional<std::shared_ptr<IParsedData>> VtxFactory::parse(std::vector<uint8_ auto cn3 = reader.ReadUByte(); auto cn4 = reader.ReadUByte(); - vertices.push_back(VtxRaw({ - {x, y, z}, flag, {tc1, tc2}, {cn1, cn2, cn3, cn4} - })); + vertices.push_back(VtxRaw({ { x, y, z }, flag, { tc1, tc2 }, { cn1, cn2, cn3, cn4 } })); } return std::make_shared<VtxData>(vertices); diff --git a/src/factories/fzerox/CourseFactory.cpp b/src/factories/fzerox/CourseFactory.cpp index 5d22814..6331b82 100644 --- a/src/factories/fzerox/CourseFactory.cpp +++ b/src/factories/fzerox/CourseFactory.cpp @@ -23,9 +23,12 @@ uint32_t FZX::CourseData::CalculateChecksum(void) { trackSegmentInfo &= ~TRACK_FORM_MASK; trackSegmentInfo &= ~TRACK_FLAG_CONTINUOUS; - checksum += (int32_t) ((controlPointInfo.controlPoint.pos.x + ((1.1f + (0.7f * counter)) * controlPointInfo.controlPoint.pos.y)) + - ((2.2f + (1.2f * counter)) * controlPointInfo.controlPoint.pos.z * (4.4f + (0.9f * counter))) + - controlPointInfo.controlPoint.radiusLeft + ((5.5f + (0.8f * counter)) * controlPointInfo.controlPoint.radiusRight * 4.8f)) + + checksum += + (int32_t)((controlPointInfo.controlPoint.pos.x + + ((1.1f + (0.7f * counter)) * controlPointInfo.controlPoint.pos.y)) + + ((2.2f + (1.2f * counter)) * controlPointInfo.controlPoint.pos.z * (4.4f + (0.9f * counter))) + + controlPointInfo.controlPoint.radiusLeft + + ((5.5f + (0.8f * counter)) * controlPointInfo.controlPoint.radiusRight * 4.8f)) + trackSegmentInfo * (0xFE - counter) + controlPointInfo.bankAngle * (0x93DE - counter * 2); checksum += (controlPointInfo.pit * counter); checksum += (controlPointInfo.dash * (counter + 0x10)); @@ -39,14 +42,14 @@ uint32_t FZX::CourseData::CalculateChecksum(void) { counter++; } - return checksum; } -ExportResult FZX::CourseHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::CourseHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -56,7 +59,8 @@ ExportResult FZX::CourseHeaderExporter::Export(std::ostream &write, std::shared_ return std::nullopt; } -ExportResult FZX::CourseCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::CourseCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto course = std::static_pointer_cast<CourseData>(raw); @@ -73,7 +77,8 @@ ExportResult FZX::CourseCodeExporter::Export(std::ostream &write, std::shared_pt write << fourSpaceTab << (int32_t)controlPointCount << ", /* Control Point Count */\n"; write << fourSpaceTab << static_cast<Venue>(course->mVenue) << ", /* Venue */\n"; write << fourSpaceTab << static_cast<Skybox>(course->mSkybox) << ", /* Skybox */\n"; - write << fourSpaceTab << "0x" << std::hex << std::uppercase << course->CalculateChecksum() << std::dec << ", /* Checksum */\n"; + write << fourSpaceTab << "0x" << std::hex << std::uppercase << course->CalculateChecksum() << std::dec + << ", /* Checksum */\n"; write << fourSpaceTab << (int32_t)course->mFlag << ", /* Flag */\n"; write << fourSpaceTab << "{ "; @@ -82,14 +87,15 @@ ExportResult FZX::CourseCodeExporter::Export(std::ostream &write, std::shared_pt if (i != 0) { write << ", "; } - if (!(course->mFileName.at(i) >= '0' && course->mFileName.at(i) <= '9') && !(course->mFileName.at(i) >= 'A' && course->mFileName.at(i) <= 'Z') - && !(course->mFileName.at(i) >= 'a' && course->mFileName.at(i) <= 'z')) { + if (!(course->mFileName.at(i) >= '0' && course->mFileName.at(i) <= '9') && + !(course->mFileName.at(i) >= 'A' && course->mFileName.at(i) <= 'Z') && + !(course->mFileName.at(i) >= 'a' && course->mFileName.at(i) <= 'z')) { write << "0x" << FORMAT_HEX((uint32_t)(uint8_t)course->mFileName.at(i), 2); continue; } write << "\'" << course->mFileName.at(i) << "\'"; } - + write << std::dec << " }, /* File Name */\n"; write << fourSpaceTab << (int32_t)course->mBgm << ",\n"; @@ -100,7 +106,8 @@ ExportResult FZX::CourseCodeExporter::Export(std::ostream &write, std::shared_pt write << fourSpaceTab << fourSpaceTab; if (i < controlPointCount) { const ControlPointInfo& controlPointInfo = course->mControlPointInfos.at(i); - Vec3f pos(controlPointInfo.controlPoint.pos.x, controlPointInfo.controlPoint.pos.y, controlPointInfo.controlPoint.pos.z); + Vec3f pos(controlPointInfo.controlPoint.pos.x, controlPointInfo.controlPoint.pos.y, + controlPointInfo.controlPoint.pos.z); write << "{ { " << FORMAT_FLOAT(pos, 6, 4) << " }, "; write << controlPointInfo.controlPoint.radiusLeft << ", "; write << controlPointInfo.controlPoint.radiusRight << ",\n"; @@ -432,7 +439,8 @@ ExportResult FZX::CourseCodeExporter::Export(std::ostream &write, std::shared_pt return offset + sizeof(CourseRawData); } -ExportResult FZX::CourseBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::CourseBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto course = std::static_pointer_cast<CourseData>(raw); int8_t controlPointCount = (int8_t)course->mControlPointInfos.size(); @@ -473,7 +481,8 @@ ExportResult FZX::CourseBinaryExporter::Export(std::ostream &write, std::shared_ return std::nullopt; } -ExportResult FZX::CourseModdingExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::CourseModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto course = std::static_pointer_cast<CourseData>(raw); const auto symbol = GetSafeNode(node, "symbol", entryName); @@ -498,8 +507,9 @@ ExportResult FZX::CourseModdingExporter::Export(std::ostream &write, std::shared out << YAML::Key << "Name"; out << YAML::Value << YAML::Flow << YAML::BeginSeq; for (size_t i = 0; i < course->mFileName.size(); i++) { - if (!(course->mFileName.at(i) >= '0' && course->mFileName.at(i) <= '9') && !(course->mFileName.at(i) >= 'A' && course->mFileName.at(i) <= 'Z') - && !(course->mFileName.at(i) >= 'a' && course->mFileName.at(i) <= 'z')) { + if (!(course->mFileName.at(i) >= '0' && course->mFileName.at(i) <= '9') && + !(course->mFileName.at(i) >= 'A' && course->mFileName.at(i) <= 'Z') && + !(course->mFileName.at(i) >= 'a' && course->mFileName.at(i) <= 'z')) { out << YAML::Hex << (uint32_t)(uint8_t)course->mFileName.at(i) << YAML::Dec; } else { out << course->mFileName.at(i); @@ -648,15 +658,16 @@ std::optional<std::shared_ptr<IParsedData>> FZX::CourseFactory::parse(std::vecto return std::make_shared<CourseData>(creatorId, venue, skybox, flag, fileName, bgm, controlPointInfos); } -std::optional<std::shared_ptr<IParsedData>> FZX::CourseFactory::parse_modding(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> FZX::CourseFactory::parse_modding(std::vector<uint8_t>& buffer, + YAML::Node& node) { YAML::Node assetNode; try { - std::string text((char*) buffer.data(), buffer.size()); + std::string text((char*)buffer.data(), buffer.size()); assetNode = YAML::Load(text.c_str()); } catch (YAML::ParserException& e) { SPDLOG_ERROR("Failed to parse message data: {}", e.what()); - SPDLOG_ERROR("{}", (char*) buffer.data()); + SPDLOG_ERROR("{}", (char*)buffer.data()); return std::nullopt; } diff --git a/src/factories/fzerox/EADAnimationFactory.cpp b/src/factories/fzerox/EADAnimationFactory.cpp index fff1545..9b2470e 100644 --- a/src/factories/fzerox/EADAnimationFactory.cpp +++ b/src/factories/fzerox/EADAnimationFactory.cpp @@ -7,10 +7,12 @@ #define FORMAT_HEX(x) std::hex << "0x" << std::uppercase << x << std::nouppercase << std::dec #define FZX_ANIMATION_SIZE 0x1C -ExportResult FZX::EADAnimationHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::EADAnimationHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -20,7 +22,8 @@ ExportResult FZX::EADAnimationHeaderExporter::Export(std::ostream &write, std::s return std::nullopt; } -ExportResult FZX::EADAnimationCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::EADAnimationCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto anim = std::static_pointer_cast<EADAnimationData>(raw); @@ -105,14 +108,17 @@ ExportResult FZX::EADAnimationCodeExporter::Export(std::ostream &write, std::sha return offset + FZX_ANIMATION_SIZE; } -ExportResult FZX::EADAnimationBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::EADAnimationBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto animation = std::static_pointer_cast<EADAnimationData>(raw); return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> FZX::EADAnimationFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> FZX::EADAnimationFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, segment.size); const auto symbol = GetSafeNode<std::string>(node, "symbol"); @@ -179,5 +185,6 @@ std::optional<std::shared_ptr<IParsedData>> FZX::EADAnimationFactory::parse(std: positionInfoNode["symbol"] = symbol + "PositionInfo"; Companion::Instance->AddAsset(positionInfoNode); - return std::make_shared<EADAnimationData>(frameCount, limbCount, scaleData, scaleInfo, rotationData, rotationInfo, positionData, positionInfo); + return std::make_shared<EADAnimationData>(frameCount, limbCount, scaleData, scaleInfo, rotationData, rotationInfo, + positionData, positionInfo); } diff --git a/src/factories/fzerox/EADLimbFactory.cpp b/src/factories/fzerox/EADLimbFactory.cpp index ba349b3..575fbdd 100644 --- a/src/factories/fzerox/EADLimbFactory.cpp +++ b/src/factories/fzerox/EADLimbFactory.cpp @@ -7,10 +7,11 @@ #define FORMAT_HEX(x) std::hex << "0x" << std::uppercase << x << std::nouppercase << std::dec #define FZX_LIMB_SIZE 0x36 -ExportResult FZX::EADLimbHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::EADLimbHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -20,7 +21,8 @@ ExportResult FZX::EADLimbHeaderExporter::Export(std::ostream &write, std::shared return std::nullopt; } -ExportResult FZX::EADLimbCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::EADLimbCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto limb = std::static_pointer_cast<EADLimbData>(raw); @@ -107,7 +109,8 @@ ExportResult FZX::EADLimbCodeExporter::Export(std::ostream &write, std::shared_p return offset + FZX_LIMB_SIZE; } -ExportResult FZX::EADLimbBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::EADLimbBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto limb = std::static_pointer_cast<EADLimbData>(raw); @@ -154,5 +157,6 @@ std::optional<std::shared_ptr<IParsedData>> FZX::EADLimbFactory::parse(std::vect } auto limbId = reader.ReadInt16(); - return std::make_shared<EADLimbData>(dl, scale, pos, rot, nextLimb, childLimb, associatedLimb, associatedLimbDL, limbId); + return std::make_shared<EADLimbData>(dl, scale, pos, rot, nextLimb, childLimb, associatedLimb, associatedLimbDL, + limbId); } diff --git a/src/factories/fzerox/GhostRecordFactory.cpp b/src/factories/fzerox/GhostRecordFactory.cpp index a702184..7a9eb4c 100644 --- a/src/factories/fzerox/GhostRecordFactory.cpp +++ b/src/factories/fzerox/GhostRecordFactory.cpp @@ -30,13 +30,13 @@ uint16_t FZX::GhostRecordData::CalculateRecordChecksum(void) { checksum += Save_CalculateChecksum(&mUnk10, sizeof(mUnk10)); checksum += Save_CalculateChecksum((void*)mTrackName.c_str(), mTrackName.length()); checksum += Save_CalculateChecksum(&mGhostMachineInfo, sizeof(mGhostMachineInfo)); - + return checksum; } uint16_t FZX::GhostRecordData::CalculateDataChecksum(void) { uint16_t checksum = 0; - + checksum += Save_CalculateChecksum(&mReplayEnd, sizeof(mReplayEnd)); checksum += Save_CalculateChecksum(&mReplaySize, sizeof(mReplaySize)); @@ -68,10 +68,12 @@ int32_t FZX::GhostRecordData::CalculateReplayChecksum(void) { return checksum; } -ExportResult FZX::GhostRecordHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::GhostRecordHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "Record[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -83,15 +85,17 @@ ExportResult FZX::GhostRecordHeaderExporter::Export(std::ostream &write, std::sh return std::nullopt; } -ExportResult FZX::GhostRecordCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::GhostRecordCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto record = std::static_pointer_cast<GhostRecordData>(raw); // HACK!! - // These checksums when read from disk do not line up to the data since the save of the data calculates the checksum with unsaved and unused buffer data, and therefore is uncalculable. - // The record checksum can occasionally not align with the value for some other unknown reason. - // When modding these values will be read in as 0 and calculated here + // These checksums when read from disk do not line up to the data since the save of the data calculates the checksum + // with unsaved and unused buffer data, and therefore is uncalculable. The record checksum can occasionally not + // align with the value for some other unknown reason. When modding these values will be read in as 0 and calculated + // here if (record->mReplayChecksum == 0) { record->mReplayChecksum = record->CalculateReplayChecksum(); } @@ -104,13 +108,16 @@ ExportResult FZX::GhostRecordCodeExporter::Export(std::ostream &write, std::shar write << "GhostRecord " << symbol << "Record = {\n"; - write << fourSpaceTab << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << record->mRecordChecksum << std::dec << ", /* Checksum */\n"; + write << fourSpaceTab << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) + << record->mRecordChecksum << std::dec << ", /* Checksum */\n"; write << fourSpaceTab << static_cast<GhostType>(record->mGhostType) << ",\n"; - write << fourSpaceTab << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(8) << record->mReplayChecksum << std::dec << ", /* Replay Checksum */\n"; + write << fourSpaceTab << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(8) + << record->mReplayChecksum << std::dec << ", /* Replay Checksum */\n"; - write << fourSpaceTab << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(8) << record->mCourseEncoding << std::dec << ", /* Course Encoding */\n"; + write << fourSpaceTab << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(8) + << record->mCourseEncoding << std::dec << ", /* Course Encoding */\n"; write << fourSpaceTab << record->mRaceTime << ", /* Race Time */ \n"; @@ -146,10 +153,10 @@ ExportResult FZX::GhostRecordCodeExporter::Export(std::ostream &write, std::shar write << "};\n\n"; - write << "GhostReplayInfo " << symbol << "ReplayInfo = {\n"; - write << fourSpaceTab << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << record->mDataChecksum << std::dec << ", /* Checksum */\n"; + write << fourSpaceTab << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) + << record->mDataChecksum << std::dec << ", /* Checksum */\n"; write << fourSpaceTab << "0,\n"; @@ -172,7 +179,6 @@ ExportResult FZX::GhostRecordCodeExporter::Export(std::ostream &write, std::shar write << "};\n\n"; - write << "s8 " << symbol << "Data[] = {\n"; write << fourSpaceTab; @@ -184,7 +190,8 @@ ExportResult FZX::GhostRecordCodeExporter::Export(std::ostream &write, std::shar if (replayData == -0x80) { write << ""; - replayData = (int16_t)(((uint32_t)(uint8_t)record->mReplayData.at(i + 1) << 8) | (uint8_t)record->mReplayData.at(i + 2)); + replayData = (int16_t)(((uint32_t)(uint8_t)record->mReplayData.at(i + 1) << 8) | + (uint8_t)record->mReplayData.at(i + 2)); write << "REPLAY_DATA_LARGE(" << replayData << ")"; i += 2; @@ -209,7 +216,9 @@ ExportResult FZX::GhostRecordCodeExporter::Export(std::ostream &write, std::shar return offset + 0x20 + 0x40 + ALIGN4(record->mReplayData.size()); } -ExportResult FZX::GhostRecordBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::GhostRecordBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto record = std::static_pointer_cast<GhostRecordData>(raw); @@ -258,7 +267,9 @@ ExportResult FZX::GhostRecordBinaryExporter::Export(std::ostream &write, std::sh return std::nullopt; } -ExportResult FZX::GhostRecordModdingExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::GhostRecordModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto record = std::static_pointer_cast<GhostRecordData>(raw); const auto symbol = GetSafeNode(node, "symbol", entryName); @@ -353,7 +364,8 @@ ExportResult FZX::GhostRecordModdingExporter::Export(std::ostream &write, std::s return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, segment.size); bool isDiskDrive = GetSafeNode<bool>(node, "disk_drive", false); @@ -366,12 +378,12 @@ std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse(std:: int32_t replayChecksum = reader.ReadInt32(); int32_t courseEncoding = reader.ReadInt32(); int32_t raceTime = reader.ReadInt32(); - + uint16_t unk_10 = reader.ReadInt16(); for (int32_t i = 0; i < 5; i++) { reader.ReadInt8(); } - + char trackNameBuffer[9]; for (int32_t i = 0; i < ARRAY_COUNT(trackNameBuffer); i++) { trackNameBuffer[i] = reader.ReadChar(); @@ -427,18 +439,21 @@ std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse(std:: replayData.push_back(reader.ReadInt8()); } - return std::make_shared<GhostRecordData>(recordChecksum, ghostType, replayChecksum, courseEncoding, raceTime, unk_10, trackName, ghostMachineInfo, dataChecksum, lapTimes, replayEnd, replaySize, replayData); + return std::make_shared<GhostRecordData>(recordChecksum, ghostType, replayChecksum, courseEncoding, raceTime, + unk_10, trackName, ghostMachineInfo, dataChecksum, lapTimes, replayEnd, + replaySize, replayData); } -std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse_modding(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse_modding(std::vector<uint8_t>& buffer, + YAML::Node& node) { YAML::Node assetNode; - + try { - std::string text((char*) buffer.data(), buffer.size()); + std::string text((char*)buffer.data(), buffer.size()); assetNode = YAML::Load(text.c_str()); } catch (YAML::ParserException& e) { SPDLOG_ERROR("Failed to parse message data: {}", e.what()); - SPDLOG_ERROR("{}", (char*) buffer.data()); + SPDLOG_ERROR("{}", (char*)buffer.data()); return std::nullopt; } @@ -472,7 +487,7 @@ std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse_moddi ghostMachineInfo.cockpitR = info["GhostMachineInfo"]["CockpitR"].as<uint32_t>(); ghostMachineInfo.cockpitG = info["GhostMachineInfo"]["CockpitG"].as<uint32_t>(); ghostMachineInfo.cockpitB = info["GhostMachineInfo"]["CockpitB"].as<uint32_t>(); - + auto lapTimesInfo = info["LapTimes"]; std::vector<int32_t> lapTimes; @@ -480,7 +495,6 @@ std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse_moddi lapTimes.push_back((*it).as<int32_t>()); } - if (lapTimes.size() < 3) { throw std::runtime_error("Invalid number of lap times in Ghost " + node["symbol"].as<std::string>()); } @@ -498,6 +512,7 @@ std::optional<std::shared_ptr<IParsedData>> FZX::GhostRecordFactory::parse_moddi if (replayData.size() != replaySize) { throw std::runtime_error("Invalid replay size in Ghost " + node["symbol"].as<std::string>()); } - - return std::make_shared<GhostRecordData>(0, ghostType, 0, courseEncoding, raceTime, unk_10, trackName, ghostMachineInfo, 0, lapTimes, replayEnd, replaySize, replayData); + + return std::make_shared<GhostRecordData>(0, ghostType, 0, courseEncoding, raceTime, unk_10, trackName, + ghostMachineInfo, 0, lapTimes, replayEnd, replaySize, replayData); } diff --git a/src/factories/fzerox/SequenceFactory.cpp b/src/factories/fzerox/SequenceFactory.cpp index 74d2a6a..5a3215d 100644 --- a/src/factories/fzerox/SequenceFactory.cpp +++ b/src/factories/fzerox/SequenceFactory.cpp @@ -8,301 +8,306 @@ // control flow commands #define ASEQ_OP_CONTROL_FLOW_FIRST 0xF2 -#define ASEQ_OP_RBLTZ 0xF2 -#define ASEQ_OP_RBEQZ 0xF3 -#define ASEQ_OP_RJUMP 0xF4 -#define ASEQ_OP_BGEZ 0xF5 -#define ASEQ_OP_BREAK 0xF6 +#define ASEQ_OP_RBLTZ 0xF2 +#define ASEQ_OP_RBEQZ 0xF3 +#define ASEQ_OP_RJUMP 0xF4 +#define ASEQ_OP_BGEZ 0xF5 +#define ASEQ_OP_BREAK 0xF6 #define ASEQ_OP_LOOPEND 0xF7 -#define ASEQ_OP_LOOP 0xF8 -#define ASEQ_OP_BLTZ 0xF9 -#define ASEQ_OP_BEQZ 0xFA -#define ASEQ_OP_JUMP 0xFB -#define ASEQ_OP_CALL 0xFC -#define ASEQ_OP_DELAY 0xFD -#define ASEQ_OP_DELAY1 0xFE -#define ASEQ_OP_END 0xFF +#define ASEQ_OP_LOOP 0xF8 +#define ASEQ_OP_BLTZ 0xF9 +#define ASEQ_OP_BEQZ 0xFA +#define ASEQ_OP_JUMP 0xFB +#define ASEQ_OP_CALL 0xFC +#define ASEQ_OP_DELAY 0xFD +#define ASEQ_OP_DELAY1 0xFE +#define ASEQ_OP_END 0xFF // sequence commands -#define ASEQ_OP_SEQ_TESTCHAN 0x00 // low nibble used as argument -#define ASEQ_OP_SEQ_STOPCHAN 0x40 // low nibble used as argument -#define ASEQ_OP_SEQ_SUBIO 0x50 // low nibble used as argument -#define ASEQ_OP_SEQ_LDRES 0x60 // low nibble used as argument -#define ASEQ_OP_SEQ_STIO 0x70 // low nibble used as argument -#define ASEQ_OP_SEQ_LDIO 0x80 // low nibble used as argument -#define ASEQ_OP_SEQ_LDCHAN 0x90 // low nibble used as argument -#define ASEQ_OP_SEQ_RLDCHAN 0xA0 // low nibble used as argument -#define ASEQ_OP_SEQ_LDSEQ 0xB0 // low nibble used as argument -#define ASEQ_OP_SEQ_RUNSEQ 0xC4 -#define ASEQ_OP_SEQ_SCRIPTCTR 0xC5 -#define ASEQ_OP_SEQ_STOP 0xC6 -#define ASEQ_OP_SEQ_STSEQ 0xC7 -#define ASEQ_OP_SEQ_SUB 0xC8 -#define ASEQ_OP_SEQ_AND 0xC9 -#define ASEQ_OP_SEQ_LDI 0xCC -#define ASEQ_OP_SEQ_DYNCALL 0xCD -#define ASEQ_OP_SEQ_RAND 0xCE -#define ASEQ_OP_SEQ_NOTEALLOC 0xD0 -#define ASEQ_OP_SEQ_LDSHORTGATEARR 0xD1 -#define ASEQ_OP_SEQ_LDSHORTVELARR 0xD2 -#define ASEQ_OP_SEQ_MUTEBHV 0xD3 -#define ASEQ_OP_SEQ_MUTE 0xD4 -#define ASEQ_OP_SEQ_MUTESCALE 0xD5 -#define ASEQ_OP_SEQ_FREECHAN 0xD6 -#define ASEQ_OP_SEQ_INITCHAN 0xD7 -#define ASEQ_OP_SEQ_VOLSCALE 0xD9 -#define ASEQ_OP_SEQ_VOLMODE 0xDA -#define ASEQ_OP_SEQ_VOL 0xDB -#define ASEQ_OP_SEQ_TEMPOCHG 0xDC -#define ASEQ_OP_SEQ_TEMPO 0xDD -#define ASEQ_OP_SEQ_RTRANSPOSE 0xDE -#define ASEQ_OP_SEQ_TRANSPOSE 0xDF -#define ASEQ_OP_SEQ_EF 0xEF -#define ASEQ_OP_SEQ_FREENOTELIST 0xF0 -#define ASEQ_OP_SEQ_ALLOCNOTELIST 0xF1 +#define ASEQ_OP_SEQ_TESTCHAN 0x00 // low nibble used as argument +#define ASEQ_OP_SEQ_STOPCHAN 0x40 // low nibble used as argument +#define ASEQ_OP_SEQ_SUBIO 0x50 // low nibble used as argument +#define ASEQ_OP_SEQ_LDRES 0x60 // low nibble used as argument +#define ASEQ_OP_SEQ_STIO 0x70 // low nibble used as argument +#define ASEQ_OP_SEQ_LDIO 0x80 // low nibble used as argument +#define ASEQ_OP_SEQ_LDCHAN 0x90 // low nibble used as argument +#define ASEQ_OP_SEQ_RLDCHAN 0xA0 // low nibble used as argument +#define ASEQ_OP_SEQ_LDSEQ 0xB0 // low nibble used as argument +#define ASEQ_OP_SEQ_RUNSEQ 0xC4 +#define ASEQ_OP_SEQ_SCRIPTCTR 0xC5 +#define ASEQ_OP_SEQ_STOP 0xC6 +#define ASEQ_OP_SEQ_STSEQ 0xC7 +#define ASEQ_OP_SEQ_SUB 0xC8 +#define ASEQ_OP_SEQ_AND 0xC9 +#define ASEQ_OP_SEQ_LDI 0xCC +#define ASEQ_OP_SEQ_DYNCALL 0xCD +#define ASEQ_OP_SEQ_RAND 0xCE +#define ASEQ_OP_SEQ_NOTEALLOC 0xD0 +#define ASEQ_OP_SEQ_LDSHORTGATEARR 0xD1 +#define ASEQ_OP_SEQ_LDSHORTVELARR 0xD2 +#define ASEQ_OP_SEQ_MUTEBHV 0xD3 +#define ASEQ_OP_SEQ_MUTE 0xD4 +#define ASEQ_OP_SEQ_MUTESCALE 0xD5 +#define ASEQ_OP_SEQ_FREECHAN 0xD6 +#define ASEQ_OP_SEQ_INITCHAN 0xD7 +#define ASEQ_OP_SEQ_VOLSCALE 0xD9 +#define ASEQ_OP_SEQ_VOLMODE 0xDA +#define ASEQ_OP_SEQ_VOL 0xDB +#define ASEQ_OP_SEQ_TEMPOCHG 0xDC +#define ASEQ_OP_SEQ_TEMPO 0xDD +#define ASEQ_OP_SEQ_RTRANSPOSE 0xDE +#define ASEQ_OP_SEQ_TRANSPOSE 0xDF +#define ASEQ_OP_SEQ_EF 0xEF +#define ASEQ_OP_SEQ_FREENOTELIST 0xF0 +#define ASEQ_OP_SEQ_ALLOCNOTELIST 0xF1 // channel commands -#define ASEQ_OP_CHAN_CDELAY 0x00 // low nibble used as argument -#define ASEQ_OP_CHAN_LDSAMPLE 0x10 // low nibble used as argument -#define ASEQ_OP_CHAN_LDCHAN 0x20 // low nibble used as argument -#define ASEQ_OP_CHAN_STCIO 0x30 // low nibble used as argument -#define ASEQ_OP_CHAN_LDCIO 0x40 // low nibble used as argument -#define ASEQ_OP_CHAN_SUBIO 0x50 // low nibble used as argument -#define ASEQ_OP_CHAN_LDIO 0x60 // low nibble used as argument -#define ASEQ_OP_CHAN_STIO 0x70 // lower 3 bits used as argument -#define ASEQ_OP_CHAN_RLDLAYER 0x78 // lower 3 bits used as argument -#define ASEQ_OP_CHAN_TESTLAYER 0x80 // lower 3 bits used as argument -#define ASEQ_OP_CHAN_LDLAYER 0x88 // lower 3 bits used as argument -#define ASEQ_OP_CHAN_DELLAYER 0x90 // lower 3 bits used as argument -#define ASEQ_OP_CHAN_DYNLDLAYER 0x98 // lower 3 bits used as argument -#define ASEQ_OP_CHAN_LDFILTER 0xB0 -#define ASEQ_OP_CHAN_FREEFILTER 0xB1 -#define ASEQ_OP_CHAN_LDSEQTOPTR 0xB2 -#define ASEQ_OP_CHAN_FILTER 0xB3 -#define ASEQ_OP_CHAN_PTRTODYNTBL 0xB4 -#define ASEQ_OP_CHAN_DYNTBLTOPTR 0xB5 -#define ASEQ_OP_CHAN_DYNTBLV 0xB6 -#define ASEQ_OP_CHAN_RANDTOPTR 0xB7 -#define ASEQ_OP_CHAN_RAND 0xB8 -#define ASEQ_OP_CHAN_RANDVEL 0xB9 -#define ASEQ_OP_CHAN_RANDGATE 0xBA -#define ASEQ_OP_CHAN_COMBFILTER 0xBB -#define ASEQ_OP_CHAN_PTRADD 0xBC -#define ASEQ_OP_CHAN_SAMPLESTART 0xBD -#define ASEQ_OP_CHAN_INSTR 0xC1 -#define ASEQ_OP_CHAN_DYNTBL 0xC2 -#define ASEQ_OP_CHAN_SHORT 0xC3 -#define ASEQ_OP_CHAN_NOSHORT 0xC4 -#define ASEQ_OP_CHAN_DYNTBLLOOKUP 0xC5 -#define ASEQ_OP_CHAN_FONT 0xC6 -#define ASEQ_OP_CHAN_STSEQ 0xC7 -#define ASEQ_OP_CHAN_SUB 0xC8 -#define ASEQ_OP_CHAN_AND 0xC9 -#define ASEQ_OP_CHAN_MUTEBHV 0xCA -#define ASEQ_OP_CHAN_LDSEQ 0xCB -#define ASEQ_OP_CHAN_LDI 0xCC -#define ASEQ_OP_CHAN_STOPCHAN 0xCD -#define ASEQ_OP_CHAN_LDPTR 0xCE -#define ASEQ_OP_CHAN_STPTRTOSEQ 0xCF -#define ASEQ_OP_CHAN_EFFECTS 0xD0 -#define ASEQ_OP_CHAN_NOTEALLOC 0xD1 -#define ASEQ_OP_CHAN_SUSTAIN 0xD2 -#define ASEQ_OP_CHAN_BEND 0xD3 -#define ASEQ_OP_CHAN_REVERB 0xD4 -#define ASEQ_OP_CHAN_VIBFREQ 0xD7 -#define ASEQ_OP_CHAN_VIBDEPTH 0xD8 -#define ASEQ_OP_CHAN_RELEASERATE 0xD9 -#define ASEQ_OP_CHAN_ENV 0xDA -#define ASEQ_OP_CHAN_TRANSPOSE 0xDB -#define ASEQ_OP_CHAN_PANWEIGHT 0xDC -#define ASEQ_OP_CHAN_PAN 0xDD -#define ASEQ_OP_CHAN_FREQSCALE 0xDE -#define ASEQ_OP_CHAN_VOL 0xDF -#define ASEQ_OP_CHAN_VOLEXP 0xE0 -#define ASEQ_OP_CHAN_VIBFREQGRAD 0xE1 -#define ASEQ_OP_CHAN_VIBDEPTHGRAD 0xE2 -#define ASEQ_OP_CHAN_VIBDELAY 0xE3 -#define ASEQ_OP_CHAN_DYNCALL 0xE4 -#define ASEQ_OP_CHAN_REVERBIDX 0xE5 -#define ASEQ_OP_CHAN_SAMPLEBOOK 0xE6 -#define ASEQ_OP_CHAN_LDPARAMS 0xE7 -#define ASEQ_OP_CHAN_PARAMS 0xE8 -#define ASEQ_OP_CHAN_NOTEPRI 0xE9 -#define ASEQ_OP_CHAN_STOP 0xEA -#define ASEQ_OP_CHAN_FONTINSTR 0xEB -#define ASEQ_OP_CHAN_VIBRESET 0xEC -#define ASEQ_OP_CHAN_GAIN 0xED -#define ASEQ_OP_CHAN_BENDFINE 0xEE -#define ASEQ_OP_CHAN_EF 0xEF -#define ASEQ_OP_CHAN_FREENOTELIST 0xF0 -#define ASEQ_OP_CHAN_ALLOCNOTELIST 0xF1 +#define ASEQ_OP_CHAN_CDELAY 0x00 // low nibble used as argument +#define ASEQ_OP_CHAN_LDSAMPLE 0x10 // low nibble used as argument +#define ASEQ_OP_CHAN_LDCHAN 0x20 // low nibble used as argument +#define ASEQ_OP_CHAN_STCIO 0x30 // low nibble used as argument +#define ASEQ_OP_CHAN_LDCIO 0x40 // low nibble used as argument +#define ASEQ_OP_CHAN_SUBIO 0x50 // low nibble used as argument +#define ASEQ_OP_CHAN_LDIO 0x60 // low nibble used as argument +#define ASEQ_OP_CHAN_STIO 0x70 // lower 3 bits used as argument +#define ASEQ_OP_CHAN_RLDLAYER 0x78 // lower 3 bits used as argument +#define ASEQ_OP_CHAN_TESTLAYER 0x80 // lower 3 bits used as argument +#define ASEQ_OP_CHAN_LDLAYER 0x88 // lower 3 bits used as argument +#define ASEQ_OP_CHAN_DELLAYER 0x90 // lower 3 bits used as argument +#define ASEQ_OP_CHAN_DYNLDLAYER 0x98 // lower 3 bits used as argument +#define ASEQ_OP_CHAN_LDFILTER 0xB0 +#define ASEQ_OP_CHAN_FREEFILTER 0xB1 +#define ASEQ_OP_CHAN_LDSEQTOPTR 0xB2 +#define ASEQ_OP_CHAN_FILTER 0xB3 +#define ASEQ_OP_CHAN_PTRTODYNTBL 0xB4 +#define ASEQ_OP_CHAN_DYNTBLTOPTR 0xB5 +#define ASEQ_OP_CHAN_DYNTBLV 0xB6 +#define ASEQ_OP_CHAN_RANDTOPTR 0xB7 +#define ASEQ_OP_CHAN_RAND 0xB8 +#define ASEQ_OP_CHAN_RANDVEL 0xB9 +#define ASEQ_OP_CHAN_RANDGATE 0xBA +#define ASEQ_OP_CHAN_COMBFILTER 0xBB +#define ASEQ_OP_CHAN_PTRADD 0xBC +#define ASEQ_OP_CHAN_SAMPLESTART 0xBD +#define ASEQ_OP_CHAN_INSTR 0xC1 +#define ASEQ_OP_CHAN_DYNTBL 0xC2 +#define ASEQ_OP_CHAN_SHORT 0xC3 +#define ASEQ_OP_CHAN_NOSHORT 0xC4 +#define ASEQ_OP_CHAN_DYNTBLLOOKUP 0xC5 +#define ASEQ_OP_CHAN_FONT 0xC6 +#define ASEQ_OP_CHAN_STSEQ 0xC7 +#define ASEQ_OP_CHAN_SUB 0xC8 +#define ASEQ_OP_CHAN_AND 0xC9 +#define ASEQ_OP_CHAN_MUTEBHV 0xCA +#define ASEQ_OP_CHAN_LDSEQ 0xCB +#define ASEQ_OP_CHAN_LDI 0xCC +#define ASEQ_OP_CHAN_STOPCHAN 0xCD +#define ASEQ_OP_CHAN_LDPTR 0xCE +#define ASEQ_OP_CHAN_STPTRTOSEQ 0xCF +#define ASEQ_OP_CHAN_EFFECTS 0xD0 +#define ASEQ_OP_CHAN_NOTEALLOC 0xD1 +#define ASEQ_OP_CHAN_SUSTAIN 0xD2 +#define ASEQ_OP_CHAN_BEND 0xD3 +#define ASEQ_OP_CHAN_REVERB 0xD4 +#define ASEQ_OP_CHAN_VIBFREQ 0xD7 +#define ASEQ_OP_CHAN_VIBDEPTH 0xD8 +#define ASEQ_OP_CHAN_RELEASERATE 0xD9 +#define ASEQ_OP_CHAN_ENV 0xDA +#define ASEQ_OP_CHAN_TRANSPOSE 0xDB +#define ASEQ_OP_CHAN_PANWEIGHT 0xDC +#define ASEQ_OP_CHAN_PAN 0xDD +#define ASEQ_OP_CHAN_FREQSCALE 0xDE +#define ASEQ_OP_CHAN_VOL 0xDF +#define ASEQ_OP_CHAN_VOLEXP 0xE0 +#define ASEQ_OP_CHAN_VIBFREQGRAD 0xE1 +#define ASEQ_OP_CHAN_VIBDEPTHGRAD 0xE2 +#define ASEQ_OP_CHAN_VIBDELAY 0xE3 +#define ASEQ_OP_CHAN_DYNCALL 0xE4 +#define ASEQ_OP_CHAN_REVERBIDX 0xE5 +#define ASEQ_OP_CHAN_SAMPLEBOOK 0xE6 +#define ASEQ_OP_CHAN_LDPARAMS 0xE7 +#define ASEQ_OP_CHAN_PARAMS 0xE8 +#define ASEQ_OP_CHAN_NOTEPRI 0xE9 +#define ASEQ_OP_CHAN_STOP 0xEA +#define ASEQ_OP_CHAN_FONTINSTR 0xEB +#define ASEQ_OP_CHAN_VIBRESET 0xEC +#define ASEQ_OP_CHAN_GAIN 0xED +#define ASEQ_OP_CHAN_BENDFINE 0xEE +#define ASEQ_OP_CHAN_EF 0xEF +#define ASEQ_OP_CHAN_FREENOTELIST 0xF0 +#define ASEQ_OP_CHAN_ALLOCNOTELIST 0xF1 // layer commands -#define ASEQ_OP_LAYER_NOTEDVG 0x00 -#define ASEQ_OP_LAYER_NOTEDV 0x40 -#define ASEQ_OP_LAYER_NOTEVG 0x80 -#define ASEQ_OP_LAYER_LDELAY 0xC0 -#define ASEQ_OP_LAYER_SHORTVEL 0xC1 -#define ASEQ_OP_LAYER_TRANSPOSE 0xC2 -#define ASEQ_OP_LAYER_SHORTDELAY 0xC3 -#define ASEQ_OP_LAYER_LEGATO 0xC4 -#define ASEQ_OP_LAYER_NOLEGATO 0xC5 -#define ASEQ_OP_LAYER_INSTR 0xC6 -#define ASEQ_OP_LAYER_PORTAMENTO 0xC7 -#define ASEQ_OP_LAYER_NOPORTAMENTO 0xC8 -#define ASEQ_OP_LAYER_SHORTGATE 0xC9 -#define ASEQ_OP_LAYER_NOTEPAN 0xCA -#define ASEQ_OP_LAYER_ENV 0xCB -#define ASEQ_OP_LAYER_NODRUMPAN 0xCC -#define ASEQ_OP_LAYER_STEREO 0xCD -#define ASEQ_OP_LAYER_BENDFINE 0xCE -#define ASEQ_OP_LAYER_RELEASERATE 0xCF -#define ASEQ_OP_LAYER_LDSHORTVEL 0xD0 // low nibble used as an argument -#define ASEQ_OP_LAYER_LDSHORTGATE 0xE0 // low nibble used as an argument +#define ASEQ_OP_LAYER_NOTEDVG 0x00 +#define ASEQ_OP_LAYER_NOTEDV 0x40 +#define ASEQ_OP_LAYER_NOTEVG 0x80 +#define ASEQ_OP_LAYER_LDELAY 0xC0 +#define ASEQ_OP_LAYER_SHORTVEL 0xC1 +#define ASEQ_OP_LAYER_TRANSPOSE 0xC2 +#define ASEQ_OP_LAYER_SHORTDELAY 0xC3 +#define ASEQ_OP_LAYER_LEGATO 0xC4 +#define ASEQ_OP_LAYER_NOLEGATO 0xC5 +#define ASEQ_OP_LAYER_INSTR 0xC6 +#define ASEQ_OP_LAYER_PORTAMENTO 0xC7 +#define ASEQ_OP_LAYER_NOPORTAMENTO 0xC8 +#define ASEQ_OP_LAYER_SHORTGATE 0xC9 +#define ASEQ_OP_LAYER_NOTEPAN 0xCA +#define ASEQ_OP_LAYER_ENV 0xCB +#define ASEQ_OP_LAYER_NODRUMPAN 0xCC +#define ASEQ_OP_LAYER_STEREO 0xCD +#define ASEQ_OP_LAYER_BENDFINE 0xCE +#define ASEQ_OP_LAYER_RELEASERATE 0xCF +#define ASEQ_OP_LAYER_LDSHORTVEL 0xD0 // low nibble used as an argument +#define ASEQ_OP_LAYER_LDSHORTGATE 0xE0 // low nibble used as an argument -#define PITCH_A0 0 -#define PITCH_BF0 1 -#define PITCH_B0 2 -#define PITCH_C1 3 -#define PITCH_DF1 4 -#define PITCH_D1 5 -#define PITCH_EF1 6 -#define PITCH_E1 7 -#define PITCH_F1 8 -#define PITCH_GF1 9 -#define PITCH_G1 10 -#define PITCH_AF1 11 -#define PITCH_A1 12 -#define PITCH_BF1 13 -#define PITCH_B1 14 -#define PITCH_C2 15 -#define PITCH_DF2 16 -#define PITCH_D2 17 -#define PITCH_EF2 18 -#define PITCH_E2 19 -#define PITCH_F2 20 -#define PITCH_GF2 21 -#define PITCH_G2 22 -#define PITCH_AF2 23 -#define PITCH_A2 24 -#define PITCH_BF2 25 -#define PITCH_B2 26 -#define PITCH_C3 27 -#define PITCH_DF3 28 -#define PITCH_D3 29 -#define PITCH_EF3 30 -#define PITCH_E3 31 -#define PITCH_F3 32 -#define PITCH_GF3 33 -#define PITCH_G3 34 -#define PITCH_AF3 35 -#define PITCH_A3 36 -#define PITCH_BF3 37 -#define PITCH_B3 38 -#define PITCH_C4 39 -#define PITCH_DF4 40 -#define PITCH_D4 41 -#define PITCH_EF4 42 -#define PITCH_E4 43 -#define PITCH_F4 44 -#define PITCH_GF4 45 -#define PITCH_G4 46 -#define PITCH_AF4 47 -#define PITCH_A4 48 -#define PITCH_BF4 49 -#define PITCH_B4 50 -#define PITCH_C5 51 -#define PITCH_DF5 52 -#define PITCH_D5 53 -#define PITCH_EF5 54 -#define PITCH_E5 55 -#define PITCH_F5 56 -#define PITCH_GF5 57 -#define PITCH_G5 58 -#define PITCH_AF5 59 -#define PITCH_A5 60 -#define PITCH_BF5 61 -#define PITCH_B5 62 -#define PITCH_C6 63 -#define PITCH_DF6 64 -#define PITCH_D6 65 -#define PITCH_EF6 66 -#define PITCH_E6 67 -#define PITCH_F6 68 -#define PITCH_GF6 69 -#define PITCH_G6 70 -#define PITCH_AF6 71 -#define PITCH_A6 72 -#define PITCH_BF6 73 -#define PITCH_B6 74 -#define PITCH_C7 75 -#define PITCH_DF7 76 -#define PITCH_D7 77 -#define PITCH_EF7 78 -#define PITCH_E7 79 -#define PITCH_F7 80 -#define PITCH_GF7 81 -#define PITCH_G7 82 -#define PITCH_AF7 83 -#define PITCH_A7 84 -#define PITCH_BF7 85 -#define PITCH_B7 86 -#define PITCH_C8 87 -#define PITCH_DF8 88 -#define PITCH_D8 89 -#define PITCH_EF8 90 -#define PITCH_E8 91 -#define PITCH_F8 92 -#define PITCH_GF8 93 -#define PITCH_G8 94 -#define PITCH_AF8 95 -#define PITCH_A8 96 -#define PITCH_BF8 97 -#define PITCH_B8 98 -#define PITCH_C9 99 -#define PITCH_DF9 100 -#define PITCH_D9 101 -#define PITCH_EF9 102 -#define PITCH_E9 103 -#define PITCH_F9 104 -#define PITCH_GF9 105 -#define PITCH_G9 106 -#define PITCH_AF9 107 -#define PITCH_A9 108 -#define PITCH_BF9 109 -#define PITCH_B9 110 -#define PITCH_C10 111 -#define PITCH_DF10 112 -#define PITCH_D10 113 -#define PITCH_EF10 114 -#define PITCH_E10 115 -#define PITCH_F10 116 -#define PITCH_BFNEG1 117 -#define PITCH_BNEG1 118 -#define PITCH_C0 119 -#define PITCH_DF0 120 -#define PITCH_D0 121 -#define PITCH_EF0 122 -#define PITCH_E0 123 -#define PITCH_F0 124 -#define PITCH_GF0 125 -#define PITCH_G0 126 -#define PITCH_AF0 127 +#define PITCH_A0 0 +#define PITCH_BF0 1 +#define PITCH_B0 2 +#define PITCH_C1 3 +#define PITCH_DF1 4 +#define PITCH_D1 5 +#define PITCH_EF1 6 +#define PITCH_E1 7 +#define PITCH_F1 8 +#define PITCH_GF1 9 +#define PITCH_G1 10 +#define PITCH_AF1 11 +#define PITCH_A1 12 +#define PITCH_BF1 13 +#define PITCH_B1 14 +#define PITCH_C2 15 +#define PITCH_DF2 16 +#define PITCH_D2 17 +#define PITCH_EF2 18 +#define PITCH_E2 19 +#define PITCH_F2 20 +#define PITCH_GF2 21 +#define PITCH_G2 22 +#define PITCH_AF2 23 +#define PITCH_A2 24 +#define PITCH_BF2 25 +#define PITCH_B2 26 +#define PITCH_C3 27 +#define PITCH_DF3 28 +#define PITCH_D3 29 +#define PITCH_EF3 30 +#define PITCH_E3 31 +#define PITCH_F3 32 +#define PITCH_GF3 33 +#define PITCH_G3 34 +#define PITCH_AF3 35 +#define PITCH_A3 36 +#define PITCH_BF3 37 +#define PITCH_B3 38 +#define PITCH_C4 39 +#define PITCH_DF4 40 +#define PITCH_D4 41 +#define PITCH_EF4 42 +#define PITCH_E4 43 +#define PITCH_F4 44 +#define PITCH_GF4 45 +#define PITCH_G4 46 +#define PITCH_AF4 47 +#define PITCH_A4 48 +#define PITCH_BF4 49 +#define PITCH_B4 50 +#define PITCH_C5 51 +#define PITCH_DF5 52 +#define PITCH_D5 53 +#define PITCH_EF5 54 +#define PITCH_E5 55 +#define PITCH_F5 56 +#define PITCH_GF5 57 +#define PITCH_G5 58 +#define PITCH_AF5 59 +#define PITCH_A5 60 +#define PITCH_BF5 61 +#define PITCH_B5 62 +#define PITCH_C6 63 +#define PITCH_DF6 64 +#define PITCH_D6 65 +#define PITCH_EF6 66 +#define PITCH_E6 67 +#define PITCH_F6 68 +#define PITCH_GF6 69 +#define PITCH_G6 70 +#define PITCH_AF6 71 +#define PITCH_A6 72 +#define PITCH_BF6 73 +#define PITCH_B6 74 +#define PITCH_C7 75 +#define PITCH_DF7 76 +#define PITCH_D7 77 +#define PITCH_EF7 78 +#define PITCH_E7 79 +#define PITCH_F7 80 +#define PITCH_GF7 81 +#define PITCH_G7 82 +#define PITCH_AF7 83 +#define PITCH_A7 84 +#define PITCH_BF7 85 +#define PITCH_B7 86 +#define PITCH_C8 87 +#define PITCH_DF8 88 +#define PITCH_D8 89 +#define PITCH_EF8 90 +#define PITCH_E8 91 +#define PITCH_F8 92 +#define PITCH_GF8 93 +#define PITCH_G8 94 +#define PITCH_AF8 95 +#define PITCH_A8 96 +#define PITCH_BF8 97 +#define PITCH_B8 98 +#define PITCH_C9 99 +#define PITCH_DF9 100 +#define PITCH_D9 101 +#define PITCH_EF9 102 +#define PITCH_E9 103 +#define PITCH_F9 104 +#define PITCH_GF9 105 +#define PITCH_G9 106 +#define PITCH_AF9 107 +#define PITCH_A9 108 +#define PITCH_BF9 109 +#define PITCH_B9 110 +#define PITCH_C10 111 +#define PITCH_DF10 112 +#define PITCH_D10 113 +#define PITCH_EF10 114 +#define PITCH_E10 115 +#define PITCH_F10 116 +#define PITCH_BFNEG1 117 +#define PITCH_BNEG1 118 +#define PITCH_C0 119 +#define PITCH_DF0 120 +#define PITCH_D0 121 +#define PITCH_EF0 122 +#define PITCH_E0 123 +#define PITCH_F0 124 +#define PITCH_GF0 125 +#define PITCH_G0 126 +#define PITCH_AF0 127 #define READ_U8 (((count++), (reader.ReadUByte()))) -#define READ_S16 (((count+=2), (reader.ReadUInt16()))) -#define READ_CS16 (((count++), (temp = reader.ReadUByte(), (temp & 0x80) ? (count++, ((temp) << 8) | reader.ReadUByte()) : temp))) +#define READ_S16 (((count += 2), (reader.ReadUInt16()))) +#define READ_CS16 \ + (((count++), (temp = reader.ReadUByte(), (temp & 0x80) ? (count++, ((temp) << 8) | reader.ReadUByte()) : temp))) -#define FORMAT_HEX(x, w) "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(w) << x << std::nouppercase << std::dec -#define FORMAT_HEX2(x, w) std::hex << std::uppercase << std::setfill('0') << std::setw(w) << x << std::nouppercase << std::dec +#define FORMAT_HEX(x, w) \ + "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(w) << x << std::nouppercase << std::dec +#define FORMAT_HEX2(x, w) \ + std::hex << std::uppercase << std::setfill('0') << std::setw(w) << x << std::nouppercase << std::dec -ExportResult FZX::SequenceHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::SequenceHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); return std::nullopt; } -ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult FZX::SequenceCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto data = std::static_pointer_cast<SequenceData>(raw); @@ -314,7 +319,8 @@ ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ uint32_t lastEndPos = 0; for (const auto& command : data->mCmds) { if (lastEndPos != command.pos) { - write << fourSpaceTab << "/* Missing instruction or padding at: " << FORMAT_HEX(lastEndPos, 3) << " ( With Gap " << FORMAT_HEX(command.pos - lastEndPos, 2) << " )*/"; + write << fourSpaceTab << "/* Missing instruction or padding at: " << FORMAT_HEX(lastEndPos, 3) + << " ( With Gap " << FORMAT_HEX(command.pos - lastEndPos, 2) << " )*/"; if (command.pos - lastEndPos < 0x10) { for (uint32_t i = lastEndPos; i < command.pos; i++) { @@ -325,15 +331,16 @@ ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ } lastEndPos = command.pos + command.size; - if (Torch::contains(data->mLabels,command.pos)) { + if (Torch::contains(data->mLabels, command.pos)) { write << "// L____" << FORMAT_HEX2(command.pos, 3) << ":\n"; } if (command.state == SequenceState::data) { uint32_t i = 0; write << fourSpaceTab << "/* DATA LABELS */\n"; - for (const auto& arg: command.args) { - write << fourSpaceTab << "/* " << FORMAT_HEX(command.pos + 2 * i, 3) << " - " << FORMAT_HEX(command.pos + 2 * (i + 1), 3) << " */ "; + for (const auto& arg : command.args) { + write << fourSpaceTab << "/* " << FORMAT_HEX(command.pos + 2 * i, 3) << " - " + << FORMAT_HEX(command.pos + 2 * (i + 1), 3) << " */ "; write << "S16(" << FORMAT_HEX(std::get<uint16_t>(arg), 3) << "), "; write << "// L____" << FORMAT_HEX2(std::get<uint16_t>(arg), 3) << "\n"; i++; @@ -345,9 +352,10 @@ ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ if (command.state == SequenceState::envelope) { uint32_t i = 0; write << fourSpaceTab << "/* ENVELOPE START */\n"; - for (const auto& arg: command.args) { + for (const auto& arg : command.args) { if (i % 2 == 0) { - write << fourSpaceTab << "/* " << FORMAT_HEX(command.pos + 2 * i, 3) << " - " << FORMAT_HEX(command.pos + 2 * (i + 2), 3) << " */ "; + write << fourSpaceTab << "/* " << FORMAT_HEX(command.pos + 2 * i, 3) << " - " + << FORMAT_HEX(command.pos + 2 * (i + 2), 3) << " */ "; write << "S16(" << FORMAT_HEX(std::get<uint16_t>(arg), 4) << "), "; } else { write << "S16(" << FORMAT_HEX(std::get<uint16_t>(arg), 4) << "),\n"; @@ -358,7 +366,8 @@ ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ continue; } - write << fourSpaceTab << "/* " << FORMAT_HEX(command.pos, 3) << " - " << FORMAT_HEX(command.pos + command.size, 3) << " */ "; + write << fourSpaceTab << "/* " << FORMAT_HEX(command.pos, 3) << " - " + << FORMAT_HEX(command.pos + command.size, 3) << " */ "; if (command.channel != -1) { write << "/* Channel: " << command.channel << " */ "; @@ -1233,9 +1242,10 @@ ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ for (const auto& arg : command.args) { write << " "; - switch(static_cast<SeqArgType>(arg.index())) { + switch (static_cast<SeqArgType>(arg.index())) { case SeqArgType::U8: - // if (command.cmd == ASEQ_OP_RJUMP || command.cmd == ASEQ_OP_RBLTZ || command.cmd == ASEQ_OP_RBEQZ) { + // if (command.cmd == ASEQ_OP_RJUMP || command.cmd == ASEQ_OP_RBLTZ || command.cmd == ASEQ_OP_RBEQZ) + // { // int32_t temp = static_cast<int32_t>((int8_t)(std::get<uint8_t>(arg) & 0xFF)); // if (temp >= 0) { // write << FORMAT_HEX(temp, 2) << ","; @@ -1260,8 +1270,14 @@ ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ } if (command.cmd == ASEQ_OP_RJUMP || command.cmd == ASEQ_OP_RBLTZ || command.cmd == ASEQ_OP_RBEQZ) { - write << " /* LABEL: L____" << FORMAT_HEX2(command.pos + static_cast<int32_t>((int8_t)(std::get<uint8_t>(command.args.at(0)) & 0xFF)) + 2, 3) << " */"; - } else if (command.cmd == ASEQ_OP_JUMP || command.cmd == ASEQ_OP_BLTZ || command.cmd == ASEQ_OP_BEQZ || ((command.cmd & 0xF0) == ASEQ_OP_SEQ_LDCHAN && command.state == SequenceState::player) || ((command.cmd & 0xF8) == ASEQ_OP_CHAN_LDLAYER && command.state == SequenceState::channel)) { + write << " /* LABEL: L____" + << FORMAT_HEX2(command.pos + + static_cast<int32_t>((int8_t)(std::get<uint8_t>(command.args.at(0)) & 0xFF)) + 2, + 3) + << " */"; + } else if (command.cmd == ASEQ_OP_JUMP || command.cmd == ASEQ_OP_BLTZ || command.cmd == ASEQ_OP_BEQZ || + ((command.cmd & 0xF0) == ASEQ_OP_SEQ_LDCHAN && command.state == SequenceState::player) || + ((command.cmd & 0xF8) == ASEQ_OP_CHAN_LDLAYER && command.state == SequenceState::channel)) { write << " /* LABEL: L____" << FORMAT_HEX2(std::get<uint16_t>(command.args.at(0)), 3) << " */"; } @@ -1270,7 +1286,8 @@ ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ if (data->mHasFooter) { const std::string mmlPassCheckStr = "== MML PASS CHECK =="; - write << fourSpaceTab << "/* " << FORMAT_HEX(lastEndPos, 3) << " - " << FORMAT_HEX(lastEndPos + mmlPassCheckStr.length(), 3) << " */ "; + write << fourSpaceTab << "/* " << FORMAT_HEX(lastEndPos, 3) << " - " + << FORMAT_HEX(lastEndPos + mmlPassCheckStr.length(), 3) << " */ "; for (size_t i = 0; i < mmlPassCheckStr.length(); i++) { write << "\'" << mmlPassCheckStr.at(i) << "\'"; if (i != mmlPassCheckStr.length() - 1) { @@ -1287,13 +1304,15 @@ ExportResult FZX::SequenceCodeExporter::Export(std::ostream &write, std::shared_ return offset + lastEndPos; } -ExportResult FZX::SequenceBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult FZX::SequenceBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { // Nothing Required Here For Binary Exporting return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> FZX::SequenceFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> FZX::SequenceFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto symbol = GetSafeNode<std::string>(node, "symbol"); @@ -1419,25 +1438,28 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SequenceFactory::parse(std::vec switch (command.cmd) { case ASEQ_OP_RBLTZ: { uint8_t jumpRPos = READ_U8; - int8_t jumpRSignedPos = (int8_t) (jumpRPos & 0xFF); + int8_t jumpRSignedPos = (int8_t)(jumpRPos & 0xFF); command.args.emplace_back(jumpRPos); - posStack.emplace_back(count + jumpRSignedPos, command.state, command.channel, command.layer, largeNotes); + posStack.emplace_back(count + jumpRSignedPos, command.state, command.channel, command.layer, + largeNotes); labels.insert(count + jumpRSignedPos); break; } case ASEQ_OP_RBEQZ: { uint8_t jumpRPos = READ_U8; - int8_t jumpRSignedPos = (int8_t) (jumpRPos & 0xFF); + int8_t jumpRSignedPos = (int8_t)(jumpRPos & 0xFF); command.args.emplace_back(jumpRPos); - posStack.emplace_back(count + jumpRSignedPos, command.state, command.channel, command.layer, largeNotes); + posStack.emplace_back(count + jumpRSignedPos, command.state, command.channel, command.layer, + largeNotes); labels.insert(count + jumpRSignedPos); break; } case ASEQ_OP_RJUMP: { uint8_t jumpRPos = READ_U8; - int8_t jumpRSignedPos = (int8_t) (jumpRPos & 0xFF); + int8_t jumpRSignedPos = (int8_t)(jumpRPos & 0xFF); command.args.emplace_back(jumpRPos); - posStack.emplace_back(count + jumpRSignedPos, command.state, command.channel, command.layer, largeNotes); + posStack.emplace_back(count + jumpRSignedPos, command.state, command.channel, command.layer, + largeNotes); labels.insert(count + jumpRSignedPos); nextLabel = true; break; @@ -1608,7 +1630,8 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SequenceFactory::parse(std::vec case ASEQ_OP_SEQ_LDCHAN: { uint16_t chanPos = READ_S16; command.args.emplace_back(chanPos); - posStack.emplace_back(chanPos, SequenceState::channel, command.cmd & 0xF, command.layer, largeNotes); + posStack.emplace_back(chanPos, SequenceState::channel, command.cmd & 0xF, command.layer, + largeNotes); labels.insert(chanPos); SPDLOG_INFO("PLAYER LDCHAN POS: 0x{:X}, Chan: {}", chanPos, command.cmd & 0xF); break; @@ -1616,7 +1639,8 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SequenceFactory::parse(std::vec case ASEQ_OP_SEQ_RLDCHAN: { uint16_t chanRPos = READ_S16; command.args.emplace_back(chanRPos); - posStack.emplace_back(count + chanRPos, SequenceState::channel, command.cmd & 0xF, command.layer, largeNotes); + posStack.emplace_back(count + chanRPos, SequenceState::channel, command.cmd & 0xF, + command.layer, largeNotes); labels.insert(count + chanRPos); SPDLOG_INFO("PLAYER RLDCHAN POS: 0x{:X}, Chan: {}", count + chanRPos, command.cmd & 0xF); break; @@ -1781,7 +1805,8 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SequenceFactory::parse(std::vec command.args.emplace_back(READ_U8); break; case ASEQ_OP_CHAN_DYNCALL: - posStack.emplace_back(dynTableStack.back(), SequenceState::data, command.channel, command.layer, largeNotes); + posStack.emplace_back(dynTableStack.back(), SequenceState::data, command.channel, + command.layer, largeNotes); labels.insert(dynTableStack.back()); dynTableStack.pop_back(); break; @@ -1837,14 +1862,16 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SequenceFactory::parse(std::vec case ASEQ_OP_CHAN_LDLAYER: { uint16_t layerPos = READ_S16; command.args.emplace_back(layerPos); - posStack.emplace_back(layerPos, SequenceState::layer, command.channel, command.cmd & 0x7, largeNotes); + posStack.emplace_back(layerPos, SequenceState::layer, command.channel, command.cmd & 0x7, + largeNotes); labels.insert(layerPos); break; } case ASEQ_OP_CHAN_RLDLAYER: { uint16_t layerRPos = READ_S16; command.args.emplace_back(layerRPos); - posStack.emplace_back(count + layerRPos, SequenceState::layer, command.channel, command.cmd & 0x7, largeNotes); + posStack.emplace_back(count + layerRPos, SequenceState::layer, command.channel, + command.cmd & 0x7, largeNotes); labels.insert(count + layerRPos); break; } @@ -1861,7 +1888,8 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SequenceFactory::parse(std::vec case ASEQ_OP_CHAN_LDCHAN: { uint16_t chanPos = READ_S16; command.args.emplace_back(chanPos); - posStack.emplace_back(chanPos, SequenceState::channel, command.cmd & 0xF, command.layer, largeNotes); + posStack.emplace_back(chanPos, SequenceState::channel, command.cmd & 0xF, command.layer, + largeNotes); labels.insert(chanPos); break; } diff --git a/src/factories/fzerox/SoundFontFactory.cpp b/src/factories/fzerox/SoundFontFactory.cpp index 1c95121..9758f7b 100644 --- a/src/factories/fzerox/SoundFontFactory.cpp +++ b/src/factories/fzerox/SoundFontFactory.cpp @@ -50,8 +50,10 @@ static std::unordered_map<uint32_t, std::string> sMediumMap = { { MEDIUM_DISK_DRIVE, "MEDIUM_DISK_DRIVE" }, }; -#define FORMAT_HEX(x, w) "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(w) << x << std::nouppercase << std::dec -#define FORMAT_FLOAT(x, w, p) std::dec << std::setfill(' ') << std::fixed << std::setprecision(p) << std::setw(w) << x << "f" +#define FORMAT_HEX(x, w) \ + "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(w) << x << std::nouppercase << std::dec +#define FORMAT_FLOAT(x, w, p) \ + std::dec << std::setfill(' ') << std::fixed << std::setprecision(p) << std::setw(w) << x << "f" #define DRUM_SIZE 0x10 #define SFX_SIZE 0x8 @@ -63,10 +65,11 @@ static std::unordered_map<uint32_t, std::string> sMediumMap = { #define LOOP_SIZE2 0x30 #define ALIGN16(val) (((val) + 0xF) & ~0xF) -ExportResult FZX::SoundFontHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult FZX::SoundFontHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto soundFontData = std::static_pointer_cast<SoundFontData>(raw); - + write << "extern u32 " << symbol << "Offsets[];\n"; for (const auto& entry : soundFontData->mEntries) { @@ -109,7 +112,8 @@ ExportResult FZX::SoundFontHeaderExporter::Export(std::ostream &write, std::shar return std::nullopt; } -ExportResult FZX::SoundFontCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult FZX::SoundFontCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto soundFontData = std::static_pointer_cast<SoundFontData>(raw); @@ -189,7 +193,8 @@ ExportResult FZX::SoundFontCodeExporter::Export(std::ostream &write, std::shared } dataNameToSizeMap[entry.name] = size; - SPDLOG_INFO("ENTRY OUT {} {}, 0x{:X} (size 0x{:X})", sSoundFontDataTypeMap[entry.type], entry.name, rollingOffset, size); + SPDLOG_INFO("ENTRY OUT {} {}, 0x{:X} (size 0x{:X})", sSoundFontDataTypeMap[entry.type], entry.name, + rollingOffset, size); rollingOffset += size; } uint32_t totalSize = rollingOffset; @@ -246,7 +251,8 @@ ExportResult FZX::SoundFontCodeExporter::Export(std::ostream &write, std::shared auto drum = std::get<Drum>(entry.data); write << "Drum " << entry.name << " = {\n"; write << fourSpaceTab << (uint32_t)drum.adsrDecayIndex << ", " << (uint32_t)drum.pan << ", 0,\n"; - write << fourSpaceTab << "{ " << FORMAT_HEX(dataNameToOffsetMap[drum.tunedSample.sampleRef], 1) << ", " << FORMAT_FLOAT(drum.tunedSample.tuning, 7, 7) << " },\n"; + write << fourSpaceTab << "{ " << FORMAT_HEX(dataNameToOffsetMap[drum.tunedSample.sampleRef], 1) << ", " + << FORMAT_FLOAT(drum.tunedSample.tuning, 7, 7) << " },\n"; write << fourSpaceTab << FORMAT_HEX(dataNameToOffsetMap[drum.envelopeRef], 1) << ",\n"; write << "};\n\n"; break; @@ -255,7 +261,8 @@ ExportResult FZX::SoundFontCodeExporter::Export(std::ostream &write, std::shared auto sfxList = std::get<std::vector<SoundEffect>>(entry.data); write << "SoundEffect " << entry.name << "[] = {\n"; for (const auto& sfx : sfxList) { - write << fourSpaceTab << "{ { " << FORMAT_HEX(dataNameToOffsetMap[sfx.tunedSample.sampleRef], 1) << ", " << FORMAT_FLOAT(sfx.tunedSample.tuning, 7, 7) << " } },\n"; + write << fourSpaceTab << "{ { " << FORMAT_HEX(dataNameToOffsetMap[sfx.tunedSample.sampleRef], 1) + << ", " << FORMAT_FLOAT(sfx.tunedSample.tuning, 7, 7) << " } },\n"; } write << "};\n\n"; break; @@ -263,10 +270,18 @@ ExportResult FZX::SoundFontCodeExporter::Export(std::ostream &write, std::shared case DataType::Instrument: { auto instrument = std::get<Instrument>(entry.data); write << "Instrument " << entry.name << " = {\n"; - write << fourSpaceTab << "0, " << (uint32_t)instrument.normalRangeLo << ", " << (uint32_t)instrument.normalRangeHi << ", " << (uint32_t)instrument.adsrDecayIndex << ", " << FORMAT_HEX(dataNameToOffsetMap[instrument.envelopeRef], 1) << ",\n"; - write << fourSpaceTab << "{ " << FORMAT_HEX(dataNameToOffsetMap[instrument.lowPitchTunedSample.sampleRef], 1) << ", " << FORMAT_FLOAT(instrument.lowPitchTunedSample.tuning, 7, 7) << " },\n"; - write << fourSpaceTab << "{ " << FORMAT_HEX(dataNameToOffsetMap[instrument.normalPitchTunedSample.sampleRef], 1) << ", " << FORMAT_FLOAT(instrument.normalPitchTunedSample.tuning, 7, 7) << " },\n"; - write << fourSpaceTab << "{ " << FORMAT_HEX(dataNameToOffsetMap[instrument.highPitchTunedSample.sampleRef], 1) << ", " << FORMAT_FLOAT(instrument.highPitchTunedSample.tuning, 7, 7) << " },\n"; + write << fourSpaceTab << "0, " << (uint32_t)instrument.normalRangeLo << ", " + << (uint32_t)instrument.normalRangeHi << ", " << (uint32_t)instrument.adsrDecayIndex << ", " + << FORMAT_HEX(dataNameToOffsetMap[instrument.envelopeRef], 1) << ",\n"; + write << fourSpaceTab << "{ " + << FORMAT_HEX(dataNameToOffsetMap[instrument.lowPitchTunedSample.sampleRef], 1) << ", " + << FORMAT_FLOAT(instrument.lowPitchTunedSample.tuning, 7, 7) << " },\n"; + write << fourSpaceTab << "{ " + << FORMAT_HEX(dataNameToOffsetMap[instrument.normalPitchTunedSample.sampleRef], 1) << ", " + << FORMAT_FLOAT(instrument.normalPitchTunedSample.tuning, 7, 7) << " },\n"; + write << fourSpaceTab << "{ " + << FORMAT_HEX(dataNameToOffsetMap[instrument.highPitchTunedSample.sampleRef], 1) << ", " + << FORMAT_FLOAT(instrument.highPitchTunedSample.tuning, 7, 7) << " },\n"; write << "};\n\n"; break; } @@ -288,8 +303,11 @@ ExportResult FZX::SoundFontCodeExporter::Export(std::ostream &write, std::shared if (soundFontData->mSupportSfx) { write << "0, "; } - write << sCodecMap.at(sample.codec) << ", " << sMediumMap.at(sample.medium) << ", " << sample.unk_bit26 << ", 0, " << FORMAT_HEX(sample.size, 1) << ",\n"; - write << fourSpaceTab << FORMAT_HEX(sample.rawSampleOffset, 1) << ", " << FORMAT_HEX(dataNameToOffsetMap[sample.loopRef], 1) << ", " << FORMAT_HEX(dataNameToOffsetMap[sample.bookRef], 1); + write << sCodecMap.at(sample.codec) << ", " << sMediumMap.at(sample.medium) << ", " << sample.unk_bit26 + << ", 0, " << FORMAT_HEX(sample.size, 1) << ",\n"; + write << fourSpaceTab << FORMAT_HEX(sample.rawSampleOffset, 1) << ", " + << FORMAT_HEX(dataNameToOffsetMap[sample.loopRef], 1) << ", " + << FORMAT_HEX(dataNameToOffsetMap[sample.bookRef], 1); write << "\n};\n\n"; break; @@ -318,10 +336,12 @@ ExportResult FZX::SoundFontCodeExporter::Export(std::ostream &write, std::shared auto loop = std::get<AdpcmLoop>(entry.data); if (loop.count != 0) { write << "AdpcmLoop " << entry.name << " = {\n"; - write << fourSpaceTab << "{ " << loop.start << ", " << loop.end << ", " << FORMAT_HEX(loop.count, 1) << ", { 0 } },"; + write << fourSpaceTab << "{ " << loop.start << ", " << loop.end << ", " << FORMAT_HEX(loop.count, 1) + << ", { 0 } },"; } else { write << "AdpcmLoopHeader " << entry.name << " = {\n"; - write << fourSpaceTab << loop.start << ", " << loop.end << ", " << FORMAT_HEX(loop.count, 1) << ", { 0 },"; + write << fourSpaceTab << loop.start << ", " << loop.end << ", " << FORMAT_HEX(loop.count, 1) + << ", { 0 },"; } if (loop.count != 0) { @@ -368,12 +388,16 @@ ExportResult FZX::SoundFontCodeExporter::Export(std::ostream &write, std::shared return offset + totalSize; } -ExportResult FZX::SoundFontBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult FZX::SoundFontBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { return std::nullopt; } -std::string FZX::SoundFontFactory::RegisterSoundFontData(std::string symbol, FZX::DataType dataType, uint32_t offset, std::map<uint32_t, std::pair<FZX::DataType, std::string>>& dataMap, std::unordered_map<FZX::DataType, uint32_t>& dataCountMap) { +std::string +FZX::SoundFontFactory::RegisterSoundFontData(std::string symbol, FZX::DataType dataType, uint32_t offset, + std::map<uint32_t, std::pair<FZX::DataType, std::string>>& dataMap, + std::unordered_map<FZX::DataType, uint32_t>& dataCountMap) { std::string dataName; if (Torch::contains(dataMap, offset)) { @@ -422,7 +446,8 @@ std::string FZX::SoundFontFactory::RegisterSoundFontData(std::string symbol, FZX return dataName; } -std::optional<std::shared_ptr<IParsedData>> FZX::SoundFontFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> FZX::SoundFontFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto symbol = GetSafeNode<std::string>(node, "symbol"); @@ -490,9 +515,10 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SoundFontFactory::parse(std::ve drum.pan = reader.ReadUByte(); drum.isRelocated = reader.ReadUByte(); reader.ReadUByte(); - + auto sampleOffset = reader.ReadUInt32(); - drum.tunedSample.sampleRef = RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); + drum.tunedSample.sampleRef = + RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); sampleOffsets.insert(sampleOffset); drum.tunedSample.tuning = reader.ReadFloat(); auto envelopeOffset = reader.ReadUInt32(); @@ -506,18 +532,19 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SoundFontFactory::parse(std::ve if (supportSfx) { SPDLOG_INFO("FZX SOUNDFONT SEEK sfx 0x{:X}", sfxOffset); reader.Seek(sfxOffset, LUS::SeekOffsetType::Start); - + if (numSfx > 0) { std::vector<SoundEffect> soundEffects; for (uint32_t i = 0; i < numSfx; i++) { SoundEffect soundEffect; auto sampleOffset = reader.ReadUInt32(); - soundEffect.tunedSample.sampleRef = RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); + soundEffect.tunedSample.sampleRef = + RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); sampleOffsets.insert(sampleOffset); soundEffect.tunedSample.tuning = reader.ReadFloat(); soundEffects.push_back(soundEffect); } - + soundFontMap[dataMap.at(sfxOffset).second] = soundEffects; } } @@ -534,26 +561,30 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SoundFontFactory::parse(std::ve instrument.normalRangeHi = reader.ReadUByte(); instrument.adsrDecayIndex = reader.ReadUByte(); auto envelopeOffset = reader.ReadUInt32(); - instrument.envelopeRef = RegisterSoundFontData(symbol, DataType::Envelope, envelopeOffset, dataMap, dataCountMap); + instrument.envelopeRef = + RegisterSoundFontData(symbol, DataType::Envelope, envelopeOffset, dataMap, dataCountMap); envelopeOffsets.insert(envelopeOffset); sampleOffset = reader.ReadUInt32(); if (sampleOffset != 0) { - instrument.lowPitchTunedSample.sampleRef = RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); + instrument.lowPitchTunedSample.sampleRef = + RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); sampleOffsets.insert(sampleOffset); } instrument.lowPitchTunedSample.tuning = reader.ReadFloat(); sampleOffset = reader.ReadUInt32(); if (sampleOffset != 0) { - instrument.normalPitchTunedSample.sampleRef = RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); + instrument.normalPitchTunedSample.sampleRef = + RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); sampleOffsets.insert(sampleOffset); } instrument.normalPitchTunedSample.tuning = reader.ReadFloat(); sampleOffset = reader.ReadUInt32(); if (sampleOffset != 0) { - instrument.highPitchTunedSample.sampleRef = RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); + instrument.highPitchTunedSample.sampleRef = + RegisterSoundFontData(symbol, DataType::Sample, sampleOffset, dataMap, dataCountMap); sampleOffsets.insert(sampleOffset); } instrument.highPitchTunedSample.tuning = reader.ReadFloat(); @@ -586,7 +617,7 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SoundFontFactory::parse(std::ve Sample sample; SPDLOG_INFO("FZX SOUNDFONT SEEK sample 0x{:X}", sampleOffset); reader.Seek(sampleOffset, LUS::SeekOffsetType::Start); - + uint32_t sampleBitfield = reader.ReadUInt32(); sample.codec = (sampleBitfield & (0b0111 << 28)) >> 28; sample.medium = (sampleBitfield & (0b11 << 26)) >> 26; @@ -601,7 +632,7 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SoundFontFactory::parse(std::ve auto bookOffset = reader.ReadUInt32(); sample.bookRef = RegisterSoundFontData(symbol, DataType::Book, bookOffset, dataMap, dataCountMap); bookOffsets.insert(bookOffset); - + soundFontMap[dataMap.at(sampleOffset).second] = sample; } @@ -650,6 +681,6 @@ std::optional<std::shared_ptr<IParsedData>> FZX::SoundFontFactory::parse(std::ve soundFontEntries.push_back(entry); } - + return std::make_shared<SoundFontData>(soundFontEntries, supportSfx); } diff --git a/src/factories/mario_artist/MA2D1Factory.cpp b/src/factories/mario_artist/MA2D1Factory.cpp index b536a9e..d9c6d57 100644 --- a/src/factories/mario_artist/MA2D1Factory.cpp +++ b/src/factories/mario_artist/MA2D1Factory.cpp @@ -5,13 +5,15 @@ #include "utils/Decompressor.h" #include "utils/TorchUtils.h" -ExportResult MA::MA2D1HeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MA::MA2D1HeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); return std::nullopt; } -ExportResult MA::MA2D1CodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MA::MA2D1CodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto data = std::static_pointer_cast<MA2D1Data>(raw); @@ -46,7 +48,8 @@ ExportResult MA::MA2D1CodeExporter::Export(std::ostream &write, std::shared_ptr< return offset + 0x10; } -ExportResult MA::MA2D1BinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MA::MA2D1BinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { // Nothing Required Here For Binary Exporting return std::nullopt; diff --git a/src/factories/mk64/CourseMetadata.cpp b/src/factories/mk64/CourseMetadata.cpp index 21bb385..57db5b0 100644 --- a/src/factories/mk64/CourseMetadata.cpp +++ b/src/factories/mk64/CourseMetadata.cpp @@ -8,7 +8,9 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) "0x" << std::hex << std::setw(2) << std::setfill('0') << c -ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto metadata = std::static_pointer_cast<MetadataData>(raw)->mMetadata; if (metadata.empty()) { @@ -17,9 +19,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: // Sort the data by id, 0 to 20 and beyond. std::sort(metadata.begin(), metadata.end(), - [this](const CourseMetadata& a, const CourseMetadata& b) { - return a.id < b.id; - }); + [this](const CourseMetadata& a, const CourseMetadata& b) { return a.id < b.id; }); std::ofstream file; auto outDir = GetSafeNode<std::string>(node, "out_directory") + "/"; @@ -28,70 +28,80 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: if (!std::filesystem::exists(outDir)) { std::filesystem::create_directory(outDir); } - - file.open(outDir+"gCourseNames.inc.c", std::ios_base::binary | std::ios_base::out); + + file.open(outDir + "gCourseNames.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { - // file << "char *gCourseNames[] = {\n" << fourSpaceTab; + // file << "char *gCourseNames[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { - if (m.name == "null") { continue; } + if (m.name == "null") { + continue; + } // Remove debug line once proven that sort worked right (start at id 0 and go up) - SPDLOG_INFO("Processing Course Id: "+std::to_string(m.id)); + SPDLOG_INFO("Processing Course Id: " + std::to_string(m.id)); file << '"' << m.name << "\", "; } file << "\n"; - // file << "\n};\n\n"; + // file << "\n};\n\n"; file.close(); } else if (file.fail()) { throw std::runtime_error("Course metadata output folder is likely bad or the file is in-use"); } - file.open(outDir+"gCourseDebugNames.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "gCourseDebugNames.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { - // file << "char *gDebugCourseNames[] = {\n" << fourSpaceTab; + // file << "char *gDebugCourseNames[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { - if (m.name == "null") { continue; } + if (m.name == "null") { + continue; + } file << '"' << m.debugName << "\", "; } file << "\n"; - //file << "\n};\n\n"; + // file << "\n};\n\n"; file.close(); } - file.open(outDir+"gCupSelectionByCourseId.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "gCupSelectionByCourseId.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { - //file << "char *gCupSelectionByCourseId[] = {\n" << fourSpaceTab; + // file << "char *gCupSelectionByCourseId[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { - if (m.cup == "null") { continue; } + if (m.cup == "null") { + continue; + } file << m.cup << ", "; } file << "\n"; - // file << "\n};\n\n"; + // file << "\n};\n\n"; file.close(); } - file.open(outDir+"gPerCupIndexByCourseId.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "gPerCupIndexByCourseId.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { - //file << "const u8 gPerCupIndexByCourseId[] = {\n" << fourSpaceTab; + // file << "const u8 gPerCupIndexByCourseId[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { - if (m.cupIndex == -1) { continue; } + if (m.cupIndex == -1) { + continue; + } file << m.cupIndex << ", "; } file << "\n"; - //file << "\n};\n\n"; + // file << "\n};\n\n"; file.close(); } - file.open(outDir+"sCourseLengths.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "sCourseLengths.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { - if (m.courseLength == "null") { continue; } + if (m.courseLength == "null") { + continue; + } file << '"' << m.courseLength << "\", "; } file << "\n"; file.close(); } - file.open(outDir+"cpu_BehaviourLUT.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "cpu_BehaviourLUT.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << m.CPUBehaviourLUT << ", "; @@ -101,7 +111,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"cpu_CourseMaximumSeparation.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "cpu_CourseMaximumSeparation.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { // file << "f32 gWaypointWidth[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { @@ -112,7 +122,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"cpu_CourseMinimumSeparation.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "cpu_CourseMinimumSeparation.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { // file << "f32 gWaypointWidth2[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { @@ -123,34 +133,34 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"D_800DCBB4.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "D_800DCBB4.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { - //file << "uintptr_t *D_800DCBB4[] = {\n" << fourSpaceTab; + // file << "uintptr_t *D_800DCBB4[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { file << m.D_800DCBB4 << ", "; } file << "\n"; - //file << "\n};\n\n"; + // file << "\n};\n\n"; file.close(); } - file.open(outDir+"cpu_SteeringSensitivity.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "cpu_SteeringSensitivity.inc.c", std::ios_base::binary | std::ios_base::out); // @WARNING THIS FILE HAS A TRAILING ZERO if (file.is_open()) { - //file << "u16 cpu_SteeringSensitivity[] = {\n" << fourSpaceTab; + // file << "u16 cpu_SteeringSensitivity[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { file << m.steeringSensitivity << ", "; } file << 0; file << "\n"; - //file << "\n};\n\n"; + // file << "\n};\n\n"; file.close(); } - file.open(outDir+"gBombKartSpawns.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "gBombKartSpawns.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { - //file << "u16 cpu_SteeringSensitivity[] = {\n" << fourSpaceTab; + // file << "u16 cpu_SteeringSensitivity[] = {\n" << fourSpaceTab; for (const auto& m : metadata) { file << "{ // " << m.name << "\n"; for (const auto& bombKart : m.bombKartSpawns) { @@ -169,7 +179,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"gCoursePathSizes.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "gCoursePathSizes.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -190,7 +200,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"cpu_CurveTargetSpeed.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "cpu_CurveTargetSpeed.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -203,7 +213,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"cpu_NormalTargetSpeed.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "cpu_NormalTargetSpeed.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -216,7 +226,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"D_0D0096B8.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "D_0D0096B8.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -229,7 +239,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"cpu_OffTrackTargetSpeed.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "cpu_OffTrackTargetSpeed.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -242,7 +252,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"gCoursePathTable.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "gCoursePathTable.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -255,7 +265,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"gCoursePathTableUnknown.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "gCoursePathTableUnknown.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -268,7 +278,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"sSkyColors.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "sSkyColors.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -281,7 +291,7 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: file.close(); } - file.open(outDir+"sSkyColors2.inc.c", std::ios_base::binary | std::ios_base::out); + file.open(outDir + "sSkyColors2.inc.c", std::ios_base::binary | std::ios_base::out); if (file.is_open()) { for (const auto& m : metadata) { file << "// " << m.name << "\n"; @@ -296,12 +306,14 @@ ExportResult MK64::CourseMetadataCodeExporter::Export(std::ostream &write, std:: return std::nullopt; } -ExportResult MK64::CourseMetadataBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MK64::CourseMetadataBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto properties = std::static_pointer_cast<MetadataData>(raw); auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::CourseProperties, 0); - writer.Write((uint32_t) properties->mMetadata.size()); + writer.Write((uint32_t)properties->mMetadata.size()); for (auto m : properties->mMetadata) { writer.Write(m.id); @@ -367,16 +379,17 @@ ExportResult MK64::CourseMetadataBinaryExporter::Export(std::ostream &write, std return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> MK64::CourseMetadataFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> MK64::CourseMetadataFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto dir = GetSafeNode<std::string>(node, "input_directory"); - + auto m = Companion::Instance->GetCourseMetadata(); SPDLOG_INFO("RUNNING"); std::vector<CourseMetadata> yamlData; - for (const auto &yamls : m[dir]) { - + for (const auto& yamls : m[dir]) { + if (!yamls["course"]) { - for (auto &node : yamls) { + for (auto& node : yamls) { std::cout << node << std::endl; } throw std::runtime_error("Course yaml missing root label of course\nEx. course:"); @@ -386,19 +399,19 @@ std::optional<std::shared_ptr<IParsedData>> MK64::CourseMetadataFactory::parse(s CourseMetadata data; - data.id = GetSafeNode<uint32_t>(metadata, "id"); - data.name = GetSafeNode<std::string>(metadata, "name"); - data.debugName = GetSafeNode<std::string>(metadata, "debug_name"); - data.cup = GetSafeNode<std::string>(metadata, "cup"); - data.cupIndex = GetSafeNode<int32_t>(metadata, "cup_index"); - data.courseLength = GetSafeNode<std::string>(metadata, "course_length"); + data.id = GetSafeNode<uint32_t>(metadata, "id"); + data.name = GetSafeNode<std::string>(metadata, "name"); + data.debugName = GetSafeNode<std::string>(metadata, "debug_name"); + data.cup = GetSafeNode<std::string>(metadata, "cup"); + data.cupIndex = GetSafeNode<int32_t>(metadata, "cup_index"); + data.courseLength = GetSafeNode<std::string>(metadata, "course_length"); - data.CPUBehaviourLUT = GetSafeNode<std::string>(metadata, "cpu_behaviour_ptr"); - data.kartAIMaximumSeparation = GetSafeNode<std::string>(metadata, "cpu_maximum_separation"); - data.kartAIMinimumSeparation = GetSafeNode<std::string>(metadata, "cpu_minimum_separation"); + data.CPUBehaviourLUT = GetSafeNode<std::string>(metadata, "cpu_behaviour_ptr"); + data.kartAIMaximumSeparation = GetSafeNode<std::string>(metadata, "cpu_maximum_separation"); + data.kartAIMinimumSeparation = GetSafeNode<std::string>(metadata, "cpu_minimum_separation"); - data.D_800DCBB4 = GetSafeNode<std::string>(metadata, "D_800DCBB4"); - data.steeringSensitivity = GetSafeNode<uint32_t>(metadata, "cpu_steering_sensitivity"); + data.D_800DCBB4 = GetSafeNode<std::string>(metadata, "D_800DCBB4"); + data.steeringSensitivity = GetSafeNode<uint32_t>(metadata, "cpu_steering_sensitivity"); SPDLOG_INFO("BEFORE"); for (const auto& bombKart : GetSafeNode<YAML::Node>(metadata, "bomb_kart_spawns")) { data.bombKartSpawns.push_back(BombKartSpawns({ @@ -448,9 +461,7 @@ std::optional<std::shared_ptr<IParsedData>> MK64::CourseMetadataFactory::parse(s data.skyColors2.push_back(value.as<uint16_t>()); } - yamlData.push_back(CourseMetadata( - {data} - )); + yamlData.push_back(CourseMetadata({ data })); } SPDLOG_INFO("END RUNNING"); diff --git a/src/factories/mk64/CourseVtx.cpp b/src/factories/mk64/CourseVtx.cpp index d41c8e0..7c635a6 100644 --- a/src/factories/mk64/CourseVtx.cpp +++ b/src/factories/mk64/CourseVtx.cpp @@ -7,10 +7,11 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) "0x" << std::hex << std::setw(2) << std::setfill('0') << c -ExportResult MK64::CourseVtxHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MK64::CourseVtxHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -19,7 +20,8 @@ ExportResult MK64::CourseVtxHeaderExporter::Export(std::ostream &write, std::sha return std::nullopt; } -ExportResult MK64::CourseVtxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::CourseVtxCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto vtx = std::static_pointer_cast<CourseVtxData>(raw)->mVtxs; const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -36,30 +38,32 @@ ExportResult MK64::CourseVtxCodeExporter::Export(std::ostream &write, std::share auto tc1 = v.tc[0]; auto tc2 = v.tc[1]; - auto c1 = (uint16_t) v.cn[0]; - auto c2 = (uint16_t) v.cn[1]; - auto c3 = (uint16_t) v.cn[2]; - auto c4 = (uint16_t) v.cn[3]; + auto c1 = (uint16_t)v.cn[0]; + auto c2 = (uint16_t)v.cn[1]; + auto c3 = (uint16_t)v.cn[2]; + auto c4 = (uint16_t)v.cn[3]; - if(i <= vtx.size() - 1) { + if (i <= vtx.size() - 1) { write << fourSpaceTab; } // {{{ x, y, z }, { tc1, tc2 }, { c1, c2, c3, c4 }}} - write << "{{{" << NUM(x) << ", " << NUM(y) << ", " << NUM(z) << "}, {" << NUM(tc1) << ", " << NUM(tc2) << "}, {" << COL(c1) << ", " << COL(c2) << ", " << COL(c3) << ", " << COL(c4) << "}}},\n"; + write << "{{{" << NUM(x) << ", " << NUM(y) << ", " << NUM(z) << "}, {" << NUM(tc1) << ", " << NUM(tc2) << "}, {" + << COL(c1) << ", " << COL(c2) << ", " << COL(c3) << ", " << COL(c4) << "}}},\n"; } write << "};\n"; return offset + vtx.size() * sizeof(CourseVtx); } -ExportResult MK64::CourseVtxBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::CourseVtxBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto vtx = std::static_pointer_cast<CourseVtxData>(raw); auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::CourseVertex, 0); - writer.Write((uint32_t) vtx->mVtxs.size()); - for(auto v : vtx->mVtxs) { + writer.Write((uint32_t)vtx->mVtxs.size()); + for (auto v : vtx->mVtxs) { writer.Write(v.ob[0]); writer.Write(v.ob[1]); writer.Write(v.ob[2]); @@ -75,7 +79,8 @@ ExportResult MK64::CourseVtxBinaryExporter::Export(std::ostream &write, std::sha return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> MK64::CourseVtxFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> MK64::CourseVtxFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto count = GetSafeNode<size_t>(node, "count"); auto [_, segment] = Decompressor::AutoDecode(node, buffer, count * sizeof(CourseVtx)); @@ -87,7 +92,7 @@ std::optional<std::shared_ptr<IParsedData>> MK64::CourseVtxFactory::parse(std::v reader.SetEndianness(Torch::Endianness::Big); std::vector<VtxRaw> vertices; - for(size_t i = 0; i < actualCount; i++) { + for (size_t i = 0; i < actualCount; i++) { auto x = reader.ReadInt16(); auto y = reader.ReadInt16(); auto z = reader.ReadInt16(); @@ -101,9 +106,8 @@ std::optional<std::shared_ptr<IParsedData>> MK64::CourseVtxFactory::parse(std::v uint16_t flags = cn1 & 3; flags |= (cn2 << 2) & 0xC; - vertices.push_back(VtxRaw({ - {x, y, z}, flags, {tc1, tc2}, {(uint8_t)(cn1 & 0xfc), (uint8_t)(cn2 & 0xfc), cn3, 0xff} - })); + vertices.push_back( + VtxRaw({ { x, y, z }, flags, { tc1, tc2 }, { (uint8_t)(cn1 & 0xfc), (uint8_t)(cn2 & 0xfc), cn3, 0xff } })); } return std::make_shared<VtxData>(vertices); diff --git a/src/factories/mk64/DrivingBehaviour.cpp b/src/factories/mk64/DrivingBehaviour.cpp index 5fb0391..5c83a0f 100644 --- a/src/factories/mk64/DrivingBehaviour.cpp +++ b/src/factories/mk64/DrivingBehaviour.cpp @@ -7,10 +7,12 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) std::dec << std::setfill(' ') << std::setw(3) << c -ExportResult MK64::DrivingBehaviourHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MK64::DrivingBehaviourHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -19,7 +21,9 @@ ExportResult MK64::DrivingBehaviourHeaderExporter::Export(std::ostream &write, s return std::nullopt; } -ExportResult MK64::DrivingBehaviourCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::DrivingBehaviourCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto bhv = std::static_pointer_cast<DrivingData>(raw); const auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -37,8 +41,7 @@ ExportResult MK64::DrivingBehaviourCodeExporter::Export(std::ostream &write, std write << "CPUBehaviour " << symbol << "[] = {\n"; - - for(auto b : bhv->mBhvs) { + for (auto b : bhv->mBhvs) { auto w1 = b.waypoint1; auto w2 = b.waypoint2; auto id = b.bhv; @@ -58,13 +61,15 @@ ExportResult MK64::DrivingBehaviourCodeExporter::Export(std::ostream &write, std return offset + bhv->mBhvs.size() * sizeof(BhvRaw); } -ExportResult MK64::DrivingBehaviourBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::DrivingBehaviourBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto bhv = std::static_pointer_cast<DrivingData>(raw); auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::DrivingBehaviour, 0); - writer.Write((uint32_t) bhv->mBhvs.size()); - for(auto b : bhv->mBhvs) { + writer.Write((uint32_t)bhv->mBhvs.size()); + for (auto b : bhv->mBhvs) { writer.Write(b.waypoint1); writer.Write(b.waypoint2); writer.Write(b.bhv); @@ -74,19 +79,20 @@ ExportResult MK64::DrivingBehaviourBinaryExporter::Export(std::ostream &write, s return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> MK64::DrivingBehaviourFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> MK64::DrivingBehaviourFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, segment.size); reader.SetEndianness(Torch::Endianness::Big); std::vector<BhvRaw> behaviours; - while(1) { + while (1) { auto w1 = reader.ReadInt16(); auto w2 = reader.ReadInt16(); auto id = reader.ReadInt32(); - behaviours.push_back( BhvRaw( {w1, w2, id} ) ); + behaviours.push_back(BhvRaw({ w1, w2, id })); // Magic number for ending of array if ((w1 == -1) && (w2 == -1)) { diff --git a/src/factories/mk64/ItemCurve.cpp b/src/factories/mk64/ItemCurve.cpp index 017ffb8..0e03445 100644 --- a/src/factories/mk64/ItemCurve.cpp +++ b/src/factories/mk64/ItemCurve.cpp @@ -7,10 +7,11 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) "0x" << std::hex << std::setw(2) << std::setfill('0') << c -ExportResult MK64::ItemCurveHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MK64::ItemCurveHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -19,19 +20,19 @@ ExportResult MK64::ItemCurveHeaderExporter::Export(std::ostream &write, std::sha return std::nullopt; } -ExportResult MK64::ItemCurveCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::ItemCurveCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto items = std::static_pointer_cast<ItemCurveData>(raw)->mItems; const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); - const auto searchTable = Companion::Instance->SearchTable(offset); - if(searchTable.has_value()){ + if (searchTable.has_value()) { const auto [name, start, end, mode, index_size] = searchTable.value(); // We will ignore the overriden index_size for now... - if(start == offset){ + if (start == offset) { write << GetSafeNode<std::string>(node, "ctype", "u8") << " " << name << "[][" << items.size() << "] = {\n"; } @@ -48,7 +49,7 @@ ExportResult MK64::ItemCurveCodeExporter::Export(std::ostream &write, std::share } write << "\n" << fourSpaceTab << "},\n"; - if(end == offset){ + if (end == offset) { write << "};\n\n"; } @@ -74,12 +75,15 @@ ExportResult MK64::ItemCurveCodeExporter::Export(std::ostream &write, std::share return offset + items.size() * sizeof(uint8_t); } -ExportResult MK64::ItemCurveBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { - throw std::runtime_error("Decomp ItemCurve is only implemented in decomp.\nuk64 and port use a new system for ease of modding and bug fixes."); +ExportResult MK64::ItemCurveBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { + throw std::runtime_error("Decomp ItemCurve is only implemented in decomp.\nuk64 and port use a new system for ease " + "of modding and bug fixes."); return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> MK64::ItemCurveFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> MK64::ItemCurveFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, (10 * 10) * sizeof(uint8_t)); @@ -87,7 +91,7 @@ std::optional<std::shared_ptr<IParsedData>> MK64::ItemCurveFactory::parse(std::v std::vector<uint8_t> items; // Each array is size of 10*10. - for(size_t i = 0; i < 10*10; i++) { + for (size_t i = 0; i < 10 * 10; i++) { items.push_back(reader.ReadUByte()); } diff --git a/src/factories/mk64/PackedDisplayListFactory.cpp b/src/factories/mk64/PackedDisplayListFactory.cpp index a49b1a4..abf79ef 100644 --- a/src/factories/mk64/PackedDisplayListFactory.cpp +++ b/src/factories/mk64/PackedDisplayListFactory.cpp @@ -191,12 +191,10 @@ #define BOWTIE_VAL 0 -#define gsSPTexture(s, t, level, tile, on) \ - { \ - (_SHIFTL(G_TEXTURE, 24, 8) | _SHIFTL(BOWTIE_VAL, 16, 8) | _SHIFTL((level), 11, 3) | _SHIFTL((tile), 8, 3) | \ - _SHIFTL((on), 0, 8)), \ - (_SHIFTL((s), 16, 16) | _SHIFTL((t), 0, 16)) \ - } +#define gsSPTexture(s, t, level, tile, on) \ + { (_SHIFTL(G_TEXTURE, 24, 8) | _SHIFTL(BOWTIE_VAL, 16, 8) | _SHIFTL((level), 11, 3) | _SHIFTL((tile), 8, 3) | \ + _SHIFTL((on), 0, 8)), \ + (_SHIFTL((s), 16, 16) | _SHIFTL((t), 0, 16)) } #define GCCc0w0(saRGB0, mRGB0, saA0, mA0) \ (_SHIFTL((saRGB0), 20, 4) | _SHIFTL((mRGB0), 15, 5) | _SHIFTL((saA0), 12, 3) | _SHIFTL((mA0), 9, 3)) @@ -216,9 +214,9 @@ _SHIFTL(G_SETCOMBINE, 24, 8) | _SHIFTL(GCCc0w0(G_CCMUX_##a0, G_CCMUX_##c0, G_ACMUX_##Aa0, G_ACMUX_##Ac0) | \ GCCc1w0(G_CCMUX_##a1, G_CCMUX_##c1), \ 0, 24), \ - (unsigned int) (GCCc0w1(G_CCMUX_##b0, G_CCMUX_##d0, G_ACMUX_##Ab0, G_ACMUX_##Ad0) | \ - GCCc1w1(G_CCMUX_##b1, G_ACMUX_##Aa1, G_ACMUX_##Ac1, G_CCMUX_##d1, G_ACMUX_##Ab1, \ - G_ACMUX_##Ad1)) \ + (unsigned int)(GCCc0w1(G_CCMUX_##b0, G_CCMUX_##d0, G_ACMUX_##Ab0, G_ACMUX_##Ad0) | \ + GCCc1w1(G_CCMUX_##b1, G_ACMUX_##Aa1, G_ACMUX_##Ac1, G_CCMUX_##d1, G_ACMUX_##Ab1, \ + G_ACMUX_##Ad1)) \ } \ } @@ -231,9 +229,9 @@ #define gsDPSetCombineMode(a, b) gsDPSetCombineLERP(a, b) #endif -#define gsSPSetOtherMode(cmd, sft, len, data) \ - { \ - { _SHIFTL(cmd, 24, 8) | _SHIFTL(sft, 8, 8) | _SHIFTL(len, 0, 8), (unsigned int) (data) } \ +#define gsSPSetOtherMode(cmd, sft, len, data) \ + { \ + { _SHIFTL(cmd, 24, 8) | _SHIFTL(sft, 8, 8) | _SHIFTL(len, 0, 8), (unsigned int)(data) } \ } #define gsDPSetRenderMode(c0, c1) gsSPSetOtherMode(G_SETOTHERMODE_L, G_MDSFT_RENDERMODE, 29, (c0) | (c1)) @@ -307,9 +305,9 @@ #define G_RM_AA_ZB_XLU_DECAL RM_AA_ZB_XLU_DECAL(1) #define G_RM_AA_ZB_XLU_DECAL2 RM_AA_ZB_XLU_DECAL(2) -#define gsSPGeometryMode(c, s) \ - { \ - { (_SHIFTL(G_GEOMETRYMODE, 24, 8) | _SHIFTL(~(u32) (c), 0, 24)), (u32) (s) } \ +#define gsSPGeometryMode(c, s) \ + { \ + { (_SHIFTL(G_GEOMETRYMODE, 24, 8) | _SHIFTL(~(u32)(c), 0, 24)), (u32)(s) } \ } #define G_TEXTURE_ENABLE 0x00000002 /* Microcode use only */ @@ -317,14 +315,14 @@ #define G_CULL_FRONT 0x00001000 #define G_CULL_BACK 0x00002000 #define G_CULL_BOTH 0x00003000 /* To make code cleaner */ -#define gsSPSetGeometryMode(word) \ - { \ - { _SHIFTL(G_SETGEOMETRYMODE, 24, 8), (unsigned int) (word) } \ +#define gsSPSetGeometryMode(word) \ + { \ + { _SHIFTL(G_SETGEOMETRYMODE, 24, 8), (unsigned int)(word) } \ } -#define gsSPClearGeometryMode(word) \ - { \ - { _SHIFTL(G_CLEARGEOMETRYMODE, 24, 8), (unsigned int) (word) } \ +#define gsSPClearGeometryMode(word) \ + { \ + { _SHIFTL(G_CLEARGEOMETRYMODE, 24, 8), (unsigned int)(word) } \ } #define gsSPCullDisplayList(vstart, vend) \ { \ @@ -347,40 +345,33 @@ #define G_MWO_NUMLIGHT 0x00 -#define gsImmp21(c, p0, p1, dat) \ - { _SHIFTL((c), 24, 8) | _SHIFTL((p0), 8, 16) | _SHIFTL((p1), 0, 8), (uintptr_t)(dat) } +#define gsImmp21(c, p0, p1, dat) { _SHIFTL((c), 24, 8) | _SHIFTL((p0), 8, 16) | _SHIFTL((p1), 0, 8), (uintptr_t)(dat) } #define gsMoveWd(index, offset, data) gsImmp21(G_MOVEWORD, offset, index, data) #define gsSPNumLights(n) gsMoveWd(G_MW_NUMLIGHT, G_MWO_NUMLIGHT, NUML(n)) -#define gsDPSetTile(fmt, siz, line, tmem, tile, palette, cmt, maskt, shiftt, cms, masks, shifts) \ - { \ - (_SHIFTL(G_SETTILE, 24, 8) | _SHIFTL(fmt, 21, 3) | _SHIFTL(siz, 19, 2) | _SHIFTL(line, 9, 9) | \ - _SHIFTL(tmem, 0, 9)), \ - (_SHIFTL(tile, 24, 3) | _SHIFTL(palette, 20, 4) | _SHIFTL(cmt, 18, 2) | _SHIFTL(maskt, 14, 4) | \ - _SHIFTL(shiftt, 10, 4) | _SHIFTL(cms, 8, 2) | _SHIFTL(masks, 4, 4) | _SHIFTL(shifts, 0, 4)) \ - } +#define gsDPSetTile(fmt, siz, line, tmem, tile, palette, cmt, maskt, shiftt, cms, masks, shifts) \ + { (_SHIFTL(G_SETTILE, 24, 8) | _SHIFTL(fmt, 21, 3) | _SHIFTL(siz, 19, 2) | _SHIFTL(line, 9, 9) | \ + _SHIFTL(tmem, 0, 9)), \ + (_SHIFTL(tile, 24, 3) | _SHIFTL(palette, 20, 4) | _SHIFTL(cmt, 18, 2) | _SHIFTL(maskt, 14, 4) | \ + _SHIFTL(shiftt, 10, 4) | _SHIFTL(cms, 8, 2) | _SHIFTL(masks, 4, 4) | _SHIFTL(shifts, 0, 4)) } #define G_TX_RENDERTILE 0 -#define gsDPLoadTileGeneric(c, tile, uls, ult, lrs, lrt) \ - { \ - _SHIFTL(c, 24, 8) | _SHIFTL(uls, 12, 12) | _SHIFTL(ult, 0, 12), \ - _SHIFTL(tile, 24, 3) | _SHIFTL(lrs, 12, 12) | _SHIFTL(lrt, 0, 12) \ - } +#define gsDPLoadTileGeneric(c, tile, uls, ult, lrs, lrt) \ + { _SHIFTL(c, 24, 8) | _SHIFTL(uls, 12, 12) | _SHIFTL(ult, 0, 12), \ + _SHIFTL(tile, 24, 3) | _SHIFTL(lrs, 12, 12) | _SHIFTL(lrt, 0, 12) } #define gsDPSetTileSize(t, uls, ult, lrs, lrt) gsDPLoadTileGeneric(G_SETTILESIZE, t, uls, ult, lrs, lrt) -#define gsDma1p(c, s, l, p) \ - { (_SHIFTL((c), 24, 8) | _SHIFTL((p), 16, 8) | _SHIFTL((l), 0, 16)), (uintptr_t)(s) } -#define gsSPVertex(v, n, v0) gsDma1p(G_VTX, (v), ((n) << 10) | (0x10 * (n)-1), (v0)*2) +#define gsDma1p(c, s, l, p) { (_SHIFTL((c), 24, 8) | _SHIFTL((p), 16, 8) | _SHIFTL((l), 0, 16)), (uintptr_t)(s) } +#define gsSPVertex(v, n, v0) gsDma1p(G_VTX, (v), ((n) << 10) | (0x10 * (n) - 1), (v0) * 2) -#define __gsSP1Triangle_w1(v0, v1, v2) (_SHIFTL((v0)*2, 16, 8) | _SHIFTL((v1)*2, 8, 8) | _SHIFTL((v2)*2, 0, 8)) +#define __gsSP1Triangle_w1(v0, v1, v2) (_SHIFTL((v0) * 2, 16, 8) | _SHIFTL((v1) * 2, 8, 8) | _SHIFTL((v2) * 2, 0, 8)) #define __gsSP1Triangle_w1f(v0, v1, v2, flag) \ (((flag) == 0) ? __gsSP1Triangle_w1(v0, v1, v2) \ : ((flag) == 1) ? __gsSP1Triangle_w1(v1, v2, v0) \ : __gsSP1Triangle_w1(v2, v0, v1)) -#define gsSP1Triangle(v0, v1, v2, flag) \ - { _SHIFTL(G_TRI1, 24, 8), __gsSP1Triangle_w1f(v0, v1, v2, flag) } +#define gsSP1Triangle(v0, v1, v2, flag) { _SHIFTL(G_TRI1, 24, 8), __gsSP1Triangle_w1f(v0, v1, v2, flag) } #define gsSP2Triangles(v00, v01, v02, flag0, v10, v11, v12, flag1) \ { (_SHIFTL(G_TRI2, 24, 8) | __gsSP1Triangle_w1f(v00, v01, v02, flag0)), __gsSP1Triangle_w1f(v10, v11, v12, flag1) } @@ -389,17 +380,15 @@ #define gsSPDisplayList(dl) gsDma1p(G_DL, dl, 0, G_DL_PUSH) #define gsSetImage(cmd, fmt, siz, width, i) \ - { _SHIFTL(cmd, 24, 8) | _SHIFTL(fmt, 21, 3) | _SHIFTL(siz, 19, 2) | _SHIFTL((width)-1, 0, 12), (uintptr_t)(i) } + { _SHIFTL(cmd, 24, 8) | _SHIFTL(fmt, 21, 3) | _SHIFTL(siz, 19, 2) | _SHIFTL((width) - 1, 0, 12), (uintptr_t)(i) } #define gsDPSetTextureImage(f, s, w, i) gsSetImage(G_SETTIMG, f, s, w, i) #define G_TX_LDBLK_MAX_TXL 4095 -#define gsDPLoadBlock(tile, uls, ult, lrs, dxt) \ - { \ - (_SHIFTL(G_LOADBLOCK, 24, 8) | _SHIFTL(uls, 12, 12) | _SHIFTL(ult, 0, 12)), \ - (_SHIFTL(tile, 24, 3) | _SHIFTL((MIN(lrs, G_TX_LDBLK_MAX_TXL)), 12, 12) | _SHIFTL(dxt, 0, 12)) \ - } +#define gsDPLoadBlock(tile, uls, ult, lrs, dxt) \ + { (_SHIFTL(G_LOADBLOCK, 24, 8) | _SHIFTL(uls, 12, 12) | _SHIFTL(ult, 0, 12)), \ + (_SHIFTL(tile, 24, 3) | _SHIFTL((MIN(lrs, G_TX_LDBLK_MAX_TXL)), 12, 12) | _SHIFTL(dxt, 0, 12)) } #define G_TX_NOMIRROR 0 #define G_TX_WRAP 0 @@ -409,43 +398,43 @@ // Packed opcodes (alignés avec src/racing/memory.c) enum PackedOp : uint8_t { - PG_LIGHTS_0 = 0x00, // 0..0x14 mappés sur unpack_lights côté runtime - PG_SETCOMBINE_CC_MODULATERGBA = 0x15, + PG_LIGHTS_0 = 0x00, // 0..0x14 mappés sur unpack_lights côté runtime + PG_SETCOMBINE_CC_MODULATERGBA = 0x15, PG_SETCOMBINE_CC_MODULATERGBDECALA = 0x16, - PG_SETCOMBINE_CC_SHADE = 0x17, - PG_RMODE_OPA = 0x18, - PG_RMODE_TEXEDGE = 0x19, - PG_TILECFG_A = 0x1A, - PG_TILECFG_B = 0x1B, - PG_TILECFG_C = 0x1C, - PG_TILECFG_D = 0x1D, - PG_TILECFG_E = 0x1E, - PG_TILECFG_F = 0x1F, - PG_TIMG_LOADBLOCK_0 = 0x20, - PG_TIMG_LOADBLOCK_1 = 0x21, - PG_TIMG_LOADBLOCK_2 = 0x22, - PG_TIMG_LOADBLOCK_3 = 0x23, - PG_TIMG_LOADBLOCK_4 = 0x24, - PG_TIMG_LOADBLOCK_5 = 0x25, - PG_TEXTURE_ON = 0x26, - PG_TEXTURE_OFF = 0x27, - PG_VTX1 = 0x28, - PG_TRI1 = 0x29, - PG_ENDDL = 0x2A, - PG_DL = 0x2B, - PG_TILECFG_G = 0x2C, - PG_CULLDL = 0x2D, - PG_SETCOMBINE_ALT = 0x2E, - PG_RMODE_XLU = 0x2F, - PG_SPLINE3D = 0x30, - PG_VTX_BASE = 0x32, // 0x33..0x52 VTX2 variants - PG_SETCOMBINE_CC_DECALRGBA= 0x53, - PG_RMODE_OPA_DECAL = 0x54, - PG_RMODE_XLU_DECAL = 0x55, - PG_SETGEOMETRYMODE = 0x56, - PG_CLEARGEOMETRYMODE = 0x57, - PG_TRI2 = 0x58, - PG_EOF = 0xFF, + PG_SETCOMBINE_CC_SHADE = 0x17, + PG_RMODE_OPA = 0x18, + PG_RMODE_TEXEDGE = 0x19, + PG_TILECFG_A = 0x1A, + PG_TILECFG_B = 0x1B, + PG_TILECFG_C = 0x1C, + PG_TILECFG_D = 0x1D, + PG_TILECFG_E = 0x1E, + PG_TILECFG_F = 0x1F, + PG_TIMG_LOADBLOCK_0 = 0x20, + PG_TIMG_LOADBLOCK_1 = 0x21, + PG_TIMG_LOADBLOCK_2 = 0x22, + PG_TIMG_LOADBLOCK_3 = 0x23, + PG_TIMG_LOADBLOCK_4 = 0x24, + PG_TIMG_LOADBLOCK_5 = 0x25, + PG_TEXTURE_ON = 0x26, + PG_TEXTURE_OFF = 0x27, + PG_VTX1 = 0x28, + PG_TRI1 = 0x29, + PG_ENDDL = 0x2A, + PG_DL = 0x2B, + PG_TILECFG_G = 0x2C, + PG_CULLDL = 0x2D, + PG_SETCOMBINE_ALT = 0x2E, + PG_RMODE_XLU = 0x2F, + PG_SPLINE3D = 0x30, + PG_VTX_BASE = 0x32, // 0x33..0x52 VTX2 variants + PG_SETCOMBINE_CC_DECALRGBA = 0x53, + PG_RMODE_OPA_DECAL = 0x54, + PG_RMODE_XLU_DECAL = 0x55, + PG_SETGEOMETRYMODE = 0x56, + PG_CLEARGEOMETRYMODE = 0x57, + PG_TRI2 = 0x58, + PG_EOF = 0xFF, }; std::string opcode_to_string(uint8_t op) { @@ -456,52 +445,93 @@ std::string opcode_to_string(uint8_t op) { return "PG_VTX_" + std::to_string(op - PG_VTX_BASE); } switch (op) { - case PG_SETCOMBINE_CC_MODULATERGBA: return "PG_SETCOMBINE_CC_MODULATERGBA"; - case PG_SETCOMBINE_CC_MODULATERGBDECALA: return "PG_SETCOMBINE_CC_MODULATERGBDECALA"; - case PG_SETCOMBINE_CC_SHADE: return "PG_SETCOMBINE_CC_SHADE"; - case PG_RMODE_OPA: return "PG_RMODE_OPA"; - case PG_RMODE_TEXEDGE: return "PG_RMODE_TEXEDGE"; - case PG_TILECFG_A: return "PG_TILECFG_A"; - case PG_TILECFG_B: return "PG_TILECFG_B"; - case PG_TILECFG_C: return "PG_TILECFG_C"; - case PG_TILECFG_D: return "PG_TILECFG_D"; - case PG_TILECFG_E: return "PG_TILECFG_E"; - case PG_TILECFG_F: return "PG_TILECFG_F"; - case PG_TIMG_LOADBLOCK_0: return "PG_TIMG_LOADBLOCK_0"; - case PG_TIMG_LOADBLOCK_1: return "PG_TIMG_LOADBLOCK_1"; - case PG_TIMG_LOADBLOCK_2: return "PG_TIMG_LOADBLOCK_2"; - case PG_TIMG_LOADBLOCK_3: return "PG_TIMG_LOADBLOCK_3"; - case PG_TIMG_LOADBLOCK_4: return "PG_TIMG_LOADBLOCK_4"; - case PG_TIMG_LOADBLOCK_5: return "PG_TIMG_LOADBLOCK_5"; - case PG_TEXTURE_ON: return "PG_TEXTURE_ON"; - case PG_TEXTURE_OFF: return "PG_TEXTURE_OFF"; - case PG_VTX1: return "PG_VTX1"; - case PG_TRI1: return "PG_TRI1"; - case PG_ENDDL: return "PG_ENDDL"; - case PG_DL: return "PG_DL"; - case PG_TILECFG_G: return "PG_TILECFG_G"; - case PG_CULLDL: return "PG_CULLDL"; - case PG_SETCOMBINE_ALT: return "PG_SETCOMBINE_ALT"; - case PG_RMODE_XLU: return "PG_RMODE_XLU"; - case PG_SPLINE3D: return "PG_SPLINE3D"; - case PG_SETCOMBINE_CC_DECALRGBA: return "PG_SETCOMBINE_CC_DECALRGBA"; - case PG_RMODE_OPA_DECAL: return "PG_RMODE_OPA_DECAL"; - case PG_RMODE_XLU_DECAL: return "PG_RMODE_XLU_DECAL"; - case PG_SETGEOMETRYMODE: return "PG_SETGEOMETRYMODE"; - case PG_CLEARGEOMETRYMODE: return "PG_CLEARGEOMETRYMODE"; - case PG_TRI2: return "PG_TRI2"; - case PG_EOF: return "PG_EOF"; - default: return "PG_UNKNOWN_" + std::to_string(op); + case PG_SETCOMBINE_CC_MODULATERGBA: + return "PG_SETCOMBINE_CC_MODULATERGBA"; + case PG_SETCOMBINE_CC_MODULATERGBDECALA: + return "PG_SETCOMBINE_CC_MODULATERGBDECALA"; + case PG_SETCOMBINE_CC_SHADE: + return "PG_SETCOMBINE_CC_SHADE"; + case PG_RMODE_OPA: + return "PG_RMODE_OPA"; + case PG_RMODE_TEXEDGE: + return "PG_RMODE_TEXEDGE"; + case PG_TILECFG_A: + return "PG_TILECFG_A"; + case PG_TILECFG_B: + return "PG_TILECFG_B"; + case PG_TILECFG_C: + return "PG_TILECFG_C"; + case PG_TILECFG_D: + return "PG_TILECFG_D"; + case PG_TILECFG_E: + return "PG_TILECFG_E"; + case PG_TILECFG_F: + return "PG_TILECFG_F"; + case PG_TIMG_LOADBLOCK_0: + return "PG_TIMG_LOADBLOCK_0"; + case PG_TIMG_LOADBLOCK_1: + return "PG_TIMG_LOADBLOCK_1"; + case PG_TIMG_LOADBLOCK_2: + return "PG_TIMG_LOADBLOCK_2"; + case PG_TIMG_LOADBLOCK_3: + return "PG_TIMG_LOADBLOCK_3"; + case PG_TIMG_LOADBLOCK_4: + return "PG_TIMG_LOADBLOCK_4"; + case PG_TIMG_LOADBLOCK_5: + return "PG_TIMG_LOADBLOCK_5"; + case PG_TEXTURE_ON: + return "PG_TEXTURE_ON"; + case PG_TEXTURE_OFF: + return "PG_TEXTURE_OFF"; + case PG_VTX1: + return "PG_VTX1"; + case PG_TRI1: + return "PG_TRI1"; + case PG_ENDDL: + return "PG_ENDDL"; + case PG_DL: + return "PG_DL"; + case PG_TILECFG_G: + return "PG_TILECFG_G"; + case PG_CULLDL: + return "PG_CULLDL"; + case PG_SETCOMBINE_ALT: + return "PG_SETCOMBINE_ALT"; + case PG_RMODE_XLU: + return "PG_RMODE_XLU"; + case PG_SPLINE3D: + return "PG_SPLINE3D"; + case PG_SETCOMBINE_CC_DECALRGBA: + return "PG_SETCOMBINE_CC_DECALRGBA"; + case PG_RMODE_OPA_DECAL: + return "PG_RMODE_OPA_DECAL"; + case PG_RMODE_XLU_DECAL: + return "PG_RMODE_XLU_DECAL"; + case PG_SETGEOMETRYMODE: + return "PG_SETGEOMETRYMODE"; + case PG_CLEARGEOMETRYMODE: + return "PG_CLEARGEOMETRYMODE"; + case PG_TRI2: + return "PG_TRI2"; + case PG_EOF: + return "PG_EOF"; + default: + return "PG_UNKNOWN_" + std::to_string(op); } } static inline uint32_t ImmediateSize(uint8_t op) { switch (op) { - case PG_TRI1: return 2; // packed 2 bytes - case PG_TRI2: return 4; // packed 4 bytes (2 tris) - case PG_DL: return 2; // index - case PG_VTX1: return 4; // vtx1: 4 bytes - case PG_SPLINE3D: return 3; // spline3d: 3 bytes + case PG_TRI1: + return 2; // packed 2 bytes + case PG_TRI2: + return 4; // packed 4 bytes (2 tris) + case PG_DL: + return 2; // index + case PG_VTX1: + return 4; // vtx1: 4 bytes + case PG_SPLINE3D: + return 3; // spline3d: 3 bytes case PG_SETCOMBINE_CC_MODULATERGBA: case PG_SETCOMBINE_CC_MODULATERGBDECALA: case PG_SETCOMBINE_CC_SHADE: @@ -514,14 +544,14 @@ static inline uint32_t ImmediateSize(uint8_t op) { case PG_RMODE_XLU_DECAL: case PG_SETGEOMETRYMODE: case PG_CLEARGEOMETRYMODE: - return 0; // pas d’immediate dans notre format packé + return 0; // pas d’immediate dans notre format packé case PG_TIMG_LOADBLOCK_0: case PG_TIMG_LOADBLOCK_1: case PG_TIMG_LOADBLOCK_2: case PG_TIMG_LOADBLOCK_3: case PG_TIMG_LOADBLOCK_4: case PG_TIMG_LOADBLOCK_5: - return 3; // fmt-dep tex, 3 bytes + return 3; // fmt-dep tex, 3 bytes case PG_TILECFG_A: case PG_TILECFG_B: case PG_TILECFG_C: @@ -529,7 +559,7 @@ static inline uint32_t ImmediateSize(uint8_t op) { case PG_TILECFG_E: case PG_TILECFG_F: case PG_TILECFG_G: - return 2; // 2 bytes + return 2; // 2 bytes default: // VTX2 banked range: 0x33..0x52 → 2 bytes if (op >= (uint8_t)(PG_VTX_BASE) && op <= (uint8_t)(PG_VTX_BASE + 0x20)) { @@ -544,7 +574,8 @@ static inline uint16_t RD16(const std::vector<uint8_t>& b, size_t i) { return (uint16_t)((b[i + 1] << 8) | b[i]); } -std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& data) { +std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& data) { auto [_, segment] = Decompressor::AutoDecode(data, buffer); std::vector<uint8_t> decoded(segment.data, segment.data + segment.size); @@ -564,7 +595,9 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: while (i < decoded.size()) { uint8_t op = decoded[i++]; // SPDLOG_INFO("PackedDListFactory: opcode 0x{:02X} ({})", op, opcode_to_string(op)); - if (op == PG_EOF) { break; } + if (op == PG_EOF) { + break; + } // LIGHTS: 0x00..0x14 if (op >= PG_LIGHTS_0 && op <= PG_LIGHTS_0 + 0x14) { @@ -579,7 +612,9 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: if (op >= (uint8_t)(PG_VTX_BASE + 0x01) && op <= (uint8_t)(PG_VTX_BASE + 0x20)) { // Mimic unpack_vtx2: banked variant encodes count in opcode - if (i + 2 > decoded.size()) { goto done; } + if (i + 2 > decoded.size()) { + goto done; + } uintptr_t vtxOff = RD16(decoded, i); i += 2; vtxOff *= 0x10; // bytes @@ -598,24 +633,26 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: switch (op) { case PG_VTX1: { // Mimic unpack_vtx1 - if (i + 4 > decoded.size()) { goto done; } + if (i + 4 > decoded.size()) { + goto done; + } uint8_t t0 = decoded[i++]; uint16_t vtxOff = ((uint16_t)decoded[i++] << 8) | t0; vtxOff *= 0x10; // bytes uint8_t b0 = decoded[i++]; uint8_t start = (uint8_t)(b0 & 0x3F); - + uint8_t b1 = decoded[i++]; uint8_t n = (uint8_t)(b1 & 0x3F); // G_VTX encoding matches DisplayListFactory exporter expectations - uint32_t w0 = (_SHIFTL(G_VTX, 24, 8) - | _SHIFTL((n * 2), 16, 8) - | ((start << 10) + ((0x10 * start) - 1))); - // Use segmented address style: segment 0x04 is vertex pool in runtime; here we keep raw offset so exporter can attempt resolution + uint32_t w0 = + (_SHIFTL(G_VTX, 24, 8) | _SHIFTL((n * 2), 16, 8) | ((start << 10) + ((0x10 * start) - 1))); + // Use segmented address style: segment 0x04 is vertex pool in runtime; here we keep raw offset so + // exporter can attempt resolution uint32_t w1 = vtxOff; // exporter will patch/resolve if possible - + emit(w0, w1); } break; case PG_TILECFG_A: @@ -626,16 +663,53 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: case PG_TILECFG_F: case PG_TILECFG_G: { // Mirror of unpack_tile_sync - if (i + 2 > decoded.size()) { goto done; } + if (i + 2 > decoded.size()) { + goto done; + } int width = 32, height = 32, fmt = 0, tmem = 0; switch (op) { - case PG_TILECFG_A: width = 32; height = 32; fmt = 0; tmem = 0; break; - case PG_TILECFG_B: width = 64; height = 32; fmt = 0; tmem = 0; break; - case PG_TILECFG_C: width = 32; height = 64; fmt = 0; tmem = 0; break; - case PG_TILECFG_D: width = 32; height = 32; fmt = 3; tmem = 0; break; - case PG_TILECFG_E: width = 64; height = 32; fmt = 3; tmem = 0; break; - case PG_TILECFG_F: width = 32; height = 64; fmt = 3; tmem = 0; break; - case PG_TILECFG_G: width = 32; height = 32; fmt = 0; tmem = 256; break; + case PG_TILECFG_A: + width = 32; + height = 32; + fmt = 0; + tmem = 0; + break; + case PG_TILECFG_B: + width = 64; + height = 32; + fmt = 0; + tmem = 0; + break; + case PG_TILECFG_C: + width = 32; + height = 64; + fmt = 0; + tmem = 0; + break; + case PG_TILECFG_D: + width = 32; + height = 32; + fmt = 3; + tmem = 0; + break; + case PG_TILECFG_E: + width = 64; + height = 32; + fmt = 3; + tmem = 0; + break; + case PG_TILECFG_F: + width = 32; + height = 64; + fmt = 3; + tmem = 0; + break; + case PG_TILECFG_G: + width = 32; + height = 32; + fmt = 0; + tmem = 256; + break; } const int sizBytes = G_IM_SIZ_16b_BYTES; // 2 const int line = (((width * 2) + 7) >> 3); @@ -654,9 +728,11 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: } // G_SETTILE - // uint32_t w0 = (_SHIFTL(G_SETTILE, 24, 8) | _SHIFTL(fmt, 21, 3) | _SHIFTL(G_IM_SIZ_16b_BYTES, 19, 2) | _SHIFTL(line, 9, 9) | _SHIFTL(tmem, 0, 9)); - // uint32_t w1 = (_SHIFTL(cmt, 18, 3) | _SHIFTL(maskt, 14, 4) | _SHIFTL(cms, 8, 3) | _SHIFTL(masks, 4, 4)); - N64Gfx macro = gsDPSetTile(fmt, G_IM_SIZ_16b, line, tmem, G_TX_RENDERTILE, 0, cmt, maskt, 0, cms, masks, 0); + // uint32_t w0 = (_SHIFTL(G_SETTILE, 24, 8) | _SHIFTL(fmt, 21, 3) | _SHIFTL(G_IM_SIZ_16b_BYTES, 19, 2) | + // _SHIFTL(line, 9, 9) | _SHIFTL(tmem, 0, 9)); uint32_t w1 = (_SHIFTL(cmt, 18, 3) | _SHIFTL(maskt, 14, + // 4) | _SHIFTL(cms, 8, 3) | _SHIFTL(masks, 4, 4)); + N64Gfx macro = + gsDPSetTile(fmt, G_IM_SIZ_16b, line, tmem, G_TX_RENDERTILE, 0, cmt, maskt, 0, cms, masks, 0); emit(macro.words.w0, macro.words.w1); // G_SETTILESIZE @@ -673,15 +749,41 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: case PG_TIMG_LOADBLOCK_4: case PG_TIMG_LOADBLOCK_5: { // Mirror of unpack_tile_load_sync - if (i + 3 > decoded.size()) { goto done; } + if (i + 3 > decoded.size()) { + goto done; + } uint32_t width = 32, height = 32, fmt = 0; switch (op) { - case PG_TIMG_LOADBLOCK_0: width = 32; height = 32; fmt = 0; break; - case PG_TIMG_LOADBLOCK_1: width = 64; height = 32; fmt = 0; break; - case PG_TIMG_LOADBLOCK_2: width = 32; height = 64; fmt = 0; break; - case PG_TIMG_LOADBLOCK_3: width = 32; height = 32; fmt = 3; break; - case PG_TIMG_LOADBLOCK_4: width = 64; height = 32; fmt = 3; break; - case PG_TIMG_LOADBLOCK_5: width = 32; height = 64; fmt = 3; break; + case PG_TIMG_LOADBLOCK_0: + width = 32; + height = 32; + fmt = 0; + break; + case PG_TIMG_LOADBLOCK_1: + width = 64; + height = 32; + fmt = 0; + break; + case PG_TIMG_LOADBLOCK_2: + width = 32; + height = 64; + fmt = 0; + break; + case PG_TIMG_LOADBLOCK_3: + width = 32; + height = 32; + fmt = 3; + break; + case PG_TIMG_LOADBLOCK_4: + width = 64; + height = 32; + fmt = 3; + break; + case PG_TIMG_LOADBLOCK_5: + width = 32; + height = 64; + fmt = 3; + break; } uint32_t offset = ((uint32_t)decoded[i++]) << 11; // index << 11 @@ -693,7 +795,7 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: // uint32_t w0 = (_SHIFTL(G_SETTIMG, 24, 8) | _SHIFTL(fmt, 21, 3) | _SHIFTL(siz, 19, 2)); N64Gfx macro = gsDPSetTextureImage(fmt, siz, 1, 0x05000000 | offset); - + emit(macro.words.w0, macro.words.w1); // gsDPTileSync @@ -705,7 +807,8 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: // G_SETTILE (fmt/siz/tmem) + tile en w1 // w0 = (_SHIFTL(G_SETTILE, 24, 8) | _SHIFTL(fmt, 21, 3) | _SHIFTL(siz, 19, 2) | _SHIFTL(tmem, 0, 9)); // uint32_t w1 = _SHIFTL(tile, 24, 3); - macro = gsDPSetTile(fmt, siz, 0, tmem, tile, 0, G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMASK, G_TX_NOLOD); + macro = gsDPSetTile(fmt, siz, 0, tmem, tile, 0, G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMASK, G_TX_NOLOD, + G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMASK, G_TX_NOLOD); emit(macro.words.w0, macro.words.w1); // gsDPLoadSync @@ -785,8 +888,11 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: emit(macro.words.w0, macro.words.w1); } break; case PG_TRI1: { - if (i + 2 > decoded.size()) { goto done; } - uint16_t c = RD16(decoded, i); i += 2; + if (i + 2 > decoded.size()) { + goto done; + } + uint16_t c = RD16(decoded, i); + i += 2; uint8_t a = (c & 0x1F); uint8_t b = ((c >> 5) & 0x1F); uint8_t d = ((c >> 10) & 0x1F); @@ -794,9 +900,13 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: emit(macro.words.w0, macro.words.w1); } break; case PG_TRI2: { - if (i + 4 > decoded.size()) { goto done; } - uint16_t c0 = RD16(decoded, i); i += 2; - uint16_t c1 = RD16(decoded, i); i += 2; + if (i + 4 > decoded.size()) { + goto done; + } + uint16_t c0 = RD16(decoded, i); + i += 2; + uint16_t c1 = RD16(decoded, i); + i += 2; uint8_t a0 = (c0 & 0x1F); uint8_t b0 = ((c0 >> 5) & 0x1F); uint8_t d0 = ((c0 >> 10) & 0x1F); @@ -808,7 +918,9 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: } break; case PG_SPLINE3D: { // Mimic unpack_spline_3D: map packed 3 bytes into a QUAD macro layout - if (i + 3 > decoded.size()) { goto done; } + if (i + 3 > decoded.size()) { + goto done; + } uint8_t b0 = decoded[i++]; uint8_t b1 = decoded[i++]; uint8_t b2 = decoded[i++]; @@ -821,30 +933,33 @@ std::optional<std::shared_ptr<IParsedData>> MK64::PackedDListFactory::parse(std: uint8_t a0 = (uint8_t)(((b1 >> 7) & 0x1) | ((b2 & 0xF) * 2)); uint32_t w0 = _SHIFTL(G_QUAD, 24, 8); - uint32_t w1 = (_SHIFTL((uint8_t)(a0 * 2), 24, 8) - | _SHIFTL((uint8_t)(t0 * 2), 16, 8) - | _SHIFTL((uint8_t)(a3 * 2), 8, 8) - | _SHIFTL((uint8_t)(a2 * 2), 0, 8)); + uint32_t w1 = (_SHIFTL((uint8_t)(a0 * 2), 24, 8) | _SHIFTL((uint8_t)(t0 * 2), 16, 8) | + _SHIFTL((uint8_t)(a3 * 2), 8, 8) | _SHIFTL((uint8_t)(a2 * 2), 0, 8)); emit(w0, w1); } break; case PG_DL: { - if (i + 2 > decoded.size()) { goto done; } - uint16_t idx = RD16(decoded, i); i += 2; + if (i + 2 > decoded.size()) { + goto done; + } + uint16_t idx = RD16(decoded, i); + i += 2; // uint32_t w0 = (_SHIFTL(G_DL, 24, 8)); // push - // // Encode as segmented address into segment 0x07 so exporter treats it as an index into packed DL buffer - // uint32_t w1 = 0x07000000u | (idx * 8); - N64Gfx macro = gsSPDisplayList(0x07000000u|(idx*8)); + // // Encode as segmented address into segment 0x07 so exporter treats it as an index into packed DL + // buffer uint32_t w1 = 0x07000000u | (idx * 8); + N64Gfx macro = gsSPDisplayList(0x07000000u | (idx * 8)); emit(macro.words.w0, macro.words.w1); } break; case PG_ENDDL: emit(_SHIFTL(G_ENDDL, 24, 8), 0); SPDLOG_INFO("Size of packed DL: 0x{:X}", i - start); goto done; - default: { + default: { // Skip immediates for any known opcode (tilecfg, timg, spline, etc.) uint32_t imm = ImmediateSize(op); if (imm) { - if (i + imm > decoded.size()) { goto done; } + if (i + imm > decoded.size()) { + goto done; + } i += imm; } // Other 1-byte ops (combine, render, texture on/off, geom modes) produce no gfx here diff --git a/src/factories/mk64/Paths.cpp b/src/factories/mk64/Paths.cpp index 6daadc0..4544e10 100644 --- a/src/factories/mk64/Paths.cpp +++ b/src/factories/mk64/Paths.cpp @@ -53,7 +53,7 @@ ExportResult MK64::PathBinaryExporter::Export(std::ostream& write, std::shared_p auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::Paths, 0); - writer.Write((uint32_t) paths.size()); + writer.Write((uint32_t)paths.size()); for (auto w : paths) { writer.Write(w.posX); writer.Write(w.posY); diff --git a/src/factories/mk64/SpawnData.cpp b/src/factories/mk64/SpawnData.cpp index 8b9f383..3a3bcce 100644 --- a/src/factories/mk64/SpawnData.cpp +++ b/src/factories/mk64/SpawnData.cpp @@ -6,10 +6,11 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) "0x" << std::hex << std::setw(2) << std::setfill('0') << c -ExportResult MK64::SpawnDataHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MK64::SpawnDataHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,7 +19,8 @@ ExportResult MK64::SpawnDataHeaderExporter::Export(std::ostream &write, std::sha return std::nullopt; } -ExportResult MK64::SpawnDataCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::SpawnDataCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto spawns = std::static_pointer_cast<SpawnDataData>(raw)->mSpawns; const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -32,7 +34,7 @@ ExportResult MK64::SpawnDataCodeExporter::Export(std::ostream &write, std::share auto id = spawns[i].id; - if(i <= spawns.size() - 1) { + if (i <= spawns.size() - 1) { write << fourSpaceTab; } @@ -44,13 +46,14 @@ ExportResult MK64::SpawnDataCodeExporter::Export(std::ostream &write, std::share return offset + spawns.size() * sizeof(MK64::ActorSpawnData); } -ExportResult MK64::SpawnDataBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::SpawnDataBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto spawns = std::static_pointer_cast<SpawnDataData>(raw)->mSpawns; auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::SpawnData, 0); - writer.Write((uint32_t) spawns.size()); - for(auto s : spawns) { + writer.Write((uint32_t)spawns.size()); + for (auto s : spawns) { writer.Write(s.x); writer.Write(s.y); writer.Write(s.z); @@ -61,7 +64,8 @@ ExportResult MK64::SpawnDataBinaryExporter::Export(std::ostream &write, std::sha return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> MK64::SpawnDataFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> MK64::SpawnDataFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto count = GetSafeNode<size_t>(node, "count"); auto [_, segment] = Decompressor::AutoDecode(node, buffer); @@ -70,15 +74,13 @@ std::optional<std::shared_ptr<IParsedData>> MK64::SpawnDataFactory::parse(std::v reader.SetEndianness(Torch::Endianness::Big); std::vector<MK64::ActorSpawnData> spawns; - for(size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { auto x = reader.ReadInt16(); auto y = reader.ReadInt16(); auto z = reader.ReadInt16(); auto id = reader.ReadUInt16(); - spawns.push_back(MK64::ActorSpawnData({ - x, y, z, id - })); + spawns.push_back(MK64::ActorSpawnData({ x, y, z, id })); } return std::make_shared<SpawnDataData>(spawns); diff --git a/src/factories/mk64/TrackSections.cpp b/src/factories/mk64/TrackSections.cpp index fb9d950..85aa038 100644 --- a/src/factories/mk64/TrackSections.cpp +++ b/src/factories/mk64/TrackSections.cpp @@ -7,10 +7,12 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) "0x" << std::hex << std::setw(2) << std::setfill('0') << c -ExportResult MK64::TrackSectionsHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MK64::TrackSectionsHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -19,7 +21,9 @@ ExportResult MK64::TrackSectionsHeaderExporter::Export(std::ostream &write, std: return std::nullopt; } -ExportResult MK64::TrackSectionsCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::TrackSectionsCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto sections = std::static_pointer_cast<TrackSectionsData>(raw)->mSecs; const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -38,7 +42,7 @@ ExportResult MK64::TrackSectionsCodeExporter::Export(std::ostream &write, std::s auto sect = entry.sectionId; auto flags = entry.flags; - if(i <= sections.size() - 1) { + if (i <= sections.size() - 1) { write << fourSpaceTab; } @@ -50,15 +54,17 @@ ExportResult MK64::TrackSectionsCodeExporter::Export(std::ostream &write, std::s return offset + sections.size() * sizeof(MK64::TrackSections); } -ExportResult MK64::TrackSectionsBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::TrackSectionsBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto sections = std::static_pointer_cast<TrackSectionsData>(raw); auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::TrackSection, 0); - writer.Write((uint32_t) sections->mSecs.size()); - for(auto entry : sections->mSecs) { + writer.Write((uint32_t)sections->mSecs.size()); + for (auto entry : sections->mSecs) { auto dec = Companion::Instance->GetSafeStringByAddr(entry.crc, "GFX"); - if(!dec.has_value()){ + if (!dec.has_value()) { SPDLOG_WARN("Could not find gfx at 0x{:X}", entry.crc); writer.Write(entry.crc); } else { @@ -74,7 +80,8 @@ ExportResult MK64::TrackSectionsBinaryExporter::Export(std::ostream &write, std: return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> MK64::TrackSectionsFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> MK64::TrackSectionsFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto count = GetSafeNode<size_t>(node, "count"); // On-disk format: uint32_t addr + int8_t surf + int8_t sect + uint16_t flags = 8 bytes @@ -86,15 +93,18 @@ std::optional<std::shared_ptr<IParsedData>> MK64::TrackSectionsFactory::parse(st reader.SetEndianness(Torch::Endianness::Big); std::vector<MK64::TrackSections> sections; - for(size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { auto addr = reader.ReadUInt32(); auto surf = reader.ReadInt8(); auto sect = reader.ReadInt8(); auto flags = reader.ReadUInt16(); sections.push_back(MK64::TrackSections({ - addr, surf, sect, flags, - })); + addr, + surf, + sect, + flags, + })); } return std::make_shared<TrackSectionsData>(sections); diff --git a/src/factories/mk64/UnkSpawnData.cpp b/src/factories/mk64/UnkSpawnData.cpp index 8486678..adf2940 100644 --- a/src/factories/mk64/UnkSpawnData.cpp +++ b/src/factories/mk64/UnkSpawnData.cpp @@ -6,10 +6,12 @@ #define NUM(x) std::dec << std::setfill(' ') << std::setw(6) << x #define COL(c) "0x" << std::hex << std::setw(2) << std::setfill('0') << c -ExportResult MK64::UnkSpawnDataHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult MK64::UnkSpawnDataHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,7 +20,9 @@ ExportResult MK64::UnkSpawnDataHeaderExporter::Export(std::ostream &write, std:: return std::nullopt; } -ExportResult MK64::UnkSpawnDataCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::UnkSpawnDataCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto spawns = std::static_pointer_cast<UnkSpawnDataData>(raw)->mSpawns; const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -33,25 +37,28 @@ ExportResult MK64::UnkSpawnDataCodeExporter::Export(std::ostream &write, std::sh auto someId = spawns[i].someId; auto unk8 = spawns[i].unk8; - if(i <= spawns.size() - 1) { + if (i <= spawns.size() - 1) { write << fourSpaceTab; } // { x, y, z, id }, - write << "{" << NUM(x) << ", " << NUM(y) << ", " << NUM(z) << ", " << NUM(someId) << ", " << NUM(unk8) << " },\n"; + write << "{" << NUM(x) << ", " << NUM(y) << ", " << NUM(z) << ", " << NUM(someId) << ", " << NUM(unk8) + << " },\n"; } write << "};\n"; return offset + spawns.size() * sizeof(MK64::UnkActorSpawnData); } -ExportResult MK64::UnkSpawnDataBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult MK64::UnkSpawnDataBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto spawns = std::static_pointer_cast<UnkSpawnDataData>(raw)->mSpawns; auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::UnkSpawnData, 0); - writer.Write((uint32_t) spawns.size()); - for(auto s : spawns) { + writer.Write((uint32_t)spawns.size()); + for (auto s : spawns) { writer.Write(s.x); writer.Write(s.y); writer.Write(s.z); @@ -63,7 +70,8 @@ ExportResult MK64::UnkSpawnDataBinaryExporter::Export(std::ostream &write, std:: return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> MK64::UnkSpawnDataFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> MK64::UnkSpawnDataFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto count = GetSafeNode<size_t>(node, "count"); auto [_, segment] = Decompressor::AutoDecode(node, buffer); @@ -72,16 +80,14 @@ std::optional<std::shared_ptr<IParsedData>> MK64::UnkSpawnDataFactory::parse(std reader.SetEndianness(Torch::Endianness::Big); std::vector<MK64::UnkActorSpawnData> spawns; - for(size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { auto x = reader.ReadInt16(); auto y = reader.ReadInt16(); auto z = reader.ReadInt16(); auto someId = reader.ReadInt16(); auto unk8 = reader.ReadInt16(); - spawns.push_back(MK64::UnkActorSpawnData({ - x, y, z, someId, unk8 - })); + spawns.push_back(MK64::UnkActorSpawnData({ x, y, z, someId, unk8 })); } return std::make_shared<UnkSpawnDataData>(spawns); diff --git a/src/factories/naudio/v0/AIFCDecode.cpp b/src/factories/naudio/v0/AIFCDecode.cpp index d487242..3782d98 100644 --- a/src/factories/naudio/v0/AIFCDecode.cpp +++ b/src/factories/naudio/v0/AIFCDecode.cpp @@ -37,7 +37,9 @@ typedef float f32; #define BSWAP32(x) x = bswap32(x) #endif -#define BSWAP16_MANY(x, n) for (s32 _i = 0; _i < n; _i++) BSWAP16((x)[_i]) +#define BSWAP16_MANY(x, n) \ + for (s32 _i = 0; _i < n; _i++) \ + BSWAP16((x)[_i]) #ifndef WIN32 #define NORETURN __attribute__((noreturn)) @@ -103,27 +105,25 @@ typedef struct { s16 nEntries; } CodeChunk; -typedef struct -{ +typedef struct { u32 start; u32 end; u32 count; s16 state[16]; } ALADPCMloop; -#define checked_fread(a, b, c, d) d.Read((char*) a, b * c) +#define checked_fread(a, b, c, d) d.Read((char*)a, b* c) NORETURN -void fail_parse(const char *fmt, ...) -{ - char *formatted = nullptr; +void fail_parse(const char* fmt, ...) { + char* formatted = nullptr; va_list ap; va_start(ap, fmt); int size = vsnprintf(nullptr, 0, fmt, ap); va_end(ap); if (size >= 0) { size++; - formatted = static_cast<char *>(malloc(size)); + formatted = static_cast<char*>(malloc(size)); if (formatted != nullptr) { va_start(ap, fmt); size = vsnprintf(formatted, size, fmt, ap); @@ -142,36 +142,35 @@ void fail_parse(const char *fmt, ...) throw std::runtime_error("Error parsing file"); } -s32 myrand() -{ +s32 myrand() { static u64 state = 1619236481962341ULL; state *= 3123692312231ULL; state++; return state >> 33; } -s16 qsample(s32 x, s32 scale) -{ +s16 qsample(s32 x, s32 scale) { // Compute x / 2^scale rounded to the nearest integer, breaking ties towards zero. - if (scale == 0) return x; + if (scale == 0) + return x; return (x + (1 << (scale - 1)) - (x > 0)) >> scale; } -s16 clamp_to_s16(s32 x) -{ - if (x < -0x8000) return -0x8000; - if (x > 0x7fff) return 0x7fff; - return (s16) x; +s16 clamp_to_s16(s32 x) { + if (x < -0x8000) + return -0x8000; + if (x > 0x7fff) + return 0x7fff; + return (s16)x; } -s32 toi4(s32 x) -{ - if (x >= 8) return x - 16; +s32 toi4(s32 x) { + if (x >= 8) + return x - 16; return x; } -s32 readaifccodebook(LUS::BinaryReader& fhandle, s32 ****table, s16 *order, s16 *npredictors) -{ +s32 readaifccodebook(LUS::BinaryReader& fhandle, s32**** table, s16* order, s16* npredictors) { checked_fread(order, sizeof(s16), 1, fhandle); BSWAP16(*order); checked_fread(npredictors, sizeof(s16), 1, fhandle); @@ -185,7 +184,7 @@ s32 readaifccodebook(LUS::BinaryReader& fhandle, s32 ****table, s16 *order, s16 } for (s32 i = 0; i < *npredictors; i++) { - s32 **table_entry = (*table)[i]; + s32** table_entry = (*table)[i]; for (s32 j = 0; j < *order; j++) { for (s32 k = 0; k < 8; k++) { s16 ts; @@ -215,10 +214,10 @@ s32 readaifccodebook(LUS::BinaryReader& fhandle, s32 ****table, s16 *order, s16 return 0; } -ALADPCMloop *readlooppoints(LUS::BinaryReader& reader, s16 *nloops) { +ALADPCMloop* readlooppoints(LUS::BinaryReader& reader, s16* nloops) { checked_fread(nloops, sizeof(s16), 1, reader); BSWAP16(*nloops); - auto *al = static_cast<ALADPCMloop *>(malloc(*nloops * sizeof(ALADPCMloop))); + auto* al = static_cast<ALADPCMloop*>(malloc(*nloops * sizeof(ALADPCMloop))); for (s32 i = 0; i < *nloops; i++) { checked_fread(&al[i], sizeof(ALADPCMloop), 1, reader); BSWAP32(al[i].start); @@ -229,8 +228,7 @@ ALADPCMloop *readlooppoints(LUS::BinaryReader& reader, s16 *nloops) { return al; } -s32 inner_product(s32 length, s32 *v1, s32 *v2) -{ +s32 inner_product(s32 length, s32* v1, s32* v2) { s32 out = 0; for (s32 i = 0; i < length; i++) { out += v1[i] * v2[i]; @@ -242,8 +240,7 @@ s32 inner_product(s32 length, s32 *v1, s32 *v2) return dout - (out - fiout < 0); } -void my_decodeframe(u8 *frame, s32 *state, s32 order, s32 ***coefTable) -{ +void my_decodeframe(u8* frame, s32* state, s32 order, s32*** coefTable) { s32 ix[16]; u8 header = frame[0]; @@ -251,13 +248,14 @@ void my_decodeframe(u8 *frame, s32 *state, s32 order, s32 ***coefTable) s32 optimalp = header & 0xf; for (s32 i = 0; i < 16; i += 2) { - u8 c = frame[1 + i/2]; + u8 c = frame[1 + i / 2]; ix[i] = c >> 4; ix[i + 1] = c & 0xf; } for (s32 i = 0; i < 16; i++) { - if (ix[i] >= 8) ix[i] -= 16; + if (ix[i] >= 8) + ix[i] -= 16; ix[i] *= scale; } @@ -281,8 +279,7 @@ void my_decodeframe(u8 *frame, s32 *state, s32 order, s32 ***coefTable) } } -void my_encodeframe(u8 *out, s16 *inBuffer, s32 *state, s32 ***coefTable, s32 order, s32 npredictors) -{ +void my_encodeframe(u8* out, s16* inBuffer, s32* state, s32*** coefTable, s32 order, s32 npredictors) { s16 ix[16]; s32 prediction[16]; s32 inVector[16]; @@ -307,7 +304,7 @@ void my_encodeframe(u8 *out, s16 *inBuffer, s32 *state, s32 ***coefTable, s32 or f32 se = 0.0f; for (s32 j = 0; j < 16; j++) { - se += (f32) e[j] * (f32) e[j]; + se += (f32)e[j] * (f32)e[j]; } if (se < min) { @@ -339,7 +336,8 @@ void my_encodeframe(u8 *out, s16 *inBuffer, s32 *state, s32 ***coefTable, s32 or } for (scale = 0; scale <= 12; scale++) { - if (max <= 7 && max >= -8) break; + if (max <= 7 && max >= -8) + break; max /= 2; } @@ -349,7 +347,8 @@ void my_encodeframe(u8 *out, s16 *inBuffer, s32 *state, s32 ***coefTable, s32 or for (s32 nIter = 0, again = 1; nIter < 2 && again; nIter++) { again = 0; - if (nIter == 1) scale++; + if (nIter == 1) + scale++; if (scale > 12) { scale = 12; } @@ -357,8 +356,7 @@ void my_encodeframe(u8 *out, s16 *inBuffer, s32 *state, s32 ***coefTable, s32 or for (s32 j = 0; j < 2; j++) { s32 base = j * 8; for (s32 i = 0; i < order; i++) { - inVector[i] = (j == 0 ? - saveState[16 - order + i] : state[8 - order + i]); + inVector[i] = (j == 0 ? saveState[16 - order + i] : state[8 - order + i]); } for (s32 i = 0; i < 8; i++) { @@ -366,7 +364,8 @@ void my_encodeframe(u8 *out, s16 *inBuffer, s32 *state, s32 ***coefTable, s32 or s32 se = inBuffer[base + i] - prediction[base + i]; ix[base + i] = qsample(se, scale); s32 cV = clamp_to_s16(ix[base + i]) - ix[base + i]; - if (cV > 1 || cV < -1) again = 1; + if (cV > 1 || cV < -1) + again = 1; ix[base + i] += cV; inVector[i + order] = ix[base + i] * (1 << scale); state[base + i] = prediction[base + i] + inVector[i + order]; @@ -378,12 +377,11 @@ void my_encodeframe(u8 *out, s16 *inBuffer, s32 *state, s32 ***coefTable, s32 or out[0] = header; for (s32 i = 0; i < 16; i += 2) { u8 c = ((ix[i] & 0xf) << 4) | (ix[i + 1] & 0xf); - out[1 + i/2] = c; + out[1 + i / 2] = c; } } -void permute(s16 *out, s32 *in, s32 scale) -{ +void permute(s16* out, s32* in, s32 scale) { for (s32 i = 0; i < 16; i++) { out[i] = clamp_to_s16(in[i] - scale / 2 + myrand() % (scale + 1)); } @@ -391,7 +389,7 @@ void permute(s16 *out, s32 *in, s32 scale) void WriteString(const char* str, int32_t size, LUS::BinaryWriter& writer) { for (int i = 0; i < size; i++) { - writer.Write((uint8_t) str[i]); + writer.Write((uint8_t)str[i]); } } @@ -403,10 +401,10 @@ void write_header(LUS::BinaryWriter& writer, std::string id, s32 size) { void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { s16 order = -1; s16 nloops = 0; - ALADPCMloop *aloops = nullptr; + ALADPCMloop* aloops = nullptr; s16 npredictors = -1; - s32 ***coefTable = nullptr; - s32 state[16] = {0}; + s32*** coefTable = nullptr; + s32 state[16] = { 0 }; s32 soundPointer = -1; s32 currPos = 0; s32 nSamples = 0; @@ -430,7 +428,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { if (reader.GetBaseAddress() >= reader.GetLength()) { break; } - reader.Read((char*) &Header, sizeof(Header)); + reader.Read((char*)&Header, sizeof(Header)); u32 ts; BSWAP32(Header.ckID); BSWAP32(Header.ckSize); @@ -439,7 +437,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { Header.ckSize &= ~1; s32 offset = reader.GetBaseAddress(); - if(Header.ckID == 0x434f4d4d) { // COMM + if (Header.ckID == 0x434f4d4d) { // COMM checked_fread(&CommChunk, sizeof(CommChunk), 1, reader); BSWAP16(CommChunk.numChannels); BSWAP16(CommChunk.numFramesH); @@ -470,7 +468,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { } } - if(Header.ckID == 0x53534e44) { //SSND + if (Header.ckID == 0x53534e44) { // SSND checked_fread(&SndDChunk, sizeof(SndDChunk), 1, reader); BSWAP32(SndDChunk.offset); BSWAP32(SndDChunk.blockSize); @@ -479,7 +477,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { soundPointer = reader.GetBaseAddress(); } - if(Header.ckID == 0x4150504c){ // APPL + if (Header.ckID == 0x4150504c) { // APPL checked_fread(&ts, sizeof(u32), 1, reader); BSWAP32(ts); if (ts == 0x73746f63) { // stoc @@ -497,8 +495,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { fail_parse("Unknown codebook chunk version"); } readaifccodebook(reader, &coefTable, &order, &npredictors); - } - else if (strcmp("VADPCMLOOPS", ChunkName) == 0) { + } else if (strcmp("VADPCMLOOPS", ChunkName) == 0) { checked_fread(&version, sizeof(s16), 1, reader); BSWAP16(version); if (version != 1) { @@ -529,12 +526,12 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { reader.Seek(soundPointer, LUS::SeekOffsetType::Start); while (currPos < nSamples) { - u8 input[9] = {0}; - u8 encoded[9] = {0}; - s32 lastState[16] = {0}; - s32 decoded[16] = {0}; - s16 guess[16] = {0}; - s16 origGuess[16] = {0}; + u8 input[9] = { 0 }; + u8 encoded[9] = { 0 }; + s32 lastState[16] = { 0 }; + s32 decoded[16] = { 0 }; + s16 guess[16] = { 0 }; + s16 origGuess[16] = { 0 }; memcpy(lastState, state, sizeof(lastState)); checked_fread(input, 9, 1, reader); @@ -567,15 +564,16 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { for (s32 failures = 0; failures < 50; failures++) { s32 ind = myrand() % 16; s32 old = guess[ind]; - if (old == origGuess[ind]) continue; + if (old == origGuess[ind]) + continue; guess[ind] = origGuess[ind]; - if (myrand() % 2) guess[ind] += (old - origGuess[ind]) / 2; + if (myrand() % 2) + guess[ind] += (old - origGuess[ind]) / 2; memcpy(state, lastState, sizeof(lastState)); my_encodeframe(encoded, guess, state, coefTable, order, npredictors); if (memcmp(input, encoded, 9) == 0) { failures = -1; - } - else { + } else { guess[ind] = old; } } @@ -584,7 +582,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { memcpy(state, decoded, sizeof(lastState)); BSWAP16_MANY(guess, 16); writer.Seek(currPos * 2, LUS::SeekOffsetType::Start); - writer.Write((char*) guess, sizeof(guess)); + writer.Write((char*)guess, sizeof(guess)); currPos += 16; } @@ -600,20 +598,18 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { BSWAP16(CommChunk.numFramesH); BSWAP16(CommChunk.numFramesL); BSWAP16(CommChunk.sampleSize); - writer.Write((char*) &CommChunk, sizeof(CommonChunk) - 4); + writer.Write((char*)&CommChunk, sizeof(CommonChunk) - 4); if (nloops > 0) { s32 startPos = aloops[0].start, endPos = aloops[0].end; - const char *markerNames[2] = {"start", "end"}; - Marker markers[2] = { - {1, static_cast<u16>((u16) startPos >> 16), static_cast<u16>((u16) startPos & 0xffff)}, - {2, static_cast<u16>(endPos >> 16), static_cast<u16>(endPos & 0xffff)} - }; + const char* markerNames[2] = { "start", "end" }; + Marker markers[2] = { { 1, static_cast<u16>((u16)startPos >> 16), static_cast<u16>((u16)startPos & 0xffff) }, + { 2, static_cast<u16>(endPos >> 16), static_cast<u16>(endPos & 0xffff) } }; write_header(writer, "MARK", 2 + 2 * sizeof(Marker) + 1 + 5 + 1 + 3); s16 numMarkers = bswap16(2); writer.Write(numMarkers); for (s32 i = 0; i < 2; i++) { - u8 len = (u8) strlen(markerNames[i]); + u8 len = (u8)strlen(markerNames[i]); BSWAP16(markers[i].MarkerID); BSWAP16(markers[i].positionH); BSWAP16(markers[i].positionL); @@ -621,7 +617,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { writer.Write(markers[i].positionH); writer.Write(markers[i].positionL); writer.Write(len); - writer.Write((char*) markerNames[i], len); + writer.Write((char*)markerNames[i], len); } write_header(writer, "INST", sizeof(InstrumentChunk)); @@ -631,7 +627,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { InstChunk.releaseLoop.playMode = 0; InstChunk.releaseLoop.beginLoop = 0; InstChunk.releaseLoop.endLoop = 0; - writer.Write((char*) &InstChunk, sizeof(InstrumentChunk)); + writer.Write((char*)&InstChunk, sizeof(InstrumentChunk)); } // Save the coefficient table for use when encoding. Ideally this wouldn't @@ -643,9 +639,9 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { cChunk.version = bswap16(1); cChunk.order = bswap16(order); cChunk.nEntries = bswap16(npredictors); - writer.Write((uint8_t) 0xB); + writer.Write((uint8_t)0xB); WriteString("VADPCMCODES", 11, writer); - writer.Write((char*) &cChunk, sizeof(CodeChunk)); + writer.Write((char*)&cChunk, sizeof(CodeChunk)); for (s32 i = 0; i < npredictors; i++) { for (s32 j = 0; j < order; j++) { for (s32 k = 0; k < 8; k++) { @@ -658,7 +654,7 @@ void write_aiff(std::vector<char> data, LUS::BinaryWriter& writer) { write_header(writer, "SSND", outputBytes + 8); SndDChunk.offset = 0; SndDChunk.blockSize = 0; - writer.Write((char*) &SndDChunk, sizeof(SoundDataChunk)); + writer.Write((char*)&SndDChunk, sizeof(SoundDataChunk)); // Fix the size in the header s32 fileSize = bswap32(writer.GetLength() - 8); diff --git a/src/factories/naudio/v0/AudioHeaderFactory.cpp b/src/factories/naudio/v0/AudioHeaderFactory.cpp index e4ef99f..25cd072 100644 --- a/src/factories/naudio/v0/AudioHeaderFactory.cpp +++ b/src/factories/naudio/v0/AudioHeaderFactory.cpp @@ -7,7 +7,8 @@ #include <factories/naudio/v1/AudioConverter.h> /* -ExportResult AudioAIFCExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult AudioAIFCExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, std::string& entryName, +YAML::Node& node, std::string* replacement) { auto samples = AudioManager::Instance->get_samples(); @@ -21,7 +22,7 @@ ExportResult AudioAIFCExporter::Export(std::ostream& write, std::shared_ptr<IPar LUS::BinaryWriter aifc = LUS::BinaryWriter(); AudioConverter::SampleV0ToAIFC(sample, aifc); - + LUS::BinaryWriter aiff = LUS::BinaryWriter(); write_aiff(aifc.ToVector(), aiff); aifc.Close(); diff --git a/src/factories/naudio/v0/AudioManager.cpp b/src/factories/naudio/v0/AudioManager.cpp index 51b44d5..a340e0b 100644 --- a/src/factories/naudio/v0/AudioManager.cpp +++ b/src/factories/naudio/v0/AudioManager.cpp @@ -27,29 +27,30 @@ std::vector<uint32_t> PyUtils::range(uint32_t start, uint32_t end) { return result; } -std::string gen_name(const std::string& prefix){ - if(!Torch::contains(name_table, prefix)){ +std::string gen_name(const std::string& prefix) { + if (!Torch::contains(name_table, prefix)) { name_table[prefix] = 0; } return prefix + std::to_string(name_table[prefix]++); } -AudioBankSample* SampleBank::AddSample(uint32_t addr, size_t sampleSize, const AdpcmBook& book, const AdpcmLoop& loop){ +AudioBankSample* SampleBank::AddSample(uint32_t addr, size_t sampleSize, const AdpcmBook& book, const AdpcmLoop& loop) { assert(sampleSize % 2 == 0); - if(sampleSize % 9 != 0){ + if (sampleSize % 9 != 0) { assert(sampleSize % 9 == 1); sampleSize -= 1; } AudioBankSample* entry; - if(Torch::contains(this->entries, addr)){ + if (Torch::contains(this->entries, addr)) { entry = this->entries[addr]; assert(entry->book == book); assert(entry->loop == loop); assert(entry->data.size() == sampleSize); } else { - entry = new AudioBankSample{ gen_name("aifc"), PyUtils::slice(this->data, addr, addr + sampleSize), book, loop }; + entry = + new AudioBankSample{ gen_name("aifc"), PyUtils::slice(this->data, addr, addr + sampleSize), book, loop }; this->entries[addr] = entry; } @@ -68,9 +69,9 @@ void Bank::print() const { SPDLOG_DEBUG("Sample Bank Offset: {}", std::to_string(sampleBank->offset)); } -std::vector<Entry> AudioManager::parse_seq_file(std::vector<uint8_t>& buffer, uint32_t offset, bool isCTL){ +std::vector<Entry> AudioManager::parse_seq_file(std::vector<uint8_t>& buffer, uint32_t offset, bool isCTL) { std::vector<Entry> entries; - LUS::BinaryReader reader((char*) buffer.data(), buffer.size()); + LUS::BinaryReader reader((char*)buffer.data(), buffer.size()); reader.SetEndianness(Torch::Endianness::Big); reader.Seek(offset, LUS::SeekOffsetType::Start); @@ -85,22 +86,22 @@ std::vector<Entry> AudioManager::parse_seq_file(std::vector<uint8_t>& buffer, ui uint32_t addr = reader.ReadUInt32(); uint32_t length = reader.ReadUInt32(); - if(isCTL){ + if (isCTL) { assert(addr == prev); } else { assert(addr <= prev); } prev = std::max(prev, addr + length); - entries.push_back({addr, length}); + entries.push_back({ addr, length }); } reader.Close(); return entries; } -CTLHeader AudioManager::parse_ctl_header(std::vector<uint8_t>& data){ - LUS::BinaryReader reader((char*) data.data(), data.size()); +CTLHeader AudioManager::parse_ctl_header(std::vector<uint8_t>& data) { + LUS::BinaryReader reader((char*)data.data(), data.size()); reader.SetEndianness(Torch::Endianness::Big); CTLHeader header = { reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32() }; @@ -116,7 +117,7 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample std::string name = ss.str(); uint32_t numInstruments = header.instruments; uint32_t numDrums = header.numDrums; - char* rawData = (char*) data.data(); + char* rawData = (char*)data.data(); uint32_t drumBaseAddr; memcpy(&drumBaseAddr, rawData, 4); @@ -124,12 +125,12 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample std::vector<uint32_t> drumOffsets; - if(numDrums != 0){ + if (numDrums != 0) { assert(drumBaseAddr != 0); for (size_t i = 0; i < numDrums; ++i) { uint32_t drumOffset; memcpy(&drumOffset, rawData + drumBaseAddr + i * 4, 4); - if(drumOffset == 0){ + if (drumOffset == 0) { continue; } @@ -147,7 +148,7 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample uint32_t instOffset; memcpy(&instOffset, rawData + (instrumentBaseAddr + i * 4), 4); instOffset = BSWAP32(instOffset); - if(instOffset == 0){ + if (instOffset == 0) { instrumentList.push_back(NONE); instrumentOffsets.push_back(NONE); } else { @@ -156,11 +157,11 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample } } -// std::sort(instrumentOffsets.begin(), instrumentOffsets.end()); + // std::sort(instrumentOffsets.begin(), instrumentOffsets.end()); std::vector<Instrument> insts; - for(auto &offset : instrumentOffsets){ - if(offset == NONE){ + for (auto& offset : instrumentOffsets) { + if (offset == NONE) { Instrument invalid = { .valid = false }; insts.push_back(invalid); continue; @@ -171,7 +172,7 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample } std::vector<Drum> drums; - for(auto &offset : drumOffsets){ + for (auto& offset : drumOffsets) { auto rDrum = PyUtils::slice(data, offset, offset + 16); Drum drum = parse_drum(rDrum, offset); drums.push_back(drum); @@ -181,16 +182,16 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample auto sampleOffsets = std::vector<uint32_t>(); auto tunings = std::unordered_map<uint32_t, float>(); - for(auto &inst : insts){ - for(auto &sound : {inst.soundLo, inst.soundMed, inst.soundHi}){ - if(sound.has_value()){ + for (auto& inst : insts) { + for (auto& sound : { inst.soundLo, inst.soundMed, inst.soundHi }) { + if (sound.has_value()) { sampleOffsets.push_back(sound.value().offset); tunings[sound.value().offset] = sound.value().tuning; } } envOffsets.push_back(inst.envelope); } - for(auto &drum : drums){ + for (auto& drum : drums) { sampleOffsets.push_back(drum.sound.offset); tunings[drum.sound.offset] = drum.sound.tuning; envOffsets.push_back(drum.envelope); @@ -200,10 +201,12 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample // but it works for our purposes.) std::vector<std::variant<Instrument, std::vector<Drum>>> allInsts; bool needDrums = !drums.empty(); - for(auto &inst : insts){ - std::vector<std::optional<AudioBankSound>> sounds = {inst.soundLo, inst.soundMed, inst.soundHi}; + for (auto& inst : insts) { + std::vector<std::optional<AudioBankSound>> sounds = { inst.soundLo, inst.soundMed, inst.soundHi }; - if(needDrums && std::any_of(sounds.cbegin(), sounds.cend(), [&drums](std::optional<AudioBankSound> sound){ return sound.has_value() && sound.value().offset > drums[0].sound.offset; })){ + if (needDrums && std::any_of(sounds.cbegin(), sounds.cend(), [&drums](std::optional<AudioBankSound> sound) { + return sound.has_value() && sound.value().offset > drums[0].sound.offset; + })) { allInsts.emplace_back(drums); needDrums = false; } @@ -211,17 +214,16 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample allInsts.emplace_back(inst); } - - if(needDrums){ + if (needDrums) { allInsts.emplace_back(drums); } std::map<uint32_t, AudioBankSample*> samples; std::sort(sampleOffsets.begin(), sampleOffsets.end()); - for(auto &offset : sampleOffsets){ + for (auto& offset : sampleOffsets) { auto rSample = PyUtils::slice(data, offset, offset + 20); AudioBankSample* sample = parse_sample(rSample, data, bank); - for(auto &tuning : tunings){ + for (auto& tuning : tunings) { sample->tunings.push_back(tuning.second); } samples[offset] = sample; @@ -230,21 +232,21 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample std::unordered_map<uint32_t, std::vector<AdsrEnvelope>> envData; std::vector<uint32_t> usedEnvOffsets; std::sort(envOffsets.begin(), envOffsets.end()); - for(auto &offset : envOffsets){ + for (auto& offset : envOffsets) { auto env = parse_envelope(offset, data); envData[offset] = env; - for(int i = 0; i < ALIGN(env.size(), 4); i++){ + for (int i = 0; i < ALIGN(env.size(), 4); i++) { usedEnvOffsets.push_back(offset + (i * 4)); } } std::vector<uint32_t> unusedEnvOffsets; - if(!usedEnvOffsets.empty()){ + if (!usedEnvOffsets.empty()) { size_t min = std::min_element(usedEnvOffsets.begin(), usedEnvOffsets.end()) - usedEnvOffsets.begin(); size_t max = std::max_element(usedEnvOffsets.begin(), usedEnvOffsets.end()) - usedEnvOffsets.begin(); - for(size_t idx = min + 4; idx < max; idx += 4){ + for (size_t idx = min + 4; idx < max; idx += 4) { uint32_t addr = usedEnvOffsets[idx]; - if(std::find(usedEnvOffsets.begin(), usedEnvOffsets.end(), addr) == usedEnvOffsets.end()){ + if (std::find(usedEnvOffsets.begin(), usedEnvOffsets.end(), addr) == usedEnvOffsets.end()) { unusedEnvOffsets.push_back(addr); uint32_t stubMarker; memcpy(&stubMarker, rawData + addr, 4); @@ -252,7 +254,7 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample assert(stubMarker == 0); auto env = parse_envelope(addr, data); envData[addr] = env; - for(int i = 0; i < ALIGN(env.size(), 4); i++){ + for (int i = 0; i < ALIGN(env.size(), 4); i++) { usedEnvOffsets.push_back(addr + (i * 4)); } } @@ -260,7 +262,7 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample } std::map<uint32_t, Envelope> envelopes; - for(auto &entry : envData){ + for (auto& entry : envData) { Envelope env = { gen_name("envelope"), entry.second }; envelopes[entry.first] = env; } @@ -270,13 +272,13 @@ Bank AudioManager::parse_ctl(CTLHeader header, std::vector<uint8_t> data, Sample } std::optional<AudioBankSound> AudioManager::parse_sound(std::vector<uint8_t> data) { - LUS::BinaryReader reader((char*) data.data(), data.size()); + LUS::BinaryReader reader((char*)data.data(), data.size()); reader.SetEndianness(Torch::Endianness::Big); uint32_t addr = reader.ReadUInt32(); float tuning = reader.ReadFloat(); - if(addr == 0){ + if (addr == 0) { assert(tuning == 0.0f); return std::nullopt; } @@ -288,7 +290,7 @@ std::optional<AudioBankSound> AudioManager::parse_sound(std::vector<uint8_t> dat } Drum AudioManager::parse_drum(std::vector<uint8_t>& data, uint32_t addr) { - LUS::BinaryReader reader((char*) data.data(), data.size()); + LUS::BinaryReader reader((char*)data.data(), data.size()); reader.SetEndianness(Torch::Endianness::Big); std::string name = gen_name("drum"); @@ -312,14 +314,14 @@ Instrument AudioManager::parse_inst(std::vector<uint8_t>& data, uint32_t addr) { uint8_t releaseRate = data[3]; uint32_t envAddr; - memcpy(&envAddr, (char*) data.data() + 4, 4); + memcpy(&envAddr, (char*)data.data() + 4, 4); envAddr = BSWAP32(envAddr); assert(envAddr != 0); - auto soundLo = parse_sound(PyUtils::slice(data, 8, 16)); + auto soundLo = parse_sound(PyUtils::slice(data, 8, 16)); auto soundMed = parse_sound(PyUtils::slice(data, 16, 24)); - auto soundHi = parse_sound(PyUtils::slice(data, 24)); + auto soundHi = parse_sound(PyUtils::slice(data, 24)); if (soundLo == std::nullopt) { assert(normalRangeLo == 0); @@ -328,12 +330,14 @@ Instrument AudioManager::parse_inst(std::vector<uint8_t>& data, uint32_t addr) { assert(normalRangeHi == 127); } - Instrument inst = { true, name, addr, releaseRate, normalRangeLo, normalRangeHi, envAddr, soundLo, soundMed, soundHi }; + Instrument inst = { + true, name, addr, releaseRate, normalRangeLo, normalRangeHi, envAddr, soundLo, soundMed, soundHi + }; return inst; } -AdpcmLoop AudioManager::parse_loop(uint32_t addr, std::vector<uint8_t>& bankData){ - LUS::BinaryReader reader((char*) bankData.data(), bankData.size()); +AdpcmLoop AudioManager::parse_loop(uint32_t addr, std::vector<uint8_t>& bankData) { + LUS::BinaryReader reader((char*)bankData.data(), bankData.size()); reader.SetEndianness(Torch::Endianness::Big); reader.Seek(addr, LUS::SeekOffsetType::Start); @@ -343,7 +347,7 @@ AdpcmLoop AudioManager::parse_loop(uint32_t addr, std::vector<uint8_t>& bankData int32_t count = reader.ReadInt32(); uint32_t pad = reader.ReadUInt32(); - if(count != 0){ + if (count != 0) { state = std::vector<int16_t>(); for (size_t i = 0; i < 16; ++i) { state.value().push_back(reader.ReadInt16()); @@ -353,8 +357,8 @@ AdpcmLoop AudioManager::parse_loop(uint32_t addr, std::vector<uint8_t>& bankData return loop; } -AdpcmBook AudioManager::parse_book(uint32_t addr, std::vector<uint8_t>& bankData){ - LUS::BinaryReader reader((char*) bankData.data(), bankData.size()); +AdpcmBook AudioManager::parse_book(uint32_t addr, std::vector<uint8_t>& bankData) { + LUS::BinaryReader reader((char*)bankData.data(), bankData.size()); reader.SetEndianness(Torch::Endianness::Big); reader.Seek(addr, LUS::SeekOffsetType::Start); @@ -366,7 +370,7 @@ AdpcmBook AudioManager::parse_book(uint32_t addr, std::vector<uint8_t>& bankData std::vector<int16_t> table; std::vector<uint8_t> tableData = PyUtils::slice(bankData, addr + 8, addr + 8 + 16 * order * npredictors); - for (size_t i = 0; i < ( 16 * order * npredictors ); i += 2) { + for (size_t i = 0; i < (16 * order * npredictors); i += 2) { int16_t dtable; memcpy(&dtable, tableData.data() + i, 2); table.push_back(BSWAP16(dtable)); @@ -376,8 +380,9 @@ AdpcmBook AudioManager::parse_book(uint32_t addr, std::vector<uint8_t>& bankData return book; } -AudioBankSample* AudioManager::parse_sample(std::vector<uint8_t>& data, std::vector<uint8_t>& bankData, SampleBank* sampleBank){ - LUS::BinaryReader reader((char*) data.data(), data.size()); +AudioBankSample* AudioManager::parse_sample(std::vector<uint8_t>& data, std::vector<uint8_t>& bankData, + SampleBank* sampleBank) { + LUS::BinaryReader reader((char*)data.data(), data.size()); reader.SetEndianness(Torch::Endianness::Big); uint32_t zero = reader.ReadUInt32(); @@ -403,20 +408,19 @@ AudioBankSample* AudioManager::parse_sample(std::vector<uint8_t>& data, std::vec return sampleBank->AddSample(addr, sampleSize, bookData, loopData); } - -std::vector<AdsrEnvelope> AudioManager::parse_envelope(uint32_t addr, std::vector<uint8_t>& dataBank){ +std::vector<AdsrEnvelope> AudioManager::parse_envelope(uint32_t addr, std::vector<uint8_t>& dataBank) { std::vector<AdsrEnvelope> entries; - LUS::BinaryReader reader((char*) dataBank.data(), dataBank.size()); + LUS::BinaryReader reader((char*)dataBank.data(), dataBank.size()); reader.SetEndianness(Torch::Endianness::Big); - while(true){ + while (true) { reader.Seek(addr, LUS::SeekOffsetType::Start); int16_t delay = reader.ReadInt16(); int16_t arg = reader.ReadInt16(); AdsrEnvelope entry = { delay, arg }; entries.push_back(entry); addr += 4; - if (1 <= (-delay) % (1 << 16) && (-delay) % (1 << 16) <= 3){ + if (1 <= (-delay) % (1 << 16) && (-delay) % (1 << 16) <= 3) { break; } } @@ -428,12 +432,11 @@ std::vector<AdsrEnvelope> AudioManager::parse_envelope(uint32_t addr, std::vecto TBLFile AudioManager::parse_tbl(std::vector<uint8_t>& data, std::vector<Entry>& entries) { TBLFile tbl; std::unordered_map<uint32_t, std::string> cache; - for(auto &entry : entries){ - if(!Torch::contains(cache, entry.offset)){ + for (auto& entry : entries) { + if (!Torch::contains(cache, entry.offset)) { std::string name = gen_name("sample_bank"); - auto* sampleBank = new SampleBank{ - name, entry.offset, PyUtils::slice(data, entry.offset, entry.offset + entry.length) - }; + auto* sampleBank = + new SampleBank{ name, entry.offset, PyUtils::slice(data, entry.offset, entry.offset + entry.length) }; tbl.banks.push_back(sampleBank); tbl.map[name] = sampleBank; cache[entry.offset] = name; @@ -479,23 +482,23 @@ void AudioManager::initialize(std::vector<uint8_t>& buffer, YAML::Node& data) { } int32_t idx = -1; - for(auto &sample_bank : this->loaded_tbl.banks){ + for (auto& sample_bank : this->loaded_tbl.banks) { auto offsets = PyUtils::keys(sample_bank->entries); std::sort(offsets.begin(), offsets.end()); - for(auto &offset : offsets){ + for (auto& offset : offsets) { this->sampleMap[sample_bank->entries[offset]] = ++idx; } } } -void AudioManager::bind_sample(YAML::Node& node, const std::string& path){ +void AudioManager::bind_sample(YAML::Node& node, const std::string& path) { auto id = GetSafeNode<uint32_t>(node, "id"); sample_table[id] = path; } std::string& AudioManager::get_sample(uint32_t id) { - if(!Torch::contains(sample_table, id)) { + if (!Torch::contains(sample_table, id)) { throw std::runtime_error("Failed to find sample with id " + std::to_string(id)); } return sample_table[id]; @@ -520,12 +523,12 @@ void AudioManager::create_aifc(int32_t index, LUS::BinaryWriter &out) { AudioBankSample AudioManager::get_aifc(int32_t index) { int32_t idx = 0; - for(auto &sample_bank : this->loaded_tbl.banks){ + for (auto& sample_bank : this->loaded_tbl.banks) { auto offsets = PyUtils::keys(sample_bank->entries); std::sort(offsets.begin(), offsets.end()); - for(auto &offset : offsets){ - if(idx++ == index){ + for (auto& offset : offsets) { + if (idx++ == index) { return *sample_bank->entries[offset]; } } @@ -536,7 +539,7 @@ AudioBankSample AudioManager::get_aifc(int32_t index) { } uint32_t AudioManager::get_index(AudioBankSample* entry) { - if(!Torch::contains(this->sampleMap, entry)){ + if (!Torch::contains(this->sampleMap, entry)) { return -1; } return this->sampleMap[entry]; @@ -552,10 +555,10 @@ std::vector<SampleBank*> AudioManager::get_loaded_banks() { std::vector<AudioBankSample*> AudioManager::get_samples() { std::vector<AudioBankSample*> samples; - for(auto &bank : this->loaded_tbl.banks){ - for(auto &entry : bank->entries){ + for (auto& bank : this->loaded_tbl.banks) { + for (auto& entry : bank->entries) { // Avoid duplicates - if(std::find(samples.begin(), samples.end(), entry.second) == samples.end()){ + if (std::find(samples.begin(), samples.end(), entry.second) == samples.end()) { samples.push_back(entry.second); } } diff --git a/src/factories/naudio/v0/BankFactory.cpp b/src/factories/naudio/v0/BankFactory.cpp index 6e72c53..6d8dfae 100644 --- a/src/factories/naudio/v0/BankFactory.cpp +++ b/src/factories/naudio/v0/BankFactory.cpp @@ -1,7 +1,8 @@ #include "BankFactory.h" #include "Companion.h" -ExportResult BankBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult BankBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto bank = std::static_pointer_cast<BankData>(raw); @@ -10,14 +11,15 @@ ExportResult BankBinaryExporter::Export(std::ostream &write, std::shared_ptr<IPa writer.Write(static_cast<uint32_t>(bank->mBank.insts.size())); for (auto& instrument : bank->mBank.insts) { writer.Write(static_cast<uint8_t>(instrument.valid)); - if(!instrument.valid) continue; + if (!instrument.valid) + continue; writer.Write(instrument.releaseRate); writer.Write(instrument.normalRangeLo); writer.Write(instrument.normalRangeHi); auto [name, entries] = bank->mBank.envelopes[instrument.envelope]; - if(!entries.empty()){ + if (!entries.empty()) { writer.Write(static_cast<uint32_t>(entries.size())); for (auto& [delay, arg] : entries) { writer.Write(static_cast<uint16_t>(delay)); @@ -31,30 +33,30 @@ ExportResult BankBinaryExporter::Export(std::ostream &write, std::shared_ptr<IPa const bool hasLo = instrument.soundLo.has_value(); const bool hasMed = instrument.soundMed.has_value(); const bool hasHi = instrument.soundHi.has_value(); - if(hasLo){ + if (hasLo) { soundFlags |= 1 << 0; } - if(hasMed){ + if (hasMed) { soundFlags |= 1 << 1; } - if(hasHi){ + if (hasHi) { soundFlags |= 1 << 2; } writer.Write(soundFlags); - if(hasLo){ + if (hasLo) { auto [offset, tuning] = instrument.soundLo.value(); const uint32_t idx = AudioManager::Instance->get_index(bank->mBank.samples[offset]); writer.Write(AudioManager::Instance->get_sample(idx)); writer.Write(tuning); } - if(hasMed){ + if (hasMed) { auto [offset, tuning] = instrument.soundMed.value(); const uint32_t idx = AudioManager::Instance->get_index(bank->mBank.samples[offset]); writer.Write(AudioManager::Instance->get_sample(idx)); writer.Write(tuning); } - if(hasHi){ + if (hasHi) { auto [offset, tuning] = instrument.soundHi.value(); const uint32_t idx = AudioManager::Instance->get_index(bank->mBank.samples[offset]); writer.Write(AudioManager::Instance->get_sample(idx)); @@ -63,13 +65,13 @@ ExportResult BankBinaryExporter::Export(std::ostream &write, std::shared_ptr<IPa } writer.Write(static_cast<uint32_t>(bank->mBank.drums.size())); - for(auto &drum : bank->mBank.drums){ + for (auto& drum : bank->mBank.drums) { writer.Write(drum.releaseRate); writer.Write(drum.pan); auto envelope = bank->mBank.envelopes[drum.envelope]; - if(!envelope.entries.empty()){ + if (!envelope.entries.empty()) { writer.Write(static_cast<uint32_t>(envelope.entries.size())); - for(auto &entry : envelope.entries){ + for (auto& entry : envelope.entries) { writer.Write(entry.delay); writer.Write(entry.arg); } @@ -91,7 +93,7 @@ std::optional<std::shared_ptr<IParsedData>> BankFactory::parse(std::vector<uint8 auto banks = AudioManager::Instance->get_banks(); auto bankId = data["id"].as<uint32_t>(); - if(AudioManager::Instance == nullptr){ + if (AudioManager::Instance == nullptr) { throw std::runtime_error("AudioManager not initialized"); } diff --git a/src/factories/naudio/v0/SampleFactory.cpp b/src/factories/naudio/v0/SampleFactory.cpp index 8d25096..c800df4 100644 --- a/src/factories/naudio/v0/SampleFactory.cpp +++ b/src/factories/naudio/v0/SampleFactory.cpp @@ -6,13 +6,14 @@ #include "spdlog/spdlog.h" #include <factories/naudio/v1/AudioConverter.h> -ExportResult SampleModdingExporter::Export(std::ostream& writer, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { - auto sample = std::static_pointer_cast<SampleData>(raw); - *replacement += ".aiff"; +ExportResult SampleModdingExporter::Export(std::ostream& writer, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { + auto sample = std::static_pointer_cast<SampleData>(raw); + *replacement += ".aiff"; LUS::BinaryWriter aifc = LUS::BinaryWriter(); AudioConverter::SampleV0ToAIFC(&sample->mSample, aifc); - + LUS::BinaryWriter aiff = LUS::BinaryWriter(); write_aiff(aifc.ToVector(), aiff); aifc.Close(); @@ -20,7 +21,8 @@ ExportResult SampleModdingExporter::Export(std::ostream& writer, std::shared_ptr return std::nullopt; } -ExportResult SampleBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SampleBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto sample = std::static_pointer_cast<SampleData>(raw)->mSample; @@ -30,7 +32,7 @@ ExportResult SampleBinaryExporter::Export(std::ostream &write, std::shared_ptr<I writer.Write(sample.loop.count); writer.Write(sample.loop.pad); - if(sample.loop.state.has_value()){ + if (sample.loop.state.has_value()) { auto state = sample.loop.state.value(); writer.Write(static_cast<uint32_t>(state.size())); writer.Write(reinterpret_cast<char*>(state.data()), state.size() * sizeof(int16_t)); @@ -55,7 +57,7 @@ ExportResult SampleBinaryExporter::Export(std::ostream &write, std::shared_ptr<I std::optional<std::shared_ptr<IParsedData>> SampleFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& data) { const auto id = data["id"].as<int32_t>(); - if(AudioManager::Instance == nullptr){ + if (AudioManager::Instance == nullptr) { throw std::runtime_error("AudioManager not initialized"); } AudioBankSample entry = AudioManager::Instance->get_aifc(id); diff --git a/src/factories/naudio/v0/SequenceFactory.cpp b/src/factories/naudio/v0/SequenceFactory.cpp index 81866c7..d9c1f96 100644 --- a/src/factories/naudio/v0/SequenceFactory.cpp +++ b/src/factories/naudio/v0/SequenceFactory.cpp @@ -2,7 +2,8 @@ #include "Companion.h" #include <tinyxml2.h> -ExportResult SequenceBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SequenceBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto sequence = std::static_pointer_cast<SequenceData>(raw); @@ -12,13 +13,14 @@ ExportResult SequenceBinaryExporter::Export(std::ostream &write, std::shared_ptr for (auto& bank : sequence->mBanks) { writer.Write(bank); } - writer.Write( sequence->mSize); + writer.Write(sequence->mSize); writer.Write(reinterpret_cast<char*>(sequence->mBuffer.data()), sequence->mSize); writer.Finish(write); return std::nullopt; } -ExportResult SequenceModdingExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SequenceModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto sequence = std::static_pointer_cast<SequenceData>(raw); *replacement += ".m64"; @@ -27,9 +29,10 @@ ExportResult SequenceModdingExporter::Export(std::ostream &write, std::shared_pt return std::nullopt; } -ExportResult SequenceXMLExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SequenceXMLExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto sequence = std::static_pointer_cast<SequenceData>(raw); - + auto path = fs::path(*replacement); tinyxml2::XMLDocument seq; tinyxml2::XMLElement* root = seq.NewElement("Sequence"); @@ -48,7 +51,7 @@ ExportResult SequenceXMLExporter::Export(std::ostream &write, std::shared_ptr<IP seq.Accept(&printer); write.write(printer.CStr(), printer.CStrSize() - 1); - auto data = (char*) sequence->mBuffer.data(); + auto data = (char*)sequence->mBuffer.data(); std::vector<char> m64(data, data + sequence->mBuffer.size()); Companion::Instance->RegisterCompanionFile(path.filename().string() + "_data.m64", m64); @@ -63,6 +66,7 @@ std::optional<std::shared_ptr<IParsedData>> SequenceFactory::parse(std::vector<u return std::make_shared<SequenceData>(id, size, buffer.data() + offset, banks); } -std::optional<std::shared_ptr<IParsedData>> SequenceFactory::parse_modding(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SequenceFactory::parse_modding(std::vector<uint8_t>& buffer, + YAML::Node& node) { return std::make_shared<RawBuffer>(buffer.data(), buffer.size()); }
\ No newline at end of file diff --git a/src/factories/naudio/v1/AudioContext.cpp b/src/factories/naudio/v1/AudioContext.cpp index 6529a58..82d034a 100644 --- a/src/factories/naudio/v1/AudioContext.cpp +++ b/src/factories/naudio/v1/AudioContext.cpp @@ -8,9 +8,9 @@ NAudioDrivers AudioContext::driver = NAudioDrivers::UNKNOWN; std::optional<std::shared_ptr<IParsedData>> AudioContextFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { auto driver = GetSafeNode<std::string>(node, "driver"); - if(driver == "SF64") { + if (driver == "SF64") { AudioContext::driver = NAudioDrivers::SF64; - } else if(driver == "FZEROX"){ + } else if (driver == "FZEROX") { AudioContext::driver = NAudioDrivers::FZEROX; } else { throw std::runtime_error("Unknown NAudio driver"); @@ -28,9 +28,12 @@ std::optional<std::shared_ptr<IParsedData>> AudioContextFactory::parse(std::vect auto tableSize = GetSafeNode<uint32_t>(table, "size"); auto tableOffset = GetSafeNode<uint32_t>(table, "offset"); - AudioContext::tables[AudioTableType::SEQ_TABLE].buffer = std::vector<uint8_t>(buffer.begin() + seqOffset, buffer.begin() + seqOffset + seqSize); - AudioContext::tables[AudioTableType::FONT_TABLE].buffer = std::vector<uint8_t>(buffer.begin() + bankOffset, buffer.begin() + bankOffset + bankSize); - AudioContext::tables[AudioTableType::SAMPLE_TABLE].buffer = std::vector<uint8_t>(buffer.begin() + tableOffset, buffer.begin() + tableOffset + tableSize); + AudioContext::tables[AudioTableType::SEQ_TABLE].buffer = + std::vector<uint8_t>(buffer.begin() + seqOffset, buffer.begin() + seqOffset + seqSize); + AudioContext::tables[AudioTableType::FONT_TABLE].buffer = + std::vector<uint8_t>(buffer.begin() + bankOffset, buffer.begin() + bankOffset + bankSize); + AudioContext::tables[AudioTableType::SAMPLE_TABLE].buffer = + std::vector<uint8_t>(buffer.begin() + tableOffset, buffer.begin() + tableOffset + tableSize); AudioContext::tables[AudioTableType::SEQ_TABLE].offset = seqOffset; AudioContext::tables[AudioTableType::FONT_TABLE].offset = bankOffset; @@ -57,8 +60,8 @@ TunedSample AudioContext::LoadTunedSample(LUS::BinaryReader& reader, uint32_t pa auto sampleAddr = reader.ReadUInt32(); auto tuning = reader.ReadFloat(); - if(sampleAddr == 0){ - if(tuning != 0.0f){ + if (sampleAddr == 0) { + if (tuning != 0.0f) { throw std::runtime_error("The provided tuned sample is invalid"); } return { 0, 0, 0.0f }; @@ -76,7 +79,7 @@ TunedSample AudioContext::LoadTunedSample(LUS::BinaryReader& reader, uint32_t pa } uint64_t AudioContext::GetPathByAddr(uint32_t addr) { - if(addr == 0){ + if (addr == 0) { return 0; } diff --git a/src/factories/naudio/v1/AudioConverter.cpp b/src/factories/naudio/v1/AudioConverter.cpp index 7c4ebb4..5b49fc9 100644 --- a/src/factories/naudio/v1/AudioConverter.cpp +++ b/src/factories/naudio/v1/AudioConverter.cpp @@ -12,36 +12,34 @@ void AIFCWriter::End(std::string chunk, LUS::BinaryWriter& writer) { auto buffer = writer.ToVector(); - this->Chunks.push_back({ - chunk, buffer - }); + this->Chunks.push_back({ chunk, buffer }); this->totalSize += ALIGN(buffer.size(), 2) + 8; } -void AIFCWriter::Close(LUS::BinaryWriter& out){ +void AIFCWriter::Close(LUS::BinaryWriter& out) { out.SetEndianness(Torch::Endianness::Big); out.Write(AIFCMagicValues::FORM); - out.Write((uint32_t) (this->totalSize + 4)); + out.Write((uint32_t)(this->totalSize + 4)); out.Write(AIFCMagicValues::AIFC); - for(auto& chunk : this->Chunks){ - out.Write((char*) chunk.id.data(), chunk.id.size()); - out.Write((uint32_t) chunk.data.size()); - out.Write((char*) chunk.data.data(), chunk.data.size()); + for (auto& chunk : this->Chunks) { + out.Write((char*)chunk.id.data(), chunk.id.size()); + out.Write((uint32_t)chunk.data.size()); + out.Write((char*)chunk.data.data(), chunk.data.size()); - if(chunk.data.size() % 2 == 1) { - out.Write((uint8_t) 0); + if (chunk.data.size() % 2 == 1) { + out.Write((uint8_t)0); } } } // Function to serialize double to 80-bit extended-precision -void SerializeF80(double num, LUS::BinaryWriter &writer) { +void SerializeF80(double num, LUS::BinaryWriter& writer) { // Convert the input double to a uint64_t representation uint64_t f64; - memcpy((void*) &f64, (void*) &num, sizeof(double)); + memcpy((void*)&f64, (void*)&num, sizeof(double)); // Extract the sign bit uint64_t f64_sign_bit = f64 & (1ULL << 63); @@ -59,16 +57,16 @@ void SerializeF80(double num, LUS::BinaryWriter &writer) { // Extract the exponent and mantissa uint64_t exponent = (f64 >> 52) & 0x7FF; // Exponent bits - assert(exponent != 0); // Ensure not denormal - assert(exponent != 0x7FF); // Ensure not infinity/NaN + assert(exponent != 0); // Ensure not denormal + assert(exponent != 0x7FF); // Ensure not infinity/NaN exponent -= 1023; // Adjust bias for 64-bit uint64_t f64_mantissa_bits = f64 & ((1ULL << 52) - 1); // Mantissa bits // Construct the 80-bit extended-precision fields - uint64_t f80_sign_bit = f64_sign_bit << (80 - 64); // Shift sign - uint64_t f80_exponent = (exponent + 0x3FFF) & 0x7FFF; // Adjust bias + uint64_t f80_sign_bit = f64_sign_bit << (80 - 64); // Shift sign + uint64_t f80_exponent = (exponent + 0x3FFF) & 0x7FFF; // Adjust bias uint64_t f80_mantissa_bits = (1ULL << 63) | (f64_mantissa_bits << (63 - 52)); // Add implicit bit // Combine components into the 80-bit representation @@ -80,26 +78,26 @@ void SerializeF80(double num, LUS::BinaryWriter &writer) { writer.Write(low); } -void AudioConverter::SampleV0ToAIFC(AudioBankSample* sample, LUS::BinaryWriter &out) { +void AudioConverter::SampleV0ToAIFC(AudioBankSample* sample, LUS::BinaryWriter& out) { auto aifc = AIFCWriter(); auto data = sample->data; uint32_t num_frames = data.size() * 16 / 9; uint32_t sample_rate = -1; - if(sample->tunings.size() == 1){ + if (sample->tunings.size() == 1) { sample_rate = 32000 * sample->tunings[0]; } else { float tmin = PyUtils::min(sample->tunings); float tmax = PyUtils::max(sample->tunings); - if(tmin <= 0.5f && 0.5f <= tmax) { + if (tmin <= 0.5f && 0.5f <= tmax) { sample_rate = 16000; - } else if(tmin <= 1.0f && 1.0f <= tmax){ + } else if (tmin <= 1.0f && 1.0f <= tmax) { sample_rate = 32000; - } else if(tmin <= 1.5f && 1.5f <= tmax){ + } else if (tmin <= 1.5f && 1.5f <= tmax) { sample_rate = 48000; - } else if(tmin <= 2.5f && 2.5f <= tmax){ + } else if (tmin <= 2.5f && 2.5f <= tmax) { sample_rate = 80000; } else { sample_rate = 16000 * (tmin + tmax); @@ -116,46 +114,46 @@ void AudioConverter::SampleV0ToAIFC(AudioBankSample* sample, LUS::BinaryWriter & comm.Write(sample_size); SerializeF80(sample_rate, comm); comm.Write(AIFCMagicValues::VAPC); - comm.Write((char*) "\x0bVADPCM ~4-1", 12); + comm.Write((char*)"\x0bVADPCM ~4-1", 12); aifc.End("COMM", comm); // INST Chunk auto inst = aifc.Start(); - for(size_t i = 0; i < 5; i++){ - inst.Write((int32_t) 0); + for (size_t i = 0; i < 5; i++) { + inst.Write((int32_t)0); } aifc.End("INST", inst); // VADPCMCODES Chunk auto vcodes = aifc.Start(); - vcodes.Write((char*) "stoc\x0bVADPCMCODES", 16); - vcodes.Write((int16_t) 1); - vcodes.Write((int16_t) sample->book.order); - vcodes.Write((int16_t) sample->book.npredictors); + vcodes.Write((char*)"stoc\x0bVADPCMCODES", 16); + vcodes.Write((int16_t)1); + vcodes.Write((int16_t)sample->book.order); + vcodes.Write((int16_t)sample->book.npredictors); - for(auto page : sample->book.table){ + for (auto page : sample->book.table) { vcodes.Write(page); } aifc.End("APPL", vcodes); // SSND Chunk auto ssnd = aifc.Start(); - ssnd.Write((uint64_t) 0); - ssnd.Write((char*) data.data(), data.size()); + ssnd.Write((uint64_t)0); + ssnd.Write((char*)data.data(), data.size()); aifc.End("SSND", ssnd); // VADPCMLOOPS - if(sample->loop.count != 0){ + if (sample->loop.count != 0) { auto vloops = aifc.Start(); - vloops.Write((char*) "stoc\x0bVADPCMLOOPS", 16); - vloops.Write((uint16_t) 1); - vloops.Write((uint16_t) 1); + vloops.Write((char*)"stoc\x0bVADPCMLOOPS", 16); + vloops.Write((uint16_t)1); + vloops.Write((uint16_t)1); vloops.Write(sample->loop.start); vloops.Write(sample->loop.end); vloops.Write(sample->loop.count); - if(sample->loop.state.has_value()){ - for(auto state : sample->loop.state.value()){ + if (sample->loop.state.has_value()) { + for (auto state : sample->loop.state.value()) { vcodes.Write(state); } } @@ -165,9 +163,11 @@ void AudioConverter::SampleV0ToAIFC(AudioBankSample* sample, LUS::BinaryWriter & aifc.Close(out); } -void AudioConverter::SampleV1ToAIFC(NSampleData* sample, LUS::BinaryWriter &out) { - auto loop = std::static_pointer_cast<ADPCMLoopData>(Companion::Instance->GetParseDataByAddr(sample->loop)->data.value()); - auto book = std::static_pointer_cast<ADPCMBookData>(Companion::Instance->GetParseDataByAddr(sample->book)->data.value()); +void AudioConverter::SampleV1ToAIFC(NSampleData* sample, LUS::BinaryWriter& out) { + auto loop = + std::static_pointer_cast<ADPCMLoopData>(Companion::Instance->GetParseDataByAddr(sample->loop)->data.value()); + auto book = + std::static_pointer_cast<ADPCMBookData>(Companion::Instance->GetParseDataByAddr(sample->book)->data.value()); auto entry = AudioContext::tables[AudioTableType::SAMPLE_TABLE]; auto sampleData = entry.buffer.data() + entry.info->entries[sample->sampleBankId].addr + sample->sampleAddr; auto aifc = AIFCWriter(); @@ -176,7 +176,7 @@ void AudioConverter::SampleV1ToAIFC(NSampleData* sample, LUS::BinaryWriter &out) uint32_t num_frames = data.size() * 16 / 9; uint32_t sample_rate = sample->sampleRate; - if(sample_rate == 0){ + if (sample_rate == 0) { sample_rate = 32000 * sample->tuning; } @@ -190,45 +190,45 @@ void AudioConverter::SampleV1ToAIFC(NSampleData* sample, LUS::BinaryWriter &out) comm.Write(sample_size); SerializeF80(sample_rate, comm); comm.Write(AIFCMagicValues::VAPC); - comm.Write((char*) "\x0bVADPCM ~4-1", 12); + comm.Write((char*)"\x0bVADPCM ~4-1", 12); aifc.End("COMM", comm); // INST Chunk auto inst = aifc.Start(); - for(size_t i = 0; i < 5; i++){ - inst.Write((int32_t) 0); + for (size_t i = 0; i < 5; i++) { + inst.Write((int32_t)0); } aifc.End("INST", inst); // VADPCMCODES Chunk auto vcodes = aifc.Start(); - vcodes.Write((char*) "stoc\x0bVADPCMCODES", 16); - vcodes.Write((int16_t) 1); - vcodes.Write((int16_t) book->order); - vcodes.Write((int16_t) book->numPredictors); + vcodes.Write((char*)"stoc\x0bVADPCMCODES", 16); + vcodes.Write((int16_t)1); + vcodes.Write((int16_t)book->order); + vcodes.Write((int16_t)book->numPredictors); - for(auto page : book->book){ + for (auto page : book->book) { vcodes.Write(page); } aifc.End("APPL", vcodes); // SSND Chunk auto ssnd = aifc.Start(); - ssnd.Write((uint64_t) 0); - ssnd.Write((char*) data.data(), data.size()); + ssnd.Write((uint64_t)0); + ssnd.Write((char*)data.data(), data.size()); aifc.End("SSND", ssnd); // VADPCMLOOPS - if(loop->count != 0){ + if (loop->count != 0) { auto vloops = aifc.Start(); - vloops.Write((char*) "stoc\x0bVADPCMLOOPS", 16); - vloops.Write((uint16_t) 1); - vloops.Write((uint16_t) 1); + vloops.Write((char*)"stoc\x0bVADPCMLOOPS", 16); + vloops.Write((uint16_t)1); + vloops.Write((uint16_t)1); vloops.Write(loop->start); vloops.Write(loop->end); vloops.Write(loop->count); - for(size_t i = 0; i < 16; i++){ + for (size_t i = 0; i < 16; i++) { vloops.Write(loop->predictorState[i]); } aifc.End("APPL", vloops); diff --git a/src/factories/naudio/v1/AudioTableFactory.cpp b/src/factories/naudio/v1/AudioTableFactory.cpp index f6e37dd..cc6386f 100644 --- a/src/factories/naudio/v1/AudioTableFactory.cpp +++ b/src/factories/naudio/v1/AudioTableFactory.cpp @@ -10,52 +10,60 @@ #define HEX(c) "0x" << std::hex << std::setw(4) << std::setfill('0') << c #define ADDR(c) "0x" << std::hex << std::setw(5) << std::setfill('0') << c -static const std::unordered_map <std::string, AudioTableType> gTableTypes = { +static const std::unordered_map<std::string, AudioTableType> gTableTypes = { { "SOUNDFONT", AudioTableType::FONT_TABLE }, { "SAMPLE", AudioTableType::SAMPLE_TABLE }, { "SEQUENCE", AudioTableType::SEQ_TABLE } }; -ExportResult AudioTableHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult AudioTableHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } write << "extern AudioTable " << symbol << ";\n"; - + return std::nullopt; } -ExportResult AudioTableCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult AudioTableCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto table = std::static_pointer_cast<AudioTableData>(raw); - if(table->type == AudioTableType::FONT_TABLE){ + if (table->type == AudioTableType::FONT_TABLE) { write << "#define SOUNDFONT_ENTRY(offset, size, medium, cachePolicy, bank1, bank2, numInst, numDrums) { \\\n"; - write << fourSpaceTab << "offset, size, medium, cachePolicy, (((bank1) &0xFF) << 8) | ((bank2) &0xFF), \\\n"; - write << fourSpaceTab << fourSpaceTab << "(((numInst) &0xFF) << 8) | ((numDrums) &0xFF) \\\n}\n\n"; + write << fourSpaceTab + << "offset, size, medium, cachePolicy, (((bank1) &0xFF) << 8) | ((bank2) &0xFF), \\\n"; + write << fourSpaceTab << fourSpaceTab + << "(((numInst) &0xFF) << 8) | ((numDrums) &0xFF) \\\n}\n\n"; } write << "AudioTable " << symbol << " = {\n"; write << fourSpaceTab << "{ " << table->entries.size() << ", " << table->medium << ", " << table->addr << " },\n"; write << fourSpaceTab << "{ \n"; - for(size_t i = 0; i < table->entries.size(); i++){ - auto &entry = table->entries[i]; + for (size_t i = 0; i < table->entries.size(); i++) { + auto& entry = table->entries[i]; - if(table->type == AudioTableType::FONT_TABLE) { + if (table->type == AudioTableType::FONT_TABLE) { uint32_t numInstruments = (entry.shortData2 >> 8) & 0xFFu; uint32_t numDrums = entry.shortData2 & 0xFFu; uint32_t sampleBankId1 = (entry.shortData1 >> 8) & 0xFFu; uint32_t sampleBankId2 = entry.shortData1 & 0xFFu; - write << fourSpaceTab << fourSpaceTab << "SOUNDFONT_ENTRY(" << ADDR(entry.addr) << ", " << HEX(entry.size) << ", " << INT2((uint32_t) entry.medium) << ", " << INT2((uint32_t) entry.cachePolicy) << ", " << INT2(numInstruments) << ", " << INT2(numDrums) << ", " << INT2(sampleBankId1) << ", " << INT2(sampleBankId2) << "),\n" ; + write << fourSpaceTab << fourSpaceTab << "SOUNDFONT_ENTRY(" << ADDR(entry.addr) << ", " << HEX(entry.size) + << ", " << INT2((uint32_t)entry.medium) << ", " << INT2((uint32_t)entry.cachePolicy) << ", " + << INT2(numInstruments) << ", " << INT2(numDrums) << ", " << INT2(sampleBankId1) << ", " + << INT2(sampleBankId2) << "),\n"; } else { - write << fourSpaceTab << fourSpaceTab << "{ " << ADDR(entry.addr) << ", " << HEX(entry.size) << ", " << (uint32_t) entry.medium << ", " << (uint32_t) entry.cachePolicy << " },\n"; + write << fourSpaceTab << fourSpaceTab << "{ " << ADDR(entry.addr) << ", " << HEX(entry.size) << ", " + << (uint32_t)entry.medium << ", " << (uint32_t)entry.cachePolicy << " },\n"; } } @@ -69,20 +77,21 @@ ExportResult AudioTableCodeExporter::Export(std::ostream &write, std::shared_ptr return offset + 0x10 + (table->entries.size() * 0x10); } -ExportResult AudioTableBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult AudioTableBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<AudioTableData>(raw); WriteHeader(writer, Torch::ResourceType::AudioTable, 0); writer.Write(data->medium); writer.Write(data->addr); - writer.Write((uint32_t) data->entries.size()); + writer.Write((uint32_t)data->entries.size()); - for(auto& entry : data->entries){ - if(data->type == AudioTableType::FONT_TABLE && entry.crc == 0){ + for (auto& entry : data->entries) { + if (data->type == AudioTableType::FONT_TABLE && entry.crc == 0) { throw std::runtime_error("Fuck this thing"); } - if(entry.size == 0){ + if (entry.size == 0) { auto item = AudioContext::tables[AudioTableType::SEQ_TABLE].info->entries[entry.addr]; writer.Write(item.crc); } else { @@ -110,7 +119,7 @@ std::optional<std::shared_ptr<IParsedData>> AudioTableFactory::parse(std::vector auto format = GetSafeNode<std::string>(node, "format"); std::transform(format.begin(), format.end(), format.begin(), ::toupper); - if(!Torch::contains(gTableTypes, format)) { + if (!Torch::contains(gTableTypes, format)) { return std::nullopt; } @@ -126,7 +135,7 @@ std::optional<std::shared_ptr<IParsedData>> AudioTableFactory::parse(std::vector std::vector<AudioTableEntry> entries; - for(size_t i = 0; i < count; i++){ + for (size_t i = 0; i < count; i++) { auto addr = reader.ReadUInt32(); auto size = reader.ReadUInt32(); auto medium = reader.ReadInt8(); @@ -136,7 +145,7 @@ std::optional<std::shared_ptr<IParsedData>> AudioTableFactory::parse(std::vector auto sd3 = reader.ReadInt16(); uint64_t crc = 0; - auto entry = AudioTableEntry { addr, size, medium, policy, sd1, sd2, sd3, crc }; + auto entry = AudioTableEntry{ addr, size, medium, policy, sd1, sd2, sd3, crc }; AudioContext::tables[type].entries[addr] = entry; switch (type) { @@ -144,12 +153,12 @@ std::optional<std::shared_ptr<IParsedData>> AudioTableFactory::parse(std::vector YAML::Node font; font["type"] = "NAUDIO:V1:SOUND_FONT"; font["offset"] = addr; - font["id"] = (uint32_t) i; - font["medium"] = (int32_t) medium; - font["policy"] = (int32_t) policy; - font["sd1"] = (int32_t) sd1; - font["sd2"] = (int32_t) sd2; - font["sd3"] = (int32_t) sd3; + font["id"] = (uint32_t)i; + font["medium"] = (int32_t)medium; + font["policy"] = (int32_t)policy; + font["sd1"] = (int32_t)sd1; + font["sd2"] = (int32_t)sd2; + font["sd3"] = (int32_t)sd3; Companion::Instance->AddAsset(font); std::string path = font["vpath"].as<std::string>(); @@ -158,7 +167,7 @@ std::optional<std::shared_ptr<IParsedData>> AudioTableFactory::parse(std::vector } case AudioTableType::SEQ_TABLE: { auto parent = AudioContext::tables[AudioTableType::SEQ_TABLE].offset; - if(size != 0){ + if (size != 0) { YAML::Node seq; seq["type"] = "NAUDIO:V1:SEQUENCE"; seq["offset"] = parent + addr; diff --git a/src/factories/naudio/v1/BookFactory.cpp b/src/factories/naudio/v1/BookFactory.cpp index a501bf5..077daa3 100644 --- a/src/factories/naudio/v1/BookFactory.cpp +++ b/src/factories/naudio/v1/BookFactory.cpp @@ -2,10 +2,11 @@ #include "utils/Decompressor.h" #include "Companion.h" -ExportResult ADPCMBookHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult ADPCMBookHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -15,20 +16,22 @@ ExportResult ADPCMBookHeaderExporter::Export(std::ostream &write, std::shared_pt return std::nullopt; } -ExportResult ADPCMBookCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult ADPCMBookCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { return std::nullopt; } -ExportResult ADPCMBookBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult ADPCMBookBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<ADPCMBookData>(raw); WriteHeader(writer, Torch::ResourceType::AdpcmBook, 0); writer.Write(data->order); writer.Write(data->numPredictors); - writer.Write((uint32_t) data->book.size()); + writer.Write((uint32_t)data->book.size()); - for(auto& page : data->book){ + for (auto& page : data->book) { writer.Write(page); } @@ -46,7 +49,7 @@ std::optional<std::shared_ptr<IParsedData>> ADPCMBookFactory::parse(std::vector< book->numPredictors = reader.ReadInt32(); size_t length = 8 * book->order * book->numPredictors; - for(size_t i = 0; i < length; i++){ + for (size_t i = 0; i < length; i++) { book->book.push_back(reader.ReadInt16()); } diff --git a/src/factories/naudio/v1/DrumFactory.cpp b/src/factories/naudio/v1/DrumFactory.cpp index 38ec7cf..cc84fa6 100644 --- a/src/factories/naudio/v1/DrumFactory.cpp +++ b/src/factories/naudio/v1/DrumFactory.cpp @@ -2,10 +2,11 @@ #include "utils/Decompressor.h" #include "Companion.h" -ExportResult DrumHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult DrumHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -15,11 +16,13 @@ ExportResult DrumHeaderExporter::Export(std::ostream &write, std::shared_ptr<IPa return std::nullopt; } -ExportResult DrumCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult DrumCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { return std::nullopt; } -ExportResult DrumBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult DrumBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<DrumData>(raw); @@ -48,7 +51,8 @@ std::optional<std::shared_ptr<IParsedData>> DrumFactory::parse(std::vector<uint8 drum->adsrDecayIndex = reader.ReadInt8(); drum->pan = reader.ReadInt8(); drum->isRelocated = reader.ReadUByte(); - reader.ReadUByte();; + reader.ReadUByte(); + ; drum->tunedSample = AudioContext::LoadTunedSample(reader, parent, sampleBankId); diff --git a/src/factories/naudio/v1/EnvelopeFactory.cpp b/src/factories/naudio/v1/EnvelopeFactory.cpp index 3ba6755..be8205d 100644 --- a/src/factories/naudio/v1/EnvelopeFactory.cpp +++ b/src/factories/naudio/v1/EnvelopeFactory.cpp @@ -2,10 +2,11 @@ #include "utils/Decompressor.h" #include "Companion.h" -ExportResult EnvelopeHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult EnvelopeHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -15,17 +16,19 @@ ExportResult EnvelopeHeaderExporter::Export(std::ostream &write, std::shared_ptr return std::nullopt; } -ExportResult EnvelopeCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult EnvelopeCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { return std::nullopt; } -ExportResult EnvelopeBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult EnvelopeBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<EnvelopeData>(raw); WriteHeader(writer, Torch::ResourceType::Envelope, 0); - writer.Write((uint32_t) data->points.size()); - for(auto& point : data->points){ + writer.Write((uint32_t)data->points.size()); + for (auto& point : data->points) { writer.Write(point.delay); writer.Write(point.arg); } @@ -39,13 +42,13 @@ std::optional<std::shared_ptr<IParsedData>> EnvelopeFactory::parse(std::vector<u auto reader = AudioContext::MakeReader(AudioTableType::FONT_TABLE, offset); std::vector<EnvelopePoint> temp; - while(true) { + while (true) { int16_t delay = BSWAP16(reader.ReadInt16()); - int16_t arg = BSWAP16(reader.ReadInt16()); + int16_t arg = BSWAP16(reader.ReadInt16()); - temp.push_back({delay, arg}); + temp.push_back({ delay, arg }); - if (1 <= (-delay) % (1 << 16) && (-delay) % (1 << 16) <= 3){ + if (1 <= (-delay) % (1 << 16) && (-delay) % (1 << 16) <= 3) { break; } } diff --git a/src/factories/naudio/v1/InstrumentFactory.cpp b/src/factories/naudio/v1/InstrumentFactory.cpp index b0c8143..1a7e6db 100644 --- a/src/factories/naudio/v1/InstrumentFactory.cpp +++ b/src/factories/naudio/v1/InstrumentFactory.cpp @@ -4,10 +4,11 @@ #include "EnvelopeFactory.h" #include <tinyxml2.h> -ExportResult InstrumentHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult InstrumentHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -17,11 +18,13 @@ ExportResult InstrumentHeaderExporter::Export(std::ostream &write, std::shared_p return std::nullopt; } -ExportResult InstrumentCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult InstrumentCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { return std::nullopt; } -ExportResult InstrumentBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult InstrumentBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<InstrumentData>(raw); @@ -63,7 +66,7 @@ std::optional<std::shared_ptr<IParsedData>> InstrumentFactory::parse(std::vector envelope["offset"] = envAddr; instrument->envelope = envAddr; Companion::Instance->AddAsset(envelope); - + instrument->lowPitchTunedSample = AudioContext::LoadTunedSample(reader, parent, sampleBankId); instrument->normalPitchTunedSample = AudioContext::LoadTunedSample(reader, parent, sampleBankId); instrument->highPitchTunedSample = AudioContext::LoadTunedSample(reader, parent, sampleBankId); diff --git a/src/factories/naudio/v1/LoopFactory.cpp b/src/factories/naudio/v1/LoopFactory.cpp index 499d8c1..a6bd22a 100644 --- a/src/factories/naudio/v1/LoopFactory.cpp +++ b/src/factories/naudio/v1/LoopFactory.cpp @@ -2,10 +2,11 @@ #include "utils/Decompressor.h" #include "Companion.h" -ExportResult ADPCMLoopHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult ADPCMLoopHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -15,11 +16,13 @@ ExportResult ADPCMLoopHeaderExporter::Export(std::ostream &write, std::shared_pt return std::nullopt; } -ExportResult ADPCMLoopCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult ADPCMLoopCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { return std::nullopt; } -ExportResult ADPCMLoopBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult ADPCMLoopBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<ADPCMLoopData>(raw); @@ -27,8 +30,8 @@ ExportResult ADPCMLoopBinaryExporter::Export(std::ostream &write, std::shared_pt writer.Write(data->start); writer.Write(data->end); writer.Write(data->count); - if(data->count != 0){ - for(size_t i = 0; i < 16; i++){ + if (data->count != 0) { + for (size_t i = 0; i < 16; i++) { writer.Write(data->predictorState[i]); } } @@ -46,8 +49,8 @@ std::optional<std::shared_ptr<IParsedData>> ADPCMLoopFactory::parse(std::vector< loop->end = reader.ReadUInt32(); loop->count = reader.ReadUInt32(); - if(loop->count != 0){ - for(size_t i = 0; i < 16; i++){ + if (loop->count != 0) { + for (size_t i = 0; i < 16; i++) { loop->predictorState[i] = reader.ReadInt16(); } } diff --git a/src/factories/naudio/v1/SampleFactory.cpp b/src/factories/naudio/v1/SampleFactory.cpp index 616d883..2faafe2 100644 --- a/src/factories/naudio/v1/SampleFactory.cpp +++ b/src/factories/naudio/v1/SampleFactory.cpp @@ -7,10 +7,11 @@ #include <factories/sf64/audio/AudioDecompressor.h> #include <factories/naudio/v0/AIFCDecode.h> -ExportResult NSampleHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult NSampleHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -20,36 +21,40 @@ ExportResult NSampleHeaderExporter::Export(std::ostream &write, std::shared_ptr< return std::nullopt; } -ExportResult NSampleCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult NSampleCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { return std::nullopt; } -ExportResult NSampleBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult NSampleBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<NSampleData>(raw); WriteHeader(writer, Torch::ResourceType::Sample, 1); - writer.Write((uint8_t) data->codec); - writer.Write((uint8_t) data->medium); - writer.Write((uint8_t) data->unk); - writer.Write((uint32_t) data->size); + writer.Write((uint8_t)data->codec); + writer.Write((uint8_t)data->medium); + writer.Write((uint8_t)data->unk); + writer.Write((uint32_t)data->size); writer.Write(AudioContext::GetPathByAddr(data->loop)); writer.Write(AudioContext::GetPathByAddr(data->book)); auto table = AudioContext::tables[AudioTableType::SAMPLE_TABLE]; - writer.Write((char*) table.buffer.data() + table.info->entries[data->sampleBankId].addr + data->sampleAddr, data->size); + writer.Write((char*)table.buffer.data() + table.info->entries[data->sampleBankId].addr + data->sampleAddr, + data->size); writer.Finish(write); return std::nullopt; } -ExportResult NSampleModdingExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult NSampleModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto aiff = LUS::BinaryWriter(); auto data = std::static_pointer_cast<NSampleData>(raw); #ifdef SF64_SUPPORT - if(AudioContext::driver == NAudioDrivers::SF64 && data->codec == 2) { + if (AudioContext::driver == NAudioDrivers::SF64 && data->codec == 2) { *replacement += ".pcm"; auto table = AudioContext::tables[AudioTableType::SAMPLE_TABLE]; auto ptr = table.buffer.data() + table.info->entries[data->sampleBankId].addr + data->sampleAddr; @@ -57,7 +62,7 @@ ExportResult NSampleModdingExporter::Export(std::ostream &write, std::shared_ptr auto output = new int16_t[data->size * 2]; SF64::DecompressAudio(vec, output); auto writer = LUS::BinaryWriter(); - writer.Write((char*) output, data->size); + writer.Write((char*)output, data->size); writer.Finish(write); } else { #endif @@ -66,7 +71,7 @@ ExportResult NSampleModdingExporter::Export(std::ostream &write, std::shared_ptr AudioConverter::SampleV1ToAIFC(data.get(), aifc); auto cnv = aifc.ToVector(); - if(!cnv.empty()){ + if (!cnv.empty()) { write_aiff(cnv, aiff); aiff.Finish(write); } @@ -74,11 +79,11 @@ ExportResult NSampleModdingExporter::Export(std::ostream &write, std::shared_ptr } #endif - return std::nullopt; } -ExportResult NSampleXMLExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult NSampleXMLExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto entry = std::static_pointer_cast<NSampleData>(raw); auto path = fs::path(*replacement); @@ -93,8 +98,9 @@ ExportResult NSampleXMLExporter::Export(std::ostream &write, std::shared_ptr<IPa root->SetAttribute("Relocated", 0); root->SetAttribute("Path", (path.string() + "_data").c_str()); - if(entry->loop != 0) { - auto loop = std::static_pointer_cast<ADPCMLoopData>(Companion::Instance->GetParseDataByAddr(entry->loop)->data.value()); + if (entry->loop != 0) { + auto loop = + std::static_pointer_cast<ADPCMLoopData>(Companion::Instance->GetParseDataByAddr(entry->loop)->data.value()); tinyxml2::XMLElement* adpcmLoop = sample.NewElement("ADPCMLoop"); adpcmLoop->SetAttribute("Start", loop->start); adpcmLoop->SetAttribute("End", loop->end); @@ -108,9 +114,10 @@ ExportResult NSampleXMLExporter::Export(std::ostream &write, std::shared_ptr<IPa } root->InsertEndChild(adpcmLoop); } - - if(entry->book != 0) { - auto book = std::static_pointer_cast<ADPCMBookData>(Companion::Instance->GetParseDataByAddr(entry->book)->data.value()); + + if (entry->book != 0) { + auto book = + std::static_pointer_cast<ADPCMBookData>(Companion::Instance->GetParseDataByAddr(entry->book)->data.value()); tinyxml2::XMLElement* adpcmBook = sample.NewElement("ADPCMBook"); adpcmBook->SetAttribute("Order", book->order); adpcmBook->SetAttribute("Npredictors", book->numPredictors); @@ -159,7 +166,7 @@ std::optional<std::shared_ptr<IParsedData>> NSampleFactory::parse(std::vector<ui auto loopAddr = reader.ReadUInt32(); auto bookAddr = reader.ReadUInt32(); - if(loopAddr != 0){ + if (loopAddr != 0) { loopAddr += table.addr; YAML::Node loop; loop["type"] = "NAUDIO:V1:ADPCM_LOOP"; @@ -167,7 +174,7 @@ std::optional<std::shared_ptr<IParsedData>> NSampleFactory::parse(std::vector<ui Companion::Instance->AddAsset(loop); } - if(bookAddr != 0){ + if (bookAddr != 0) { bookAddr += table.addr; YAML::Node book; book["type"] = "NAUDIO:V1:ADPCM_BOOK"; diff --git a/src/factories/naudio/v1/SequenceFactory.cpp b/src/factories/naudio/v1/SequenceFactory.cpp index fe41498..6b34be3 100644 --- a/src/factories/naudio/v1/SequenceFactory.cpp +++ b/src/factories/naudio/v1/SequenceFactory.cpp @@ -3,10 +3,11 @@ #include "utils/Decompressor.h" #include "AudioContext.h" -ExportResult NSequenceHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult NSequenceHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -16,12 +17,13 @@ ExportResult NSequenceHeaderExporter::Export(std::ostream &write, std::shared_pt return std::nullopt; } -ExportResult NSequenceCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult NSequenceCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -33,7 +35,7 @@ ExportResult NSequenceCodeExporter::Export(std::ostream &write, std::shared_ptr< write << "\n" << tab_t; } - write << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int) data[i] << ", "; + write << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)data[i] << ", "; } write << "\n};\n"; @@ -44,23 +46,25 @@ ExportResult NSequenceCodeExporter::Export(std::ostream &write, std::shared_ptr< return offset + data.size(); } -ExportResult NSequenceModdingExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult NSequenceModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; *replacement += ".m64"; - writer.Write((char*) data.data(), data.size()); + writer.Write((char*)data.data(), data.size()); writer.Finish(write); return std::nullopt; } -ExportResult NSequenceBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult NSequenceBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; // Its the same shit as a blob WriteHeader(writer, Torch::ResourceType::Blob, 0); - writer.Write((uint32_t) data.size()); - writer.Write((char*) data.data(), data.size()); + writer.Write((uint32_t)data.size()); + writer.Write((char*)data.data(), data.size()); writer.Finish(write); return std::nullopt; } @@ -71,6 +75,7 @@ std::optional<std::shared_ptr<IParsedData>> NSequenceFactory::parse(std::vector< return std::make_shared<RawBuffer>(segment.data, segment.size); } -std::optional<std::shared_ptr<IParsedData>> NSequenceFactory::parse_modding(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> NSequenceFactory::parse_modding(std::vector<uint8_t>& buffer, + YAML::Node& node) { return std::make_shared<RawBuffer>(buffer.data(), buffer.size()); } diff --git a/src/factories/naudio/v1/SoundFontFactory.cpp b/src/factories/naudio/v1/SoundFontFactory.cpp index cd00123..9279050 100644 --- a/src/factories/naudio/v1/SoundFontFactory.cpp +++ b/src/factories/naudio/v1/SoundFontFactory.cpp @@ -8,10 +8,11 @@ #include "EnvelopeFactory.h" #include "InstrumentFactory.h" -ExportResult SoundFontHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SoundFontHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -21,11 +22,13 @@ ExportResult SoundFontHeaderExporter::Export(std::ostream &write, std::shared_pt return std::nullopt; } -ExportResult SoundFontCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SoundFontCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { return std::nullopt; } -ExportResult SoundFontBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SoundFontBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<SoundFontData>(raw); @@ -35,12 +38,12 @@ ExportResult SoundFontBinaryExporter::Export(std::ostream &write, std::shared_pt writer.Write(data->sampleBankId1); writer.Write(data->sampleBankId2); - for(auto& instrument : data->instruments){ + for (auto& instrument : data->instruments) { auto crc = AudioContext::GetPathByAddr(instrument); writer.Write(crc); } - for(auto& drum : data->drums){ + for (auto& drum : data->drums) { auto crc = AudioContext::GetPathByAddr(drum); writer.Write(crc); } @@ -49,9 +52,11 @@ ExportResult SoundFontBinaryExporter::Export(std::ostream &write, std::shared_pt return std::nullopt; } -void WriteInstrument(tinyxml2::XMLElement* parent, uint32_t offset){ - auto instrument = std::static_pointer_cast<InstrumentData>(Companion::Instance->GetParseDataByAddr(offset)->data.value()); - auto envelopeData = std::static_pointer_cast<EnvelopeData>(Companion::Instance->GetParseDataByAddr(instrument->envelope)->data.value()); +void WriteInstrument(tinyxml2::XMLElement* parent, uint32_t offset) { + auto instrument = + std::static_pointer_cast<InstrumentData>(Companion::Instance->GetParseDataByAddr(offset)->data.value()); + auto envelopeData = std::static_pointer_cast<EnvelopeData>( + Companion::Instance->GetParseDataByAddr(instrument->envelope)->data.value()); tinyxml2::XMLElement* root = parent->InsertNewChildElement("Instrument"); root->SetAttribute("NormalRangeLo", instrument->normalRangeLo); @@ -59,7 +64,7 @@ void WriteInstrument(tinyxml2::XMLElement* parent, uint32_t offset){ root->SetAttribute("ReleaseRate", instrument->adsrDecayIndex); tinyxml2::XMLElement* envelopes = root->InsertNewChildElement("Envelopes"); - for(size_t i = 0; i < envelopeData->points.size(); i++){ + for (size_t i = 0; i < envelopeData->points.size(); i++) { auto point = envelopeData->points[i]; tinyxml2::XMLElement* pointEntry = envelopes->InsertNewChildElement("Envelope"); pointEntry->SetAttribute("Delay", point.delay); @@ -71,26 +76,31 @@ void WriteInstrument(tinyxml2::XMLElement* parent, uint32_t offset){ auto normSample = instrument->normalPitchTunedSample; auto highSample = instrument->highPitchTunedSample; - if(lowSample.sample != 0 && lowSample.tuning != 0.0f){ + if (lowSample.sample != 0 && lowSample.tuning != 0.0f) { tinyxml2::XMLElement* low = root->InsertNewChildElement("LowNotesSound"); low->SetAttribute("Tuning", lowSample.tuning); - low->SetAttribute("SampleRef", (std::get<std::string>(Companion::Instance->GetNodeByAddr(lowSample.sample).value())).c_str()); + low->SetAttribute( + "SampleRef", (std::get<std::string>(Companion::Instance->GetNodeByAddr(lowSample.sample).value())).c_str()); root->InsertEndChild(low); } - if(normSample.sample != 0 && normSample.tuning != 0.0f) { + if (normSample.sample != 0 && normSample.tuning != 0.0f) { tinyxml2::XMLElement* normal = root->InsertNewChildElement("NormalNotesSound"); normal->SetAttribute("Tuning", normSample.tuning); - normal->SetAttribute("SampleRef", (std::get<std::string>(Companion::Instance->GetNodeByAddr(normSample.sample).value())).c_str()); + normal->SetAttribute( + "SampleRef", + (std::get<std::string>(Companion::Instance->GetNodeByAddr(normSample.sample).value())).c_str()); root->InsertEndChild(normal); } - if(highSample.sample != 0 && highSample.tuning != 0.0f) { + if (highSample.sample != 0 && highSample.tuning != 0.0f) { tinyxml2::XMLElement* high = root->InsertNewChildElement("HighNotesSound"); high->SetAttribute("Tuning", highSample.tuning); - high->SetAttribute("SampleRef", (std::get<std::string>(Companion::Instance->GetNodeByAddr(highSample.sample).value())).c_str()); + high->SetAttribute( + "SampleRef", + (std::get<std::string>(Companion::Instance->GetNodeByAddr(highSample.sample).value())).c_str()); root->InsertEndChild(high); } @@ -98,21 +108,23 @@ void WriteInstrument(tinyxml2::XMLElement* parent, uint32_t offset){ parent->InsertEndChild(root); } -void WriteDrum(tinyxml2::XMLElement* parent, uint32_t offset){ +void WriteDrum(tinyxml2::XMLElement* parent, uint32_t offset) { auto drum = std::static_pointer_cast<DrumData>(Companion::Instance->GetParseDataByAddr(offset)->data.value()); - auto envelopeData = std::static_pointer_cast<EnvelopeData>(Companion::Instance->GetParseDataByAddr(drum->envelope)->data.value()); + auto envelopeData = + std::static_pointer_cast<EnvelopeData>(Companion::Instance->GetParseDataByAddr(drum->envelope)->data.value()); auto sample = drum->tunedSample; tinyxml2::XMLElement* root = parent->InsertNewChildElement("Drum"); root->SetAttribute("ReleaseRate", drum->adsrDecayIndex); root->SetAttribute("Pan", drum->pan); root->SetAttribute("Loaded", 0); - root->SetAttribute("SampleRef", (std::get<std::string>(Companion::Instance->GetNodeByAddr(sample.sample).value())).c_str()); + root->SetAttribute("SampleRef", + (std::get<std::string>(Companion::Instance->GetNodeByAddr(sample.sample).value())).c_str()); root->SetAttribute("Tuning", sample.tuning); tinyxml2::XMLElement* envelopes = root->InsertNewChildElement("Envelopes"); - envelopes->SetAttribute("Count", (uint32_t) envelopeData->points.size()); - for(size_t i = 0; i < envelopeData->points.size(); i++){ + envelopes->SetAttribute("Count", (uint32_t)envelopeData->points.size()); + for (size_t i = 0; i < envelopeData->points.size(); i++) { auto point = envelopeData->points[i]; tinyxml2::XMLElement* pointEntry = envelopes->InsertNewChildElement("Envelope"); pointEntry->SetAttribute("Delay", point.delay); @@ -123,14 +135,15 @@ void WriteDrum(tinyxml2::XMLElement* parent, uint32_t offset){ parent->InsertEndChild(root); } -ExportResult SoundFontXMLExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SoundFontXMLExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, + YAML::Node& node, std::string* replacement) { auto font = std::static_pointer_cast<SoundFontData>(raw); auto id = GetSafeNode<uint32_t>(node, "id"); - auto medium = (int8_t) GetSafeNode<int32_t>(node, "medium"); - auto policy = (int8_t) GetSafeNode<int32_t>(node, "policy"); - auto sd1 = (int16_t) GetSafeNode<int32_t>(node, "sd1"); - auto sd2 = (int16_t) GetSafeNode<int32_t>(node, "sd2"); - auto sd3 = (int16_t) GetSafeNode<int32_t>(node, "sd3"); + auto medium = (int8_t)GetSafeNode<int32_t>(node, "medium"); + auto policy = (int8_t)GetSafeNode<int32_t>(node, "policy"); + auto sd1 = (int16_t)GetSafeNode<int32_t>(node, "sd1"); + auto sd2 = (int16_t)GetSafeNode<int32_t>(node, "sd2"); + auto sd3 = (int16_t)GetSafeNode<int32_t>(node, "sd3"); tinyxml2::XMLDocument doc; tinyxml2::XMLElement* root = doc.NewElement("SoundFont"); @@ -145,8 +158,8 @@ ExportResult SoundFontXMLExporter::Export(std::ostream &write, std::shared_ptr<I tinyxml2::XMLElement* drums = doc.NewElement("Drums"); drums->SetAttribute("Count", font->numDrums); - for(auto& drum : font->drums){ - if(drum == 0){ + for (auto& drum : font->drums) { + if (drum == 0) { continue; } WriteDrum(drums, drum); @@ -156,8 +169,8 @@ ExportResult SoundFontXMLExporter::Export(std::ostream &write, std::shared_ptr<I tinyxml2::XMLElement* insts = doc.NewElement("Instruments"); insts->SetAttribute("Count", font->numInstruments); - for(auto& inst : font->instruments){ - if(inst == 0){ + for (auto& inst : font->instruments) { + if (inst == 0) { continue; } WriteInstrument(insts, inst); @@ -192,12 +205,12 @@ std::optional<std::shared_ptr<IParsedData>> SoundFontFactory::parse(std::vector< uint32_t drumBaseAddr = reader.ReadUInt32(); uint32_t instBaseAddr = 4; - if(drumBaseAddr != 0){ + if (drumBaseAddr != 0) { reader.Seek(entry.addr + drumBaseAddr, LUS::SeekOffsetType::Start); - for(size_t i = 0; i < font->numDrums; i++){ + for (size_t i = 0; i < font->numDrums; i++) { uint32_t addr = reader.ReadUInt32(); - if(addr == 0){ + if (addr == 0) { font->drums.push_back(0); continue; } @@ -208,26 +221,26 @@ std::optional<std::shared_ptr<IParsedData>> SoundFontFactory::parse(std::vector< drum["type"] = "NAUDIO:V1:DRUM"; drum["parent"] = entry.addr; drum["offset"] = entry.addr + addr; - drum["sampleBankId"] = (uint32_t) font->sampleBankId1; + drum["sampleBankId"] = (uint32_t)font->sampleBankId1; Companion::Instance->AddAsset(drum); font->drums.push_back(entry.addr + addr); } -// YAML::Node table; -// table["type"] = "ASSET_ARRAY"; -// table["assetType"] = "Drum"; -// table["factoryType"] = "NAUDIO:V1:DRUM"; -// table["offset"] = entry.addr + drumBaseAddr; -// table["count"] = (uint32_t) font->numDrums; -// Companion::Instance->AddAsset(table); + // YAML::Node table; + // table["type"] = "ASSET_ARRAY"; + // table["assetType"] = "Drum"; + // table["factoryType"] = "NAUDIO:V1:DRUM"; + // table["offset"] = entry.addr + drumBaseAddr; + // table["count"] = (uint32_t) font->numDrums; + // Companion::Instance->AddAsset(table); } reader.Seek(entry.addr + instBaseAddr, LUS::SeekOffsetType::Start); - for(size_t i = 0; i < font->numInstruments; i++){ + for (size_t i = 0; i < font->numInstruments; i++) { uint32_t addr = reader.ReadUInt32(); - if(addr == 0){ + if (addr == 0) { font->instruments.push_back(0); continue; } @@ -238,19 +251,19 @@ std::optional<std::shared_ptr<IParsedData>> SoundFontFactory::parse(std::vector< instrument["type"] = "NAUDIO:V1:INSTRUMENT"; instrument["parent"] = entry.addr; instrument["offset"] = entry.addr + addr; - instrument["sampleBankId"] = (uint32_t) font->sampleBankId1; + instrument["sampleBankId"] = (uint32_t)font->sampleBankId1; font->instruments.push_back(entry.addr + addr); Companion::Instance->AddAsset(instrument); } -// YAML::Node table; -// table["type"] = "ASSET_ARRAY"; -// table["assetType"] = "Instrument"; -// table["factoryType"] = "NAUDIO:V1:INSTRUMENT"; -// table["offset"] = entry.addr + instBaseAddr; -// table["count"] = (uint32_t) font->numInstruments; -// Companion::Instance->AddAsset(table); + // YAML::Node table; + // table["type"] = "ASSET_ARRAY"; + // table["assetType"] = "Instrument"; + // table["factoryType"] = "NAUDIO:V1:INSTRUMENT"; + // table["offset"] = entry.addr + instBaseAddr; + // table["count"] = (uint32_t) font->numInstruments; + // Companion::Instance->AddAsset(table); return font; } diff --git a/src/factories/pm64/AudioFactory.cpp b/src/factories/pm64/AudioFactory.cpp index a4df6bf..8c0b0ee 100644 --- a/src/factories/pm64/AudioFactory.cpp +++ b/src/factories/pm64/AudioFactory.cpp @@ -10,32 +10,32 @@ #define SEF_SIGNATURE 0x53454620 // 'SEF ' #define PER_SIGNATURE 0x50455220 // 'PER ' #define PRG_SIGNATURE 0x50524720 // 'PRG ' -#define BK_SIGNATURE 0x424B // 'BK' +#define BK_SIGNATURE 0x424B // 'BK' #define MSEQ_SIGNATURE 0x4D534551 // 'MSEQ' // Audio file format types (upper byte of SBNFileEntry.data) // NOTE: PER and PRG share format 0x40 with MSEQ; distinguished by file signature -#define AU_FMT_BGM 0x10 -#define AU_FMT_SEF 0x20 -#define AU_FMT_BK 0x30 +#define AU_FMT_BGM 0x10 +#define AU_FMT_SEF 0x20 +#define AU_FMT_BK 0x30 #define AU_FMT_MSEQ 0x40 // Structure sizes -#define SBN_HEADER_SIZE 0x40 +#define SBN_HEADER_SIZE 0x40 #define SBN_FILE_ENTRY_SIZE 8 -#define INIT_HEADER_SIZE 0x20 +#define INIT_HEADER_SIZE 0x20 #define INIT_SONG_ENTRY_SIZE 8 #define INIT_BANK_ENTRY_SIZE 4 -#define BGM_HEADER_SIZE 0x24 -#define BK_HEADER_SIZE 0x40 -#define SEF_HEADER_SIZE 0x22 -#define MSEQ_HEADER_SIZE 0x18 -#define PER_HEADER_SIZE 0x10 +#define BGM_HEADER_SIZE 0x24 +#define BK_HEADER_SIZE 0x40 +#define SEF_HEADER_SIZE 0x22 +#define MSEQ_HEADER_SIZE 0x18 +#define PER_HEADER_SIZE 0x10 // SEF section entry counts (from game code) -#define SEF_SECTION_0_3_ENTRIES 0xC0 // 192 entries for sections 0-3 -#define SEF_SECTION_4_7_ENTRIES 0x40 // 64 entries for sections 4-7 -#define SEF_EXTRA_ENTRIES 0x140 // 320 entries for extra section +#define SEF_SECTION_0_3_ENTRIES 0xC0 // 192 entries for sections 0-3 +#define SEF_SECTION_4_7_ENTRIES 0x40 // 64 entries for sections 4-7 +#define SEF_EXTRA_ENTRIES 0x140 // 320 entries for extra section // BGMDrumInfo size #define BGM_DRUM_INFO_SIZE 0x0C @@ -65,10 +65,10 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { header32[1] = BSWAP32(header32[1]); // size uint32_t fileListOffset = BSWAP32(header32[4]); // 0x10 - uint32_t numEntries = BSWAP32(header32[5]); // 0x14 - uint32_t fullFileSize = BSWAP32(header32[6]); // 0x18 - uint32_t versionOffset = BSWAP32(header32[7]); // 0x1C - uint32_t initOffset = BSWAP32(header32[9]); // 0x24 + uint32_t numEntries = BSWAP32(header32[5]); // 0x14 + uint32_t fullFileSize = BSWAP32(header32[6]); // 0x18 + uint32_t versionOffset = BSWAP32(header32[7]); // 0x1C + uint32_t initOffset = BSWAP32(header32[9]); // 0x24 header32[4] = fileListOffset; header32[5] = numEntries; @@ -76,8 +76,8 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { header32[7] = versionOffset; header32[9] = initOffset; - SPDLOG_DEBUG("SBN: signature=0x{:08X}, fileListOffset=0x{:X}, numEntries={}, initOffset=0x{:X}", - signature, fileListOffset, numEntries, initOffset); + SPDLOG_DEBUG("SBN: signature=0x{:08X}, fileListOffset=0x{:X}, numEntries={}, initOffset=0x{:X}", signature, + fileListOffset, numEntries, initOffset); if (signature != SBN_SIGNATURE) { SPDLOG_ERROR("Invalid SBN signature: 0x{:08X}", signature); @@ -115,12 +115,13 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { uint32_t* bgm32 = reinterpret_cast<uint32_t*>(fileData); bgm32[0] = BSWAP32(bgm32[0]); // signature uint32_t bgmFileSize = BSWAP32(bgm32[1]); - bgm32[1] = bgmFileSize; // size + bgm32[1] = bgmFileSize; // size bgm32[2] = BSWAP32(bgm32[2]); // name // pad at 0x0C // BGMFileInfo at offset 0x10: - // u8 timingPreset, pad[3], u16 compositions[4], u16 drums, u16 drumCount, u16 instruments, u16 instrumentCount + // u8 timingPreset, pad[3], u16 compositions[4], u16 drums, u16 drumCount, u16 instruments, + // u16 instrumentCount uint16_t* bgm16 = reinterpret_cast<uint16_t*>(fileData + 0x14); bgm16[0] = BSWAP16(bgm16[0]); // compositions[0] bgm16[1] = BSWAP16(bgm16[1]); // compositions[1] @@ -136,7 +137,8 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { std::set<uint32_t> swappedPhrases; for (int comp = 0; comp < 4; comp++) { uint16_t compOff = bgm16[comp]; // already swapped - if (compOff == 0) continue; + if (compOff == 0) + continue; uint32_t compAbsOff = fileOffset + compOff * 4; uint32_t* cmdPtr = reinterpret_cast<uint32_t*>(data + compAbsOff); @@ -144,7 +146,8 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { // Walk composition commands until BGM_COMP_END (0x00000000) while (compAbsOff + 4 <= size) { uint32_t raw = *cmdPtr; - if (raw == 0) break; // BGM_COMP_END is 0 in both endiannesses + if (raw == 0) + break; // BGM_COMP_END is 0 in both endiannesses uint32_t swapped = BSWAP32(raw); *cmdPtr = swapped; @@ -153,8 +156,8 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { // Phrase offset is relative to compStartPos, in u32 units uint16_t phraseRelOff = swapped & 0xFFFF; uint32_t phraseAbsOff = fileOffset + compOff * 4 + phraseRelOff * 4; - if (swappedPhrases.find(phraseAbsOff) == swappedPhrases.end() - && CHECK_BOUNDS(phraseAbsOff, 16 * 4, size)) { + if (swappedPhrases.find(phraseAbsOff) == swappedPhrases.end() && + CHECK_BOUNDS(phraseAbsOff, 16 * 4, size)) { swappedPhrases.insert(phraseAbsOff); // Swap 16 u32 track info entries uint32_t* phrasePtr = reinterpret_cast<uint32_t*>(data + phraseAbsOff); @@ -202,8 +205,9 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { case AU_FMT_BK: { // BK Header: u16 signature, pad[2], s32 size, s32 name, u16 format, u8 swizzled, pad[3], - // u16 instruments[16], u16 instrumentsLength, u16 loopStatesStart, u16 loopStatesLength, - // u16 predictorsStart, u16 predictorsLength, u16 envelopesStart, u16 envelopesLength + // u16 instruments[16], u16 instrumentsLength, u16 loopStatesStart, u16 + // loopStatesLength, u16 predictorsStart, u16 predictorsLength, u16 envelopesStart, + // u16 envelopesLength if (CHECK_BOUNDS(fileOffset, BK_HEADER_SIZE, size)) { uint16_t* bk16 = reinterpret_cast<uint16_t*>(fileData); bk16[0] = BSWAP16(bk16[0]); // signature @@ -317,7 +321,8 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { for (uint32_t p = 0; p < numShorts; p++) { predData[p] = BSWAP16(predData[p]); } - SPDLOG_DEBUG("BK: swapped {} predictor shorts at offset 0x{:X}", numShorts, predictorsStart); + SPDLOG_DEBUG("BK: swapped {} predictor shorts at offset 0x{:X}", numShorts, + predictorsStart); } } @@ -330,7 +335,8 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { for (uint32_t l = 0; l < numShorts; l++) { loopData[l] = BSWAP16(loopData[l]); } - SPDLOG_DEBUG("BK: swapped {} loop state shorts at offset 0x{:X}", numShorts, loopStatesStart); + SPDLOG_DEBUG("BK: swapped {} loop state shorts at offset 0x{:X}", numShorts, + loopStatesStart); } } } @@ -342,7 +348,7 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { // u16 sections[8], u16 section2000 if (CHECK_BOUNDS(fileOffset, SEF_HEADER_SIZE, size)) { uint32_t* sef32 = reinterpret_cast<uint32_t*>(fileData); - sef32[0] = BSWAP32(sef32[0]); // signature + sef32[0] = BSWAP32(sef32[0]); // signature uint32_t sefSize = BSWAP32(sef32[1]); // size sef32[1] = sefSize; sef32[2] = BSWAP32(sef32[2]); // name @@ -367,10 +373,12 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { // Swap sections 0-3 lookup tables for (int j = 0; j < 4; j++) { - if (sectionOffsets[j] == 0) continue; + if (sectionOffsets[j] == 0) + continue; uint32_t secAbsOff = fileOffset + sectionOffsets[j]; uint32_t entryCount = SEF_SECTION_0_3_ENTRIES; - if (!CHECK_BOUNDS(secAbsOff, entryCount * 4, size)) continue; + if (!CHECK_BOUNDS(secAbsOff, entryCount * 4, size)) + continue; uint16_t* entries = reinterpret_cast<uint16_t*>(data + secAbsOff); for (uint32_t k = 0; k < entryCount; k++) { @@ -379,18 +387,20 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { entries[k * 2] = cmdOffset; entries[k * 2 + 1] = cmdInfo; - if (cmdOffset == 0) continue; + if (cmdOffset == 0) + continue; // Check for polyphonic entries (bits 5-6 of info) uint8_t polyphonyMode = (cmdInfo & 0x60) >> 5; - if (polyphonyMode != 0 && swappedSubTables.find(cmdOffset) == swappedSubTables.end()) { + if (polyphonyMode != 0 && + swappedSubTables.find(cmdOffset) == swappedSubTables.end()) { // Follow offset to polyphonic sub-table and swap it uint32_t trackCount = 2 << (polyphonyMode - 1); // 2, 4, or 8 uint32_t subTableAbsOff = fileOffset + cmdOffset; if (CHECK_BOUNDS(subTableAbsOff, trackCount * 4, size)) { uint16_t* subEntries = reinterpret_cast<uint16_t*>(data + subTableAbsOff); for (uint32_t t = 0; t < trackCount; t++) { - subEntries[t * 2] = BSWAP16(subEntries[t * 2]); // offset + subEntries[t * 2] = BSWAP16(subEntries[t * 2]); // offset subEntries[t * 2 + 1] = BSWAP16(subEntries[t * 2 + 1]); // info } } @@ -402,8 +412,8 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { // Sections 4-7: raw command bytes, no swap needed // Extra section (section2000): raw command bytes, no swap needed - SPDLOG_DEBUG("SEF: swapped {} section 0-3 lookup tables, {} polyphonic sub-tables", - 4, swappedSubTables.size()); + SPDLOG_DEBUG("SEF: swapped {} section 0-3 lookup tables, {} polyphonic sub-tables", 4, + swappedSubTables.size()); } break; } @@ -440,7 +450,8 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { } } else if (fileSig == PRG_SIGNATURE) { // PRG file: s32 signature, s32 size, pad[8], then BGMInstrumentInfo data - // BGMInstrumentInfo: u16 bankPatch, u8 volume, s8 pan, u8 reverb, s8 coarseTune, s8 fineTune, pad + // BGMInstrumentInfo: u16 bankPatch, u8 volume, s8 pan, u8 reverb, s8 coarseTune, s8 + // fineTune, pad if (CHECK_BOUNDS(fileOffset, PER_HEADER_SIZE, size)) { uint32_t* prg32 = reinterpret_cast<uint32_t*>(fileData); prg32[0] = BSWAP32(prg32[0]); // signature @@ -475,7 +486,7 @@ static void ByteSwapAudioData(uint8_t* data, size_t size) { uint16_t* mseq16 = reinterpret_cast<uint16_t*>(fileData + 0x0E); uint16_t trackSettingsOffset = BSWAP16(mseq16[0]); mseq16[0] = trackSettingsOffset; // trackSettingsOffset - mseq16[1] = BSWAP16(mseq16[1]); // dataStart + mseq16[1] = BSWAP16(mseq16[1]); // dataStart // Swap MSEQTrackData entries // Each entry: u8 trackIndex, u8 type, s16 time, s16 delta, s16 goal (8 bytes) @@ -588,7 +599,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64AudioFactory::parse(std::vector< return std::make_shared<RawBuffer>(audioData); } -ExportResult PM64AudioBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64AudioBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; @@ -601,7 +613,8 @@ ExportResult PM64AudioBinaryExporter::Export(std::ostream& write, std::shared_pt return std::nullopt; } -ExportResult PM64AudioHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64AudioHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); if (Companion::Instance->IsOTRMode()) { diff --git a/src/factories/pm64/BackgroundFactory.cpp b/src/factories/pm64/BackgroundFactory.cpp index a745cd5..c2eda63 100644 --- a/src/factories/pm64/BackgroundFactory.cpp +++ b/src/factories/pm64/BackgroundFactory.cpp @@ -29,18 +29,18 @@ static void ByteSwapBackgroundData(uint8_t* data, size_t size) { uint16_t* header16 = reinterpret_cast<uint16_t*>(data); // Swap 16-bit dimension fields first (we need these for validation) - header16[4] = BSWAP16(header16[4]); // startX at offset 0x08 - header16[5] = BSWAP16(header16[5]); // startY at offset 0x0A - header16[6] = BSWAP16(header16[6]); // width at offset 0x0C - header16[7] = BSWAP16(header16[7]); // height at offset 0x0E + header16[4] = BSWAP16(header16[4]); // startX at offset 0x08 + header16[5] = BSWAP16(header16[5]); // startY at offset 0x0A + header16[6] = BSWAP16(header16[6]); // width at offset 0x0C + header16[7] = BSWAP16(header16[7]); // height at offset 0x0E // The N64 header contains absolute VRAM addresses (0x802xxxxx) that cannot be // converted to file offsets. The background data has a fixed layout: // - Palette at offset 0x10 (right after 16-byte header) // - Raster at offset 0x210 (after header + 512-byte palette) // We ignore the N64 addresses and write the correct fixed offsets. - constexpr uint32_t paletteOffset = 0x10; // Right after 16-byte header - constexpr uint32_t rasterOffset = 0x210; // After header (16) + palette (512) + constexpr uint32_t paletteOffset = 0x10; // Right after 16-byte header + constexpr uint32_t rasterOffset = 0x210; // After header (16) + palette (512) header32[0] = rasterOffset; header32[1] = paletteOffset; @@ -49,7 +49,8 @@ static void ByteSwapBackgroundData(uint8_t* data, size_t size) { // Also, Raster data is CI8 (byte indices) - no swap needed } -std::optional<std::shared_ptr<IParsedData>> PM64BackgroundFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> PM64BackgroundFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto offset = GetSafeNode<uint32_t>(node, "offset"); // Check if compressed (YAY0) @@ -78,7 +79,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64BackgroundFactory::parse(std::ve } } -ExportResult PM64BackgroundBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64BackgroundBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; @@ -91,7 +93,8 @@ ExportResult PM64BackgroundBinaryExporter::Export(std::ostream& write, std::shar return std::nullopt; } -ExportResult PM64BackgroundHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64BackgroundHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); if (Companion::Instance->IsOTRMode()) { diff --git a/src/factories/pm64/CollisionFactory.cpp b/src/factories/pm64/CollisionFactory.cpp index 55e6a98..53a4e45 100644 --- a/src/factories/pm64/CollisionFactory.cpp +++ b/src/factories/pm64/CollisionFactory.cpp @@ -64,9 +64,10 @@ static void ByteSwapHitFileHeader(uint8_t* data, uint32_t headerOffset, size_t t uint32_t* boundingBoxesOffset = reinterpret_cast<uint32_t*>(header + 0x14); *boundingBoxesOffset = BSWAP32(*boundingBoxesOffset); - SPDLOG_DEBUG("HitFileHeader at 0x{:X}: numColliders={}, collidersOffset=0x{:X}, numVertices={}, verticesOffset=0x{:X}, bbSize={}, bbOffset=0x{:X}", - headerOffset, *numColliders, *collidersOffset, *numVertices, *verticesOffset, - *boundingBoxesDataSize, *boundingBoxesOffset); + SPDLOG_DEBUG("HitFileHeader at 0x{:X}: numColliders={}, collidersOffset=0x{:X}, numVertices={}, " + "verticesOffset=0x{:X}, bbSize={}, bbOffset=0x{:X}", + headerOffset, *numColliders, *collidersOffset, *numVertices, *verticesOffset, *boundingBoxesDataSize, + *boundingBoxesOffset); // Byte-swap colliders array (HitAssetCollider, 0x0C bytes each) uint32_t collOffset = *collidersOffset; @@ -137,7 +138,8 @@ static void ByteSwapCollisionData(uint8_t* data, size_t size) { ByteSwapHitFileHeader(data, zoneOffset, size); } -std::optional<std::shared_ptr<IParsedData>> PM64CollisionFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> PM64CollisionFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto offset = GetSafeNode<uint32_t>(node, "offset"); // Check if compressed (YAY0) @@ -166,7 +168,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64CollisionFactory::parse(std::vec } } -ExportResult PM64CollisionBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64CollisionBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; @@ -179,7 +182,8 @@ ExportResult PM64CollisionBinaryExporter::Export(std::ostream& write, std::share return std::nullopt; } -ExportResult PM64CollisionHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64CollisionHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); if (Companion::Instance->IsOTRMode()) { diff --git a/src/factories/pm64/EntityGfxFactory.cpp b/src/factories/pm64/EntityGfxFactory.cpp index 23f90b6..ecaf00b 100644 --- a/src/factories/pm64/EntityGfxFactory.cpp +++ b/src/factories/pm64/EntityGfxFactory.cpp @@ -8,22 +8,23 @@ #include "strhash64/StrHash64.h" // F3DEX2 GBI opcodes -#define F3DEX2_G_ENDDL 0xDF -#define F3DEX2_G_VTX 0x01 -#define F3DEX2_G_DL 0xDE +#define F3DEX2_G_ENDDL 0xDF +#define F3DEX2_G_VTX 0x01 +#define F3DEX2_G_DL 0xDE #define F3DEX2_G_SETTIMG 0xFD #define F3DEX2_G_MOVEMEM 0xDC -#define F3DEX2_G_MTX 0xDA +#define F3DEX2_G_MTX 0xDA // Walk a display list at the given offset, byte-swap commands from BE to native, // collect them, and recursively process nested display lists. // Buffer is const — overlapping display lists share tail commands, // so we must never modify the shared ROM data. static void WalkDisplayList(const uint8_t* data, uint32_t offset, size_t bufferSize, - std::unordered_set<uint32_t>& visited, - std::vector<PM64EntityDisplayListInfo>& collected) { - if (offset >= bufferSize - 8) return; - if (visited.count(offset)) return; + std::unordered_set<uint32_t>& visited, std::vector<PM64EntityDisplayListInfo>& collected) { + if (offset >= bufferSize - 8) + return; + if (visited.count(offset)) + return; visited.insert(offset); const uint8_t* ptr = data + offset; @@ -79,14 +80,15 @@ static void WalkDisplayList(const uint8_t* data, uint32_t offset, size_t bufferS } } -std::optional<std::shared_ptr<IParsedData>> PM64EntityGfxFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> PM64EntityGfxFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto offset = GetSafeNode<uint32_t>(node, "offset"); auto size = GetSafeNode<uint32_t>(node, "size"); auto dlistsNode = node["dlists"]; if (offset + size > buffer.size()) { - SPDLOG_ERROR("PM64:ENTITY_GFX: Data at offset 0x{:X} exceeds buffer (need {}, have {})", - offset, size, buffer.size() - offset); + SPDLOG_ERROR("PM64:ENTITY_GFX: Data at offset 0x{:X} exceeds buffer (need {}, have {})", offset, size, + buffer.size() - offset); return std::nullopt; } @@ -118,11 +120,13 @@ std::optional<std::shared_ptr<IParsedData>> PM64EntityGfxFactory::parse(std::vec if (opcode == F3DEX2_G_VTX) { uint32_t n = (w0 >> 12) & 0xFF; uint32_t end = w1 + n * 16; - if (end > maxReferencedEnd) maxReferencedEnd = end; + if (end > maxReferencedEnd) + maxReferencedEnd = end; } else if (opcode == F3DEX2_G_SETTIMG || opcode == F3DEX2_G_MTX || opcode == F3DEX2_G_MOVEMEM) { // We don't know exact sizes yet, but the offset itself must be in-bounds // Add a generous margin (textures can be large) - if (w1 >= maxReferencedEnd) maxReferencedEnd = w1 + 0x800; + if (w1 >= maxReferencedEnd) + maxReferencedEnd = w1 + 0x800; } } } @@ -259,8 +263,8 @@ static void ExportEntityDisplayList(const std::string& entityName, const PM64Ent } // Export vertex data as a Vertex resource (V1 format with float ob[]) -static void ExportVertexResource_Entity(const std::string& entityName, const uint8_t* data, - uint32_t offset, uint32_t size, uint32_t totalSize) { +static void ExportVertexResource_Entity(const std::string& entityName, const uint8_t* data, uint32_t offset, + uint32_t size, uint32_t totalSize) { char pathBuf[256]; snprintf(pathBuf, sizeof(pathBuf), "%s/vtx_%X", entityName.c_str(), offset); std::string path = pathBuf; @@ -273,13 +277,16 @@ static void ExportVertexResource_Entity(const std::string& entityName, const uin writer.Write(count); for (uint32_t i = 0; i < count; i++) { const uint8_t* src = data + offset + i * 16; - writer.Write(static_cast<int16_t>((src[0] << 8) | src[1])); // ob[0] - writer.Write(static_cast<int16_t>((src[2] << 8) | src[3])); // ob[1] - writer.Write(static_cast<int16_t>((src[4] << 8) | src[5])); // ob[2] - writer.Write(static_cast<uint16_t>((src[6] << 8) | src[7])); // flag - writer.Write(static_cast<int16_t>((src[8] << 8) | src[9])); // tc[0] - writer.Write(static_cast<int16_t>((src[10] << 8) | src[11])); // tc[1] - writer.Write(src[12]); writer.Write(src[13]); writer.Write(src[14]); writer.Write(src[15]); // cn[4] + writer.Write(static_cast<int16_t>((src[0] << 8) | src[1])); // ob[0] + writer.Write(static_cast<int16_t>((src[2] << 8) | src[3])); // ob[1] + writer.Write(static_cast<int16_t>((src[4] << 8) | src[5])); // ob[2] + writer.Write(static_cast<uint16_t>((src[6] << 8) | src[7])); // flag + writer.Write(static_cast<int16_t>((src[8] << 8) | src[9])); // tc[0] + writer.Write(static_cast<int16_t>((src[10] << 8) | src[11])); // tc[1] + writer.Write(src[12]); + writer.Write(src[13]); + writer.Write(src[14]); + writer.Write(src[15]); // cn[4] } std::stringstream ss; @@ -292,27 +299,29 @@ static void ExportVertexResource_Entity(const std::string& entityName, const uin // Map N64 fmt/siz to Torch TextureType enum value static uint32_t N64FmtSizToTextureType(uint32_t fmt, uint32_t siz) { switch (fmt) { - case 0: // G_IM_FMT_RGBA - return (siz == 3) ? 1 : 2; // RGBA32bpp or RGBA16bpp - case 2: // G_IM_FMT_CI - return (siz == 0) ? 3 : 4; // Palette4bpp or Palette8bpp - case 4: // G_IM_FMT_I - return (siz == 0) ? 5 : 6; // Grayscale4bpp or Grayscale8bpp - case 3: // G_IM_FMT_IA - if (siz == 0) return 7; // GrayscaleAlpha4bpp - if (siz == 1) return 8; // GrayscaleAlpha8bpp - return 9; // GrayscaleAlpha16bpp + case 0: // G_IM_FMT_RGBA + return (siz == 3) ? 1 : 2; // RGBA32bpp or RGBA16bpp + case 2: // G_IM_FMT_CI + return (siz == 0) ? 3 : 4; // Palette4bpp or Palette8bpp + case 4: // G_IM_FMT_I + return (siz == 0) ? 5 : 6; // Grayscale4bpp or Grayscale8bpp + case 3: // G_IM_FMT_IA + if (siz == 0) + return 7; // GrayscaleAlpha4bpp + if (siz == 1) + return 8; // GrayscaleAlpha8bpp + return 9; // GrayscaleAlpha16bpp default: - return 2; // Default to RGBA16bpp + return 2; // Default to RGBA16bpp } } // Export texture/palette data as a Texture resource (V1 format) // Fast3D interpreter reads pixel/palette data as BE byte pairs — keep raw ROM byte order. -static void ExportTextureResource(const std::string& entityName, const uint8_t* data, - uint32_t offset, uint32_t size, const char* prefix, - uint32_t settimgW0) { - if (offset + size > 0x100000) return; // Sanity check +static void ExportTextureResource(const std::string& entityName, const uint8_t* data, uint32_t offset, uint32_t size, + const char* prefix, uint32_t settimgW0) { + if (offset + size > 0x100000) + return; // Sanity check char pathBuf[256]; snprintf(pathBuf, sizeof(pathBuf), "%s/%s_%X", entityName.c_str(), prefix, offset); @@ -326,25 +335,36 @@ static void ExportTextureResource(const std::string& entityName, const uint8_t* // Compute height from data size and pixel format uint32_t bitsPerPixel; switch (siz) { - case 0: bitsPerPixel = 4; break; - case 1: bitsPerPixel = 8; break; - case 2: bitsPerPixel = 16; break; - case 3: bitsPerPixel = 32; break; - default: bitsPerPixel = 16; break; + case 0: + bitsPerPixel = 4; + break; + case 1: + bitsPerPixel = 8; + break; + case 2: + bitsPerPixel = 16; + break; + case 3: + bitsPerPixel = 32; + break; + default: + bitsPerPixel = 16; + break; } uint32_t bytesPerRow = (width * bitsPerPixel + 7) / 8; uint32_t height = (bytesPerRow > 0) ? (size / bytesPerRow) : 1; - if (height == 0) height = 1; + if (height == 0) + height = 1; auto writer = LUS::BinaryWriter(); BaseExporter::WriteHeader(writer, Torch::ResourceType::Texture, 1); - writer.Write(N64FmtSizToTextureType(fmt, siz)); // Type - writer.Write(width); // Width - writer.Write(height); // Height - writer.Write(static_cast<uint32_t>(0)); // Flags - writer.Write(1.0f); // HByteScale - writer.Write(1.0f); // VPixelScale - writer.Write(static_cast<uint32_t>(size)); // ImageDataSize + writer.Write(N64FmtSizToTextureType(fmt, siz)); // Type + writer.Write(width); // Width + writer.Write(height); // Height + writer.Write(static_cast<uint32_t>(0)); // Flags + writer.Write(1.0f); // HByteScale + writer.Write(1.0f); // VPixelScale + writer.Write(static_cast<uint32_t>(size)); // ImageDataSize writer.Write(const_cast<char*>(reinterpret_cast<const char*>(data + offset)), size); std::stringstream ss; @@ -355,9 +375,8 @@ static void ExportTextureResource(const std::string& entityName, const uint8_t* } // Export matrix data as a Blob resource — convert N64 fixed-point to float[4][4] -static void ExportMatrixBlob(const std::string& entityName, const uint8_t* data, - uint32_t offset) { - const uint32_t MTX_SIZE = 64; // N64 Mtx is 64 bytes (s15.16 interleaved) +static void ExportMatrixBlob(const std::string& entityName, const uint8_t* data, uint32_t offset) { + const uint32_t MTX_SIZE = 64; // N64 Mtx is 64 bytes (s15.16 interleaved) std::vector<uint8_t> mtxData(data + offset, data + offset + MTX_SIZE); // Byte-swap 32-bit words from BE @@ -395,8 +414,8 @@ static void ExportMatrixBlob(const std::string& entityName, const uint8_t* data, } // Export G_MOVEMEM data (lights, viewports) as a Blob resource -static void ExportMovememBlob(const std::string& entityName, const uint8_t* data, - uint32_t offset, uint32_t size, uint8_t index) { +static void ExportMovememBlob(const std::string& entityName, const uint8_t* data, uint32_t offset, uint32_t size, + uint8_t index) { std::vector<uint8_t> mmData(data + offset, data + offset + size); // Viewport data has s16 fields that need byte-swap @@ -423,7 +442,8 @@ static void ExportMovememBlob(const std::string& entityName, const uint8_t* data Companion::Instance->RegisterCompanionFile(path, fileData); } -ExportResult PM64EntityGfxBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64EntityGfxBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto entityData = std::static_pointer_cast<PM64EntityGfxData>(raw); // Extract entity name from entry path @@ -435,9 +455,9 @@ ExportResult PM64EntityGfxBinaryExporter::Export(std::ostream& write, std::share // Collect all vertex, texture, matrix, and movemem offsets from display lists std::unordered_set<uint32_t> vtxOffsets; - std::unordered_map<uint32_t, uint32_t> texInfo; // offset → G_SETTIMG w0 + std::unordered_map<uint32_t, uint32_t> texInfo; // offset → G_SETTIMG w0 std::unordered_set<uint32_t> mtxOffsets; - std::unordered_map<uint32_t, uint32_t> mmInfo; // offset → w0 + std::unordered_map<uint32_t, uint32_t> mmInfo; // offset → w0 for (const auto& dl : entityData->mDisplayLists) { for (size_t i = 0; i < dl.commands.size(); i += 2) { @@ -477,13 +497,16 @@ ExportResult PM64EntityGfxBinaryExporter::Export(std::ostream& write, std::share if (op == F3DEX2_G_VTX && w1 == vtxOff) { uint32_t n = (w0 >> 12) & 0xFF; uint32_t candidateSize = n * 16; - if (candidateSize > vtxSize) vtxSize = candidateSize; + if (candidateSize > vtxSize) + vtxSize = candidateSize; } } } - if (vtxSize == 0) vtxSize = 256; + if (vtxSize == 0) + vtxSize = 256; if (vtxOff + vtxSize <= entityData->mBuffer.size()) { - ExportVertexResource_Entity(entityName, entityData->mBuffer.data(), vtxOff, vtxSize, entityData->mBuffer.size()); + ExportVertexResource_Entity(entityName, entityData->mBuffer.data(), vtxOff, vtxSize, + entityData->mBuffer.size()); } } @@ -563,7 +586,8 @@ ExportResult PM64EntityGfxBinaryExporter::Export(std::ostream& write, std::share return std::nullopt; } -ExportResult PM64EntityGfxHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64EntityGfxHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { // Header generation handled by tools/extract-entity-offsets.py return std::nullopt; } diff --git a/src/factories/pm64/ImgFXAnimFactory.cpp b/src/factories/pm64/ImgFXAnimFactory.cpp index 503e558..f4daa66 100644 --- a/src/factories/pm64/ImgFXAnimFactory.cpp +++ b/src/factories/pm64/ImgFXAnimFactory.cpp @@ -13,41 +13,40 @@ // [0x10] Keyframe data (keyframesCount * vtxCount * 12 bytes, positions byte-swapped) // [0x10 + keyframeDataSize] GFX data (gfxCount * 8 bytes, N64 Gfx commands word-swapped) -std::optional<std::shared_ptr<IParsedData>> PM64ImgFXAnimFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> PM64ImgFXAnimFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto segmentBase = GetSafeNode<uint32_t>(node, "offset"); auto headerOffset = GetSafeNode<uint32_t>(node, "header_offset"); uint32_t headerRomAddr = segmentBase + headerOffset; if (headerRomAddr + 16 > buffer.size()) { - SPDLOG_ERROR("PM64:IMGFX_ANIM: Header at 0x{:X} exceeds buffer size 0x{:X}", - headerRomAddr, buffer.size()); + SPDLOG_ERROR("PM64:IMGFX_ANIM: Header at 0x{:X} exceeds buffer size 0x{:X}", headerRomAddr, buffer.size()); return std::nullopt; } // Read 16-byte N64 header (big-endian) uint8_t* hdr = buffer.data() + headerRomAddr; uint32_t n64KeyframesOffset = BSWAP32(*(uint32_t*)(hdr + 0x00)); - uint32_t n64GfxOffset = BSWAP32(*(uint32_t*)(hdr + 0x04)); - uint16_t vtxCount = BSWAP16(*(uint16_t*)(hdr + 0x08)); - uint16_t gfxCount = BSWAP16(*(uint16_t*)(hdr + 0x0A)); - uint16_t keyframesCount = BSWAP16(*(uint16_t*)(hdr + 0x0C)); - uint16_t flags = BSWAP16(*(uint16_t*)(hdr + 0x0E)); + uint32_t n64GfxOffset = BSWAP32(*(uint32_t*)(hdr + 0x04)); + uint16_t vtxCount = BSWAP16(*(uint16_t*)(hdr + 0x08)); + uint16_t gfxCount = BSWAP16(*(uint16_t*)(hdr + 0x0A)); + uint16_t keyframesCount = BSWAP16(*(uint16_t*)(hdr + 0x0C)); + uint16_t flags = BSWAP16(*(uint16_t*)(hdr + 0x0E)); - uint32_t keyframeDataSize = keyframesCount * vtxCount * 12; // sizeof(ImgFXVtx) = 0x0C - uint32_t gfxDataSize = gfxCount * 8; // sizeof(N64 Gfx) = 8 + uint32_t keyframeDataSize = keyframesCount * vtxCount * 12; // sizeof(ImgFXVtx) = 0x0C + uint32_t gfxDataSize = gfxCount * 8; // sizeof(N64 Gfx) = 8 uint32_t keyframesRomAddr = segmentBase + n64KeyframesOffset; uint32_t gfxRomAddr = segmentBase + n64GfxOffset; if (keyframesRomAddr + keyframeDataSize > buffer.size()) { - SPDLOG_ERROR("PM64:IMGFX_ANIM: Keyframe data at 0x{:X} (size 0x{:X}) exceeds buffer", - keyframesRomAddr, keyframeDataSize); + SPDLOG_ERROR("PM64:IMGFX_ANIM: Keyframe data at 0x{:X} (size 0x{:X}) exceeds buffer", keyframesRomAddr, + keyframeDataSize); return std::nullopt; } if (gfxRomAddr + gfxDataSize > buffer.size()) { - SPDLOG_ERROR("PM64:IMGFX_ANIM: GFX data at 0x{:X} (size 0x{:X}) exceeds buffer", - gfxRomAddr, gfxDataSize); + SPDLOG_ERROR("PM64:IMGFX_ANIM: GFX data at 0x{:X} (size 0x{:X}) exceeds buffer", gfxRomAddr, gfxDataSize); return std::nullopt; } @@ -71,9 +70,9 @@ std::optional<std::shared_ptr<IParsedData>> PM64ImgFXAnimFactory::parse(std::vec memcpy(kfDst, kfSrc, keyframeDataSize); for (uint32_t i = 0; i + 12 <= keyframeDataSize; i += 12) { uint16_t* v = reinterpret_cast<uint16_t*>(kfDst + i); - v[0] = BSWAP16(v[0]); // ob[0] - v[1] = BSWAP16(v[1]); // ob[1] - v[2] = BSWAP16(v[2]); // ob[2] + v[0] = BSWAP16(v[0]); // ob[0] + v[1] = BSWAP16(v[1]); // ob[1] + v[2] = BSWAP16(v[2]); // ob[2] // bytes 6-11: u8/s8 fields, no swap needed } @@ -90,7 +89,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64ImgFXAnimFactory::parse(std::vec return std::make_shared<RawBuffer>(blob); } -ExportResult PM64ImgFXAnimBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64ImgFXAnimBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; @@ -102,6 +102,7 @@ ExportResult PM64ImgFXAnimBinaryExporter::Export(std::ostream& write, std::share return std::nullopt; } -ExportResult PM64ImgFXAnimHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64ImgFXAnimHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { return std::nullopt; } diff --git a/src/factories/pm64/MapTextureFactory.cpp b/src/factories/pm64/MapTextureFactory.cpp index 7ccf9aa..ff652bc 100644 --- a/src/factories/pm64/MapTextureFactory.cpp +++ b/src/factories/pm64/MapTextureFactory.cpp @@ -188,7 +188,8 @@ static void ByteSwapAllTextureHeaders(uint8_t* data, size_t size) { SPDLOG_DEBUG("Byte-swapped texture headers up to offset 0x{:X}", offset); } -std::optional<std::shared_ptr<IParsedData>> PM64MapTextureFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> PM64MapTextureFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto offset = GetSafeNode<uint32_t>(node, "offset"); // Check if compressed (YAY0) @@ -230,7 +231,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64MapTextureFactory::parse(std::ve return std::make_shared<RawBuffer>(textureData); } -ExportResult PM64MapTextureBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64MapTextureBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; @@ -243,7 +245,8 @@ ExportResult PM64MapTextureBinaryExporter::Export(std::ostream& write, std::shar return std::nullopt; } -ExportResult PM64MapTextureHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64MapTextureHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); if (Companion::Instance->IsOTRMode()) { diff --git a/src/factories/pm64/ShapeFactory.cpp b/src/factories/pm64/ShapeFactory.cpp index fb1dc52..f4826a2 100644 --- a/src/factories/pm64/ShapeFactory.cpp +++ b/src/factories/pm64/ShapeFactory.cpp @@ -62,7 +62,8 @@ static std::vector<PM64DisplayListInfo>* gCollectedDisplayLists = nullptr; // Convert N64 virtual address to file offset static uint32_t N64AddrToOffset(uint32_t addr) { - if (addr == 0) return 0; + if (addr == 0) + return 0; // Check if it looks like an N64 virtual address (segment in high byte) if (addr >= 0x80000000) { @@ -87,25 +88,30 @@ static bool IsValidOffset(uint32_t offset, size_t size) { } // F3DEX2 GBI opcodes used in shape display lists -#define F3DEX2_G_ENDDL 0xDF -#define F3DEX2_G_VTX 0x01 -#define F3DEX2_G_DL 0xDE +#define F3DEX2_G_ENDDL 0xDF +#define F3DEX2_G_VTX 0x01 +#define F3DEX2_G_DL 0xDE #define F3DEX2_G_SETTIMG 0xFD // Check if an opcode is a valid F3DEX2 GBI command. // Valid ranges: 0x00-0x07 (geometry), 0xD7-0xDF (matrix/mode), 0xE4-0xFF (RDP). static bool IsValidF3DEX2Opcode(uint8_t opcode) { - if (opcode <= 0x07) return true; // G_NOOP..G_QUAD - if (opcode >= 0xD7 && opcode <= 0xDF) return true; // G_TEXTURE..G_ENDDL - if (opcode >= 0xE4) return true; // G_TEXRECT..G_SETCIMG + if (opcode <= 0x07) + return true; // G_NOOP..G_QUAD + if (opcode >= 0xD7 && opcode <= 0xDF) + return true; // G_TEXTURE..G_ENDDL + if (opcode >= 0xE4) + return true; // G_TEXRECT..G_SETCIMG return false; } // Byte-swap display list commands, convert embedded N64 addresses to file offsets, // and collect the display list for separate resource export static void ByteSwapDisplayList(uint8_t* data, uint32_t offset, size_t size) { - if (!IsValidOffset(offset, size - 8)) return; - if (gVisitedDisplayLists.count(offset)) return; // Already processed + if (!IsValidOffset(offset, size - 8)) + return; + if (gVisitedDisplayLists.count(offset)) + return; // Already processed gVisitedDisplayLists.insert(offset); uint8_t* ptr = data + offset; @@ -127,8 +133,8 @@ static void ByteSwapDisplayList(uint8_t* data, uint32_t offset, size_t size) { // Stop if we hit a non-F3DEX2 opcode — we've overrun past the display list // into adjacent data (e.g., string data, vertex data, padding). if (!IsValidF3DEX2Opcode(opcode)) { - SPDLOG_WARN("DL at 0x{:X}: invalid opcode 0x{:02X} at offset 0x{:X}, stopping", - offset, opcode, (uint32_t)(ptr - data)); + SPDLOG_WARN("DL at 0x{:X}: invalid opcode 0x{:02X} at offset 0x{:X}, stopping", offset, opcode, + (uint32_t)(ptr - data)); break; } @@ -145,7 +151,7 @@ static void ByteSwapDisplayList(uint8_t* data, uint32_t offset, size_t size) { vtxByteOffset = vtxFileOffset; } uint32_t vtxIndex = vtxByteOffset / 16; - w1 = vtxIndex * 24; // sizeof(Vtx) with GBI_FLOATS = 24 + w1 = vtxIndex * 24; // sizeof(Vtx) with GBI_FLOATS = 24 } // Handle G_SETTIMG - convert texture address to file offset @@ -176,7 +182,7 @@ static void ByteSwapDisplayList(uint8_t* data, uint32_t offset, size_t size) { break; } - ptr += 8; // Move to next Gfx command (8 bytes each) + ptr += 8; // Move to next Gfx command (8 bytes each) } // Add to collected display lists @@ -189,7 +195,8 @@ static void ByteSwapDisplayList(uint8_t* data, uint32_t offset, size_t size) { #define MODEL_PROP_KEY_TEXTURE_NAME 0x5E static void ByteSwapModelNodeProperty(uint8_t* data, uint32_t offset, size_t size) { - if (!IsValidOffset(offset, size - 0xC)) return; + if (!IsValidOffset(offset, size - 0xC)) + return; uint32_t* prop = reinterpret_cast<uint32_t*>(data + offset); int32_t key = static_cast<int32_t>(BSWAP32(prop[0])); @@ -207,7 +214,8 @@ static void ByteSwapModelNodeProperty(uint8_t* data, uint32_t offset, size_t siz } static void ByteSwapModelDisplayData(uint8_t* data, uint32_t offset, size_t size) { - if (!IsValidOffset(offset, size - 0x8)) return; + if (!IsValidOffset(offset, size - 0x8)) + return; // Track this offset so vertex byte-swapping skips it gVisitedDisplayData.insert(offset); @@ -230,8 +238,10 @@ static void ByteSwapModelGroupData(uint8_t* data, uint32_t offset, size_t size); static void ByteSwapModelNode(uint8_t* data, uint32_t offset, size_t size); static void ByteSwapModelGroupData(uint8_t* data, uint32_t offset, size_t size) { - if (!IsValidOffset(offset, size - 0x14)) return; - if (gVisitedGroups.count(offset)) return; // Already processed + if (!IsValidOffset(offset, size - 0x14)) + return; + if (gVisitedGroups.count(offset)) + return; // Already processed gVisitedGroups.insert(offset); uint32_t* group = reinterpret_cast<uint32_t*>(data + offset); @@ -291,8 +301,10 @@ static void ByteSwapModelGroupData(uint8_t* data, uint32_t offset, size_t size) } static void ByteSwapModelNode(uint8_t* data, uint32_t offset, size_t size) { - if (!IsValidOffset(offset, size - 0x14)) return; - if (gVisitedNodes.count(offset)) return; // Already processed + if (!IsValidOffset(offset, size - 0x14)) + return; + if (gVisitedNodes.count(offset)) + return; // Already processed gVisitedNodes.insert(offset); uint32_t* node = reinterpret_cast<uint32_t*>(data + offset); @@ -340,7 +352,7 @@ static uint32_t FindRootNodeOffset(uint8_t* data, size_t size) { for (uint32_t offset = 0x20; offset < size - 0x14; offset += 4) { int32_t type = static_cast<int32_t>(BSWAP32(*reinterpret_cast<uint32_t*>(data + offset))); - if (type == 7) { // SHAPE_TYPE_ROOT + if (type == 7) { // SHAPE_TYPE_ROOT // Validate surrounding fields look like a ModelNode uint32_t displayAddr = BSWAP32(*reinterpret_cast<uint32_t*>(data + offset + 0x04)); int32_t numProps = static_cast<int32_t>(BSWAP32(*reinterpret_cast<uint32_t*>(data + offset + 0x08))); @@ -361,7 +373,7 @@ static uint32_t FindRootNodeOffset(uint8_t* data, size_t size) { } static void ByteSwapShapeData(uint8_t* data, size_t size, std::vector<PM64DisplayListInfo>& collectedDLs, - uint32_t& outVtxTableOffset, uint32_t& outVtxDataSize) { + uint32_t& outVtxTableOffset, uint32_t& outVtxDataSize) { outVtxTableOffset = 0; outVtxDataSize = 0; @@ -447,27 +459,36 @@ static void ByteSwapShapeData(uint8_t* data, size_t size, std::vector<PM64Displa // This marks where non-vertex data begins (display lists, model nodes, etc.) uint32_t minVisitedOffset = size; for (uint32_t off : gVisitedNodes) { - if (off > vertexTable && off < minVisitedOffset) minVisitedOffset = off; + if (off > vertexTable && off < minVisitedOffset) + minVisitedOffset = off; } for (uint32_t off : gVisitedGroups) { - if (off > vertexTable && off < minVisitedOffset) minVisitedOffset = off; + if (off > vertexTable && off < minVisitedOffset) + minVisitedOffset = off; } for (uint32_t off : gVisitedDisplayLists) { - if (off > vertexTable && off < minVisitedOffset) minVisitedOffset = off; + if (off > vertexTable && off < minVisitedOffset) + minVisitedOffset = off; } for (uint32_t off : gVisitedDisplayData) { - if (off > vertexTable && off < minVisitedOffset) minVisitedOffset = off; + if (off > vertexTable && off < minVisitedOffset) + minVisitedOffset = off; } for (uint32_t off : gVisitedProperties) { - if (off > vertexTable && off < minVisitedOffset) minVisitedOffset = off; + if (off > vertexTable && off < minVisitedOffset) + minVisitedOffset = off; } // Also check name tables and header structures uint32_t vtxEnd = minVisitedOffset; - if (root > vertexTable && root < vtxEnd) vtxEnd = root; - if (modelNames > vertexTable && modelNames < vtxEnd) vtxEnd = modelNames; - if (colliderNames > vertexTable && colliderNames < vtxEnd) vtxEnd = colliderNames; - if (zoneNames > vertexTable && zoneNames < vtxEnd) vtxEnd = zoneNames; + if (root > vertexTable && root < vtxEnd) + vtxEnd = root; + if (modelNames > vertexTable && modelNames < vtxEnd) + vtxEnd = modelNames; + if (colliderNames > vertexTable && colliderNames < vtxEnd) + vtxEnd = colliderNames; + if (zoneNames > vertexTable && zoneNames < vtxEnd) + vtxEnd = zoneNames; size_t vtxSize = vtxEnd - vertexTable; size_t numVertices = vtxSize / 16; @@ -492,7 +513,8 @@ static void ByteSwapShapeData(uint8_t* data, size_t size, std::vector<PM64Displa // Each table is an array of BE u32 pointers to null-terminated strings. // The terminator is an entry whose pointed-to string content is literally "db". auto swapNameTable = [&](uint32_t tableOffset) { - if (!IsValidOffset(tableOffset, size - 4)) return; + if (!IsValidOffset(tableOffset, size - 4)) + return; uint32_t* names = reinterpret_cast<uint32_t*>(data + tableOffset); while (reinterpret_cast<uint8_t*>(names) < data + size - 4) { @@ -543,7 +565,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64ShapeFactory::parse(std::vector< std::vector<uint8_t> shapeData(decoded->data, decoded->data + decoded->size); ByteSwapShapeData(shapeData.data(), shapeData.size(), collectedDLs, vtxTableOffset, vtxDataSize); - return std::make_shared<PM64ShapeData>(std::move(shapeData), std::move(collectedDLs), vtxTableOffset, vtxDataSize); + return std::make_shared<PM64ShapeData>(std::move(shapeData), std::move(collectedDLs), vtxTableOffset, + vtxDataSize); } else { // Uncompressed - read raw data with size from YAML auto size = GetSafeNode<size_t>(node, "size"); @@ -552,14 +575,15 @@ std::optional<std::shared_ptr<IParsedData>> PM64ShapeFactory::parse(std::vector< std::vector<uint8_t> shapeData(segment.data, segment.data + segment.size); ByteSwapShapeData(shapeData.data(), shapeData.size(), collectedDLs, vtxTableOffset, vtxDataSize); - return std::make_shared<PM64ShapeData>(std::move(shapeData), std::move(collectedDLs), vtxTableOffset, vtxDataSize); + return std::make_shared<PM64ShapeData>(std::move(shapeData), std::move(collectedDLs), vtxTableOffset, + vtxDataSize); } } // Export vertex data as a separate OTR Vertex resource (V1 format with float ob[]) // Returns the resource path used for hashing in G_VTX_OTR_HASH commands -static std::string ExportVertexResource(const std::string& shapeName, const uint8_t* shapeData, - uint32_t vtxTableOffset, uint32_t vtxDataSize) { +static std::string ExportVertexResource(const std::string& shapeName, const uint8_t* shapeData, uint32_t vtxTableOffset, + uint32_t vtxDataSize) { if (vtxDataSize == 0) { SPDLOG_WARN("No vertex data to export for shape {}", shapeName); return ""; @@ -577,13 +601,16 @@ static std::string ExportVertexResource(const std::string& shapeName, const uint writer.Write(count); for (uint32_t i = 0; i < count; i++) { const uint8_t* src = shapeData + vtxTableOffset + i * 16; - writer.Write(*reinterpret_cast<const int16_t*>(src + 0)); // ob[0] - writer.Write(*reinterpret_cast<const int16_t*>(src + 2)); // ob[1] - writer.Write(*reinterpret_cast<const int16_t*>(src + 4)); // ob[2] - writer.Write(*reinterpret_cast<const uint16_t*>(src + 6)); // flag - writer.Write(*reinterpret_cast<const int16_t*>(src + 8)); // tc[0] - writer.Write(*reinterpret_cast<const int16_t*>(src + 10)); // tc[1] - writer.Write(src[12]); writer.Write(src[13]); writer.Write(src[14]); writer.Write(src[15]); // cn[4] + writer.Write(*reinterpret_cast<const int16_t*>(src + 0)); // ob[0] + writer.Write(*reinterpret_cast<const int16_t*>(src + 2)); // ob[1] + writer.Write(*reinterpret_cast<const int16_t*>(src + 4)); // ob[2] + writer.Write(*reinterpret_cast<const uint16_t*>(src + 6)); // flag + writer.Write(*reinterpret_cast<const int16_t*>(src + 8)); // tc[0] + writer.Write(*reinterpret_cast<const int16_t*>(src + 10)); // tc[1] + writer.Write(src[12]); + writer.Write(src[13]); + writer.Write(src[14]); + writer.Write(src[15]); // cn[4] } // Finish writing and register as companion file @@ -640,7 +667,7 @@ static void ExportDisplayListResource(const std::string& shapeName, const PM64Di if (opcode == F3DEX2_G_SETTIMG) { // Replace G_SETTIMG with G_NOOP - PM64 textures are loaded via texture handle system // G_NOOP is a standard 8-byte command - writer.Write(static_cast<uint32_t>(0x00 << 24)); // G_NOOP + writer.Write(static_cast<uint32_t>(0x00 << 24)); // G_NOOP writer.Write(static_cast<uint32_t>(0)); // NO PADDING - standard command is 8 bytes } else if (opcode == F3DEX2_G_VTX) { @@ -656,7 +683,7 @@ static void ExportDisplayListResource(const std::string& shapeName, const PM64Di // Replace opcode with G_VTX_OTR_HASH, keep n and v0 encoding uint32_t newW0 = (G_VTX_OTR_HASH << 24) | (w0 & 0x00FFFFFF); writer.Write(newW0); - writer.Write(w1); // w1 is vertex-table-relative offset + writer.Write(w1); // w1 is vertex-table-relative offset // Write hash (extra 8 bytes for expanded command) writer.Write(static_cast<uint32_t>(vtxHash >> 32)); @@ -694,7 +721,8 @@ static void ExportDisplayListResource(const std::string& shapeName, const PM64Di Companion::Instance->RegisterCompanionFile(path, data); } -ExportResult PM64ShapeBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64ShapeBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto shapeData = std::static_pointer_cast<PM64ShapeData>(raw); auto writer = LUS::BinaryWriter(); @@ -706,8 +734,8 @@ ExportResult PM64ShapeBinaryExporter::Export(std::ostream& write, std::shared_pt } // Export vertex data as a separate OTR resource - ExportVertexResource(shapeName, shapeData->mBuffer.data(), - shapeData->mVertexTableOffset, shapeData->mVertexDataSize); + ExportVertexResource(shapeName, shapeData->mBuffer.data(), shapeData->mVertexTableOffset, + shapeData->mVertexDataSize); // Export each display list as a separate OTR resource for (const auto& dlInfo : shapeData->mDisplayLists) { @@ -723,7 +751,8 @@ ExportResult PM64ShapeBinaryExporter::Export(std::ostream& write, std::shared_pt return std::nullopt; } -ExportResult PM64ShapeHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64ShapeHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); if (Companion::Instance->IsOTRMode()) { diff --git a/src/factories/pm64/SpriteFactory.cpp b/src/factories/pm64/SpriteFactory.cpp index 60d2eb2..14ac420 100644 --- a/src/factories/pm64/SpriteFactory.cpp +++ b/src/factories/pm64/SpriteFactory.cpp @@ -124,7 +124,8 @@ static void ByteSwapSpriteData(uint8_t* data, size_t size) { compData16[3] = BSWAP16(compData16[3]); // compOffset.z // Byte-swap command list (array of u16) - if (cmdListOffset > 0 && cmdListOffset < size && cmdListSize > 0 && !processedCmdLists.count(cmdListOffset)) { + if (cmdListOffset > 0 && cmdListOffset < size && cmdListSize > 0 && + !processedCmdLists.count(cmdListOffset)) { processedCmdLists.insert(cmdListOffset); uint16_t* cmdList = reinterpret_cast<uint16_t*>(data + cmdListOffset); @@ -182,7 +183,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64SpriteFactory::parse(std::vector } } -ExportResult PM64SpriteBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64SpriteBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; @@ -195,7 +197,8 @@ ExportResult PM64SpriteBinaryExporter::Export(std::ostream& write, std::shared_p return std::nullopt; } -ExportResult PM64SpriteHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64SpriteHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); if (Companion::Instance->IsOTRMode()) { diff --git a/src/factories/pm64/StoryImageFactory.cpp b/src/factories/pm64/StoryImageFactory.cpp index f87c721..79c6700 100644 --- a/src/factories/pm64/StoryImageFactory.cpp +++ b/src/factories/pm64/StoryImageFactory.cpp @@ -16,19 +16,20 @@ // NOTE: Palette is kept in big-endian format because libultraship's Fast3D // interpreter reads palette data as big-endian (see interpreter.cpp line 749, 785-786) -std::optional<std::shared_ptr<IParsedData>> PM64StoryImageFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> PM64StoryImageFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto offset = GetSafeNode<uint32_t>(node, "offset"); auto width = GetSafeNode<uint32_t>(node, "width"); auto height = GetSafeNode<uint32_t>(node, "height"); auto hasPalette = GetSafeNode<bool>(node, "has_palette"); - size_t imageSize = width * height; // CI8 or IA8 = 1 byte per pixel - size_t paletteSize = hasPalette ? 512 : 0; // 256 colors * 2 bytes + size_t imageSize = width * height; // CI8 or IA8 = 1 byte per pixel + size_t paletteSize = hasPalette ? 512 : 0; // 256 colors * 2 bytes size_t totalSize = imageSize + paletteSize; if (offset + totalSize > buffer.size()) { - SPDLOG_ERROR("PM64:STORY_IMAGE: Data at offset 0x{:X} exceeds buffer size (need {} bytes, have {})", - offset, totalSize, buffer.size() - offset); + SPDLOG_ERROR("PM64:STORY_IMAGE: Data at offset 0x{:X} exceeds buffer size (need {} bytes, have {})", offset, + totalSize, buffer.size() - offset); return std::nullopt; } @@ -42,7 +43,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64StoryImageFactory::parse(std::ve return std::make_shared<RawBuffer>(result); } -ExportResult PM64StoryImageBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64StoryImageBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; @@ -55,7 +57,8 @@ ExportResult PM64StoryImageBinaryExporter::Export(std::ostream& write, std::shar return std::nullopt; } -ExportResult PM64StoryImageHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64StoryImageHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); if (Companion::Instance->IsOTRMode()) { diff --git a/src/factories/pm64/TitleDataFactory.cpp b/src/factories/pm64/TitleDataFactory.cpp index cb2123d..b0ad1f9 100644 --- a/src/factories/pm64/TitleDataFactory.cpp +++ b/src/factories/pm64/TitleDataFactory.cpp @@ -10,7 +10,8 @@ // Sub-images are byte-addressed (IA8 = 1 byte/pixel, RGBA32 = 4 bytes/pixel) // so no byte-swapping is needed. -std::optional<std::shared_ptr<IParsedData>> PM64TitleDataFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> PM64TitleDataFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto offset = GetSafeNode<uint32_t>(node, "offset"); auto subOffset = GetSafeNode<uint32_t>(node, "sub_offset"); auto size = GetSafeNode<uint32_t>(node, "size"); @@ -23,8 +24,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64TitleDataFactory::parse(std::vec } if (subOffset + size > decoded->size) { - SPDLOG_ERROR("PM64:TITLE_DATA: Sub-image at 0x{:X} + {} exceeds decompressed size {}", - subOffset, size, decoded->size); + SPDLOG_ERROR("PM64:TITLE_DATA: Sub-image at 0x{:X} + {} exceeds decompressed size {}", subOffset, size, + decoded->size); return std::nullopt; } @@ -35,7 +36,8 @@ std::optional<std::shared_ptr<IParsedData>> PM64TitleDataFactory::parse(std::vec return std::make_shared<RawBuffer>(result); } -ExportResult PM64TitleDataBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64TitleDataBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; @@ -47,7 +49,8 @@ ExportResult PM64TitleDataBinaryExporter::Export(std::ostream& write, std::share return std::nullopt; } -ExportResult PM64TitleDataHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node& node, std::string* replacement) { +ExportResult PM64TitleDataHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); if (Companion::Instance->IsOTRMode()) { diff --git a/src/factories/sf64/AnimFactory.cpp b/src/factories/sf64/AnimFactory.cpp index ff5bc96..eae91c1 100644 --- a/src/factories/sf64/AnimFactory.cpp +++ b/src/factories/sf64/AnimFactory.cpp @@ -8,35 +8,41 @@ #define NUM_JOINT(x) std::dec << std::setfill(' ') << std::setw(5) << x #define VEC_SIZE(vec) ((vec).size() * sizeof((vec)[0])) -SF64::AnimData::AnimData(int16_t frameCount, int16_t limbCount, uint32_t dataOffset, std::vector<uint16_t> frameData, uint32_t keyOffset, std::vector<SF64::JointKey> jointKeys): mFrameCount(frameCount), mLimbCount(limbCount), mDataOffset(dataOffset), mFrameData(std::move(frameData)), mKeyOffset(keyOffset), mJointKeys(std::move(jointKeys)) { - if((mDataOffset + VEC_SIZE(mFrameData) > mKeyOffset) && (mKeyOffset + VEC_SIZE(mJointKeys) > mDataOffset)) { +SF64::AnimData::AnimData(int16_t frameCount, int16_t limbCount, uint32_t dataOffset, std::vector<uint16_t> frameData, + uint32_t keyOffset, std::vector<SF64::JointKey> jointKeys) + : mFrameCount(frameCount), mLimbCount(limbCount), mDataOffset(dataOffset), mFrameData(std::move(frameData)), + mKeyOffset(keyOffset), mJointKeys(std::move(jointKeys)) { + if ((mDataOffset + VEC_SIZE(mFrameData) > mKeyOffset) && (mKeyOffset + VEC_SIZE(mJointKeys) > mDataOffset)) { SPDLOG_ERROR("SF64:ANIM error: Data and Key offsets overlap"); } - if(mJointKeys.size() != limbCount + 1) { + if (mJointKeys.size() != limbCount + 1) { SPDLOG_ERROR("SF64:ANIM error: Joint Key count does not match Limb count"); } - if(frameData.size() > 0 && frameData[0] != 0){ + if (frameData.size() > 0 && frameData[0] != 0) { SPDLOG_INFO("SF64:ANIM alert: Found non-zero frame data on first frame"); } - if(jointKeys.size() > 0 && jointKeys[0].keys[1] != 0){ + if (jointKeys.size() > 0 && jointKeys[0].keys[1] != 0) { SPDLOG_INFO("SF64:ANIM alert: Found non-zero joint key on first frame"); } } -ExportResult SF64::AnimHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::AnimHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto anim = std::static_pointer_cast<SF64::AnimData>(raw); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } - write << "extern Animation " << symbol << "; // frames: " << std::dec << anim->mFrameCount << ", limbs: " << anim->mLimbCount + 1 << "\n"; + write << "extern Animation " << symbol << "; // frames: " << std::dec << anim->mFrameCount + << ", limbs: " << anim->mLimbCount + 1 << "\n"; return std::nullopt; } -ExportResult SF64::AnimCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::AnimCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto anim = std::static_pointer_cast<SF64::AnimData>(raw); const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -65,15 +71,15 @@ ExportResult SF64::AnimCodeExporter::Export(std::ostream &write, std::shared_ptr auto keyName = GetSafeNode(node, "data_symbol", keyDefaultName.str()); auto dataCount = anim->mFrameData.size(); - // write << "Frame data end: 0x" << std::hex << std::uppercase << (dataOffset + sizeof(uint16_t) * dataCount) << "\n"; - // write << "JointKey start: 0x" << std::hex << std::uppercase << keyOffset << "\n"; - if(dataOffset + sizeof(uint16_t) * dataCount > keyOffset) { + // write << "Frame data end: 0x" << std::hex << std::uppercase << (dataOffset + sizeof(uint16_t) * dataCount) << + // "\n"; write << "JointKey start: 0x" << std::hex << std::uppercase << keyOffset << "\n"; + if (dataOffset + sizeof(uint16_t) * dataCount > keyOffset) { dataCount = (keyOffset - dataOffset) / sizeof(uint16_t); write << "// SF64:ANIM error: Frame data overlaps joint key.\n"; } write << "u16 " << dataName << "[] = {"; - for(int i = 0; i < dataCount; i++) { - if((i % 12) == 0) { + for (int i = 0; i < dataCount; i++) { + if ((i % 12) == 0) { write << "\n" << fourSpaceTab; } write << NUM(anim->mFrameData[i]) << ","; @@ -81,9 +87,9 @@ ExportResult SF64::AnimCodeExporter::Export(std::ostream &write, std::shared_ptr write << "\n};\n\n"; write << "JointKey " << keyName << "[] = {\n"; - for(auto joint : anim->mJointKeys) { + for (auto joint : anim->mJointKeys) { write << fourSpaceTab << "{"; - for(int i = 0; i < 6; i++) { + for (int i = 0; i < 6; i++) { write << NUM_JOINT(joint.keys[i]) << ", "; } write << "},\n"; @@ -91,16 +97,15 @@ ExportResult SF64::AnimCodeExporter::Export(std::ostream &write, std::shared_ptr write << "};\n\n"; write << "Animation " << symbol << " = {\n"; - write << fourSpaceTab << anim->mFrameCount << ", " << anim->mLimbCount << ", " << dataName << ", " << keyName << ",\n"; + write << fourSpaceTab << anim->mFrameCount << ", " << anim->mLimbCount << ", " << dataName << ", " << keyName + << ",\n"; write << "};\n"; - return OffsetEntry { - anim->mDataOffset, - offset + 0xC - }; + return OffsetEntry{ anim->mDataOffset, offset + 0xC }; } -ExportResult SF64::AnimBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::AnimBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto anim = std::static_pointer_cast<SF64::AnimData>(raw); auto writer = LUS::BinaryWriter(); @@ -109,17 +114,17 @@ ExportResult SF64::AnimBinaryExporter::Export(std::ostream &write, std::shared_p writer.Write(anim->mLimbCount); auto jointSize = anim->mJointKeys.size(); - writer.Write((uint32_t) jointSize); + writer.Write((uint32_t)jointSize); SPDLOG_INFO("Joint Size: {}", jointSize); - for(auto joint : anim->mJointKeys) { - writer.Write((char*) joint.keys, sizeof(joint.keys)); + for (auto joint : anim->mJointKeys) { + writer.Write((char*)joint.keys, sizeof(joint.keys)); } auto frameSize = anim->mFrameData.size(); - writer.Write((uint32_t) frameSize); + writer.Write((uint32_t)frameSize); SPDLOG_INFO("Frame Size: {}", frameSize); - for(size_t i = 0; i < frameSize; i++) { + for (size_t i = 0; i < frameSize; i++) { writer.Write(anim->mFrameData[i]); } writer.Finish(write); @@ -149,7 +154,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::AnimFactory::parse(std::vector LUS::BinaryReader keyReader(keySegment.data, keySegment.size); keyReader.SetEndianness(Torch::Endianness::Big); - for(int i = 0; i <= limbCount; i++) { + for (int i = 0; i <= limbCount; i++) { auto xLen = keyReader.ReadUInt16(); auto x = keyReader.ReadUInt16(); maxIndex = std::max(maxIndex, (int)x); @@ -160,15 +165,15 @@ std::optional<std::shared_ptr<IParsedData>> SF64::AnimFactory::parse(std::vector auto z = keyReader.ReadUInt16(); maxIndex = std::max(maxIndex, (int)z); - jointKeys.push_back(SF64::JointKey({xLen, x, yLen, y, zLen, z})); - if(x != 0 && xLen != 0) { - dataCount += (xLen > frameCount) ? frameCount: xLen; + jointKeys.push_back(SF64::JointKey({ xLen, x, yLen, y, zLen, z })); + if (x != 0 && xLen != 0) { + dataCount += (xLen > frameCount) ? frameCount : xLen; } - if(y != 0 && yLen != 0) { - dataCount += (yLen > frameCount) ? frameCount: yLen; + if (y != 0 && yLen != 0) { + dataCount += (yLen > frameCount) ? frameCount : yLen; } - if(z != 0 && zLen != 0) { - dataCount += (zLen > frameCount) ? frameCount: zLen; + if (z != 0 && zLen != 0) { + dataCount += (zLen > frameCount) ? frameCount : zLen; } } // std::cout << dataCount << fourSpaceTab << maxIndex << "\n"; @@ -177,7 +182,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::AnimFactory::parse(std::vector LUS::BinaryReader dataReader(dataSegment.data, dataSegment.size); dataReader.SetEndianness(Torch::Endianness::Big); - for(int i = 0; i < dataCount; i++) { + for (int i = 0; i < dataCount; i++) { frameData.push_back(dataReader.ReadUInt16()); } diff --git a/src/factories/sf64/ColPolyFactory.cpp b/src/factories/sf64/ColPolyFactory.cpp index 36d58f3..04e70e0 100644 --- a/src/factories/sf64/ColPolyFactory.cpp +++ b/src/factories/sf64/ColPolyFactory.cpp @@ -6,19 +6,19 @@ #include "utils/TorchUtils.h" #include <regex> - #define NUM(x, w) std::dec << std::setfill(' ') << std::setw(w) << x #define FORMAT_FLOAT(x, w, p) std::dec << std::setfill(' ') << std::fixed << std::setprecision(p) << std::setw(w) << x -SF64::ColPolyData::ColPolyData(std::vector<SF64::CollisionPoly> polys, std::vector<YAML::Node> meshNodes): mPolys(polys), mMeshNodes(meshNodes) { - +SF64::ColPolyData::ColPolyData(std::vector<SF64::CollisionPoly> polys, std::vector<YAML::Node> meshNodes) + : mPolys(polys), mMeshNodes(meshNodes) { } -ExportResult SF64::ColPolyHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::ColPolyHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto colpolys = std::static_pointer_cast<SF64::ColPolyData>(raw); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -27,7 +27,8 @@ ExportResult SF64::ColPolyHeaderExporter::Export(std::ostream &write, std::share return std::nullopt; } -ExportResult SF64::ColPolyCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::ColPolyCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto colpolys = std::static_pointer_cast<SF64::ColPolyData>(raw); @@ -36,7 +37,7 @@ ExportResult SF64::ColPolyCodeExporter::Export(std::ostream &write, std::shared_ write << "CollisionPoly " << symbol << "[] = {"; int width = std::log10(meshSize) + 1; - for(SF64::CollisionPoly poly : colpolys->mPolys) { + for (SF64::CollisionPoly poly : colpolys->mPolys) { write << "\n" << fourSpaceTab; write << "{ " << NUM(poly.tri, width) << ", "; if (poly.unk_06 != 0) { @@ -44,7 +45,7 @@ ExportResult SF64::ColPolyCodeExporter::Export(std::ostream &write, std::shared_ write << "/* ALERT: NONZERO PAD */ "; } write << "{" << NUM(poly.norm, 6) << ", "; - if(poly.unk_0E != 0) { + if (poly.unk_0E != 0) { SPDLOG_ERROR("SF64:COLPOLY error: Nonzero value found in padding"); write << "/* ALERT: NONZERO PAD */ "; } @@ -63,15 +64,16 @@ ExportResult SF64::ColPolyCodeExporter::Export(std::ostream &write, std::shared_ return endOffset; } -ExportResult SF64::ColPolyBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::ColPolyBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto colpolys = std::static_pointer_cast<SF64::ColPolyData>(raw); WriteHeader(writer, Torch::ResourceType::ColPoly, 0); - writer.Write((uint32_t) colpolys->mPolys.size()); + writer.Write((uint32_t)colpolys->mPolys.size()); - for(auto &poly : colpolys->mPolys) { + for (auto& poly : colpolys->mPolys) { writer.Write(poly.tri.x); writer.Write(poly.tri.y); writer.Write(poly.tri.z); @@ -91,7 +93,8 @@ ExportResult SF64::ColPolyBinaryExporter::Export(std::ostream &write, std::share return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SF64::ColPolyFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SF64::ColPolyFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto count = GetSafeNode<uint32_t>(node, "count"); const auto meshCount = GetSafeNode<uint32_t>(node, "mesh_count", 1); @@ -102,7 +105,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::ColPolyFactory::parse(std::vec LUS::BinaryReader reader(segment.data, segment.size); reader.SetEndianness(Torch::Endianness::Big); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { int16_t v0 = reader.ReadInt16(); meshSize = std::max(meshSize, (int)v0); int16_t v1 = reader.ReadInt16(); @@ -116,17 +119,17 @@ std::optional<std::shared_ptr<IParsedData>> SF64::ColPolyFactory::parse(std::vec int16_t pad2 = reader.ReadInt16(); int32_t dist = reader.ReadInt32(); - polys.push_back(CollisionPoly({{v0, v1, v2}, pad1, {nx, ny, nz}, pad2, dist})); + polys.push_back(CollisionPoly({ { v0, v1, v2 }, pad1, { nx, ny, nz }, pad2, dist })); } meshSize++; auto meshOffset = GetSafeNode<uint32_t>(node, "mesh_offset", offset + count * sizeof(SF64::CollisionPoly)); - for(int j = 0; j < meshCount; j++) { + for (int j = 0; j < meshCount; j++) { YAML::Node meshNode; - if(node["mesh_symbol"]) { + if (node["mesh_symbol"]) { auto meshSymbol = GetSafeNode<std::string>(node, "mesh_symbol"); if (meshSymbol.find("OFFSET") == std::string::npos) { - if(meshCount > 1) { + if (meshCount > 1) { meshSymbol += "_" + std::to_string(j); } } else { diff --git a/src/factories/sf64/EnvironmentFactory.cpp b/src/factories/sf64/EnvironmentFactory.cpp index ae59be0..ef1fe71 100644 --- a/src/factories/sf64/EnvironmentFactory.cpp +++ b/src/factories/sf64/EnvironmentFactory.cpp @@ -5,17 +5,27 @@ #include "utils/Decompressor.h" #include "utils/TorchUtils.h" -#define VALUE_TO_ENUM(val, enumname, fallback) (Companion::Instance->GetEnumFromValue(enumname, val).value_or("/*" + std::string(fallback) + " */ " + std::to_string(val))); -#define VALUE_TO_XML_ENUM(val, enumname, fallback) (Companion::Instance->GetEnumFromValue(enumname, val).value_or(std::to_string(val))) - -SF64::EnvironmentData::EnvironmentData(int32_t type, int32_t ground, uint16_t bgColor, uint16_t seqId, int32_t fogR, int32_t fogG, int32_t fogB, int32_t fogN, int32_t fogF, Vec3f lightDir, int32_t lightR, int32_t lightG, int32_t lightB, int32_t ambR, int32_t ambG, int32_t ambB): mType(type), mGround(ground), mBgColor(bgColor), mSeqId(seqId), mFogR(fogR), mFogG(fogG), mFogB(fogB), mFogN(fogN), mFogF(fogF), mLightDir(lightDir), mLightR(lightR), mLightG(lightG), mLightB(lightB), mAmbR(ambR), mAmbG(ambG), mAmbB(ambB) { - +#define VALUE_TO_ENUM(val, enumname, fallback) \ + (Companion::Instance->GetEnumFromValue(enumname, val) \ + .value_or("/*" + std::string(fallback) + " */ " + std::to_string(val))); +#define VALUE_TO_XML_ENUM(val, enumname, fallback) \ + (Companion::Instance->GetEnumFromValue(enumname, val).value_or(std::to_string(val))) + +SF64::EnvironmentData::EnvironmentData(int32_t type, int32_t ground, uint16_t bgColor, uint16_t seqId, int32_t fogR, + int32_t fogG, int32_t fogB, int32_t fogN, int32_t fogF, Vec3f lightDir, + int32_t lightR, int32_t lightG, int32_t lightB, int32_t ambR, int32_t ambG, + int32_t ambB) + : mType(type), mGround(ground), mBgColor(bgColor), mSeqId(seqId), mFogR(fogR), mFogG(fogG), mFogB(fogB), + mFogN(fogN), mFogF(fogF), mLightDir(lightDir), mLightR(lightR), mLightG(lightG), mLightB(lightB), mAmbR(ambR), + mAmbG(ambG), mAmbB(ambB) { } -ExportResult SF64::EnvironmentHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::EnvironmentHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -24,7 +34,8 @@ ExportResult SF64::EnvironmentHeaderExporter::Export(std::ostream &write, std::s return std::nullopt; } -ExportResult SF64::EnvironmentCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::EnvironmentCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto env = std::static_pointer_cast<SF64::EnvironmentData>(raw); @@ -39,7 +50,8 @@ ExportResult SF64::EnvironmentCodeExporter::Export(std::ostream &write, std::sha if (env->mSeqId == 0xFFFF) { write << "SEQ_ID_NONE, "; } else { - auto seqId = Companion::Instance->GetEnumFromValue("BgmSeqIds", env->mSeqId & 0xFF).value_or("/* SEQ_ID_UNK */ " + std::to_string(env->mSeqId)); + auto seqId = Companion::Instance->GetEnumFromValue("BgmSeqIds", env->mSeqId & 0xFF) + .value_or("/* SEQ_ID_UNK */ " + std::to_string(env->mSeqId)); write << seqId << ((env->mSeqId < 0x8000) ? "" : " | SEQ_FLAG") << ", "; } write << std::dec << env->mFogR << ", "; @@ -59,7 +71,9 @@ ExportResult SF64::EnvironmentCodeExporter::Export(std::ostream &write, std::sha return offset + sizeof(EnvironmentData); } -ExportResult SF64::EnvironmentBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::EnvironmentBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); auto environment = std::static_pointer_cast<SF64::EnvironmentData>(raw); @@ -88,7 +102,8 @@ ExportResult SF64::EnvironmentBinaryExporter::Export(std::ostream &write, std::s return std::nullopt; } -void AppendNode(tinyxml2::XMLDocument& doc, tinyxml2::XMLElement* root, const std::string& name, const std::string value) { +void AppendNode(tinyxml2::XMLDocument& doc, tinyxml2::XMLElement* root, const std::string& name, + const std::string value) { auto node = doc.NewElement(name.c_str()); node->SetText(value.c_str()); root->InsertEndChild(node); @@ -101,7 +116,7 @@ void AppendSeqNode(tinyxml2::XMLDocument& doc, tinyxml2::XMLElement* root, uint1 node->SetAttribute("Flag", "0"); } else { bool flag = id < 0x8000; - if(!flag) { + if (!flag) { id &= 0x7FFF; } node->SetText(VALUE_TO_XML_ENUM(id, "BgmSeqIds", std::to_string(id)).c_str()); @@ -110,7 +125,8 @@ void AppendSeqNode(tinyxml2::XMLDocument& doc, tinyxml2::XMLElement* root, uint1 root->InsertEndChild(node); } -ExportResult SF64::EnvironmentXMLExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::EnvironmentXMLExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto env = std::static_pointer_cast<SF64::EnvironmentData>(raw); @@ -166,29 +182,31 @@ ExportResult SF64::EnvironmentXMLExporter::Export(std::ostream &write, std::shar return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SF64::EnvironmentFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SF64::EnvironmentFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer, sizeof(SF64::EnvironmentData)); LUS::BinaryReader reader(segment.data, segment.size); reader.SetEndianness(Torch::Endianness::Big); Vec3f lightDir; - int32_t type = reader.ReadInt32(); - int32_t ground = reader.ReadInt32(); + int32_t type = reader.ReadInt32(); + int32_t ground = reader.ReadInt32(); uint16_t bgColor = reader.ReadUInt16(); uint16_t seqId = reader.ReadUInt16(); - int32_t fogR = reader.ReadInt32(); - int32_t fogG = reader.ReadInt32(); - int32_t fogB = reader.ReadInt32(); - int32_t fogN = reader.ReadInt32(); - int32_t fogF = reader.ReadInt32(); + int32_t fogR = reader.ReadInt32(); + int32_t fogG = reader.ReadInt32(); + int32_t fogB = reader.ReadInt32(); + int32_t fogN = reader.ReadInt32(); + int32_t fogF = reader.ReadInt32(); lightDir.x = reader.ReadFloat(); lightDir.y = reader.ReadFloat(); lightDir.z = reader.ReadFloat(); - int32_t lightR = reader.ReadInt32(); - int32_t lightG = reader.ReadInt32(); - int32_t lightB = reader.ReadInt32(); - int32_t ambR = reader.ReadInt32(); - int32_t ambG = reader.ReadInt32(); - int32_t ambB = reader.ReadInt32(); - - return std::make_shared<SF64::EnvironmentData>(type, ground, bgColor, seqId, fogR, fogG, fogB, fogN, fogF, lightDir, lightR, lightG, lightB, ambR, ambG, ambB); + int32_t lightR = reader.ReadInt32(); + int32_t lightG = reader.ReadInt32(); + int32_t lightB = reader.ReadInt32(); + int32_t ambR = reader.ReadInt32(); + int32_t ambG = reader.ReadInt32(); + int32_t ambB = reader.ReadInt32(); + + return std::make_shared<SF64::EnvironmentData>(type, ground, bgColor, seqId, fogR, fogG, fogB, fogN, fogF, lightDir, + lightR, lightG, lightB, ambR, ambG, ambB); } diff --git a/src/factories/sf64/HitboxFactory.cpp b/src/factories/sf64/HitboxFactory.cpp index b6b11a6..6f762ee 100644 --- a/src/factories/sf64/HitboxFactory.cpp +++ b/src/factories/sf64/HitboxFactory.cpp @@ -10,7 +10,7 @@ static int GetPrecision(float f) { int shift = 1; float approx = std::round(f); - while(f != approx && p < 12 ){ + while (f != approx && p < 12) { shift *= 10; p++; approx = std::round(f * shift) / shift; @@ -19,21 +19,22 @@ static int GetPrecision(float f) { } static void FormatFloat(std::ostream& out, const float x, int w) { - if(x == (int) x) { + if (x == (int)x) { out << std::dec << std::fixed << std::setprecision(0) << std::setfill(' ') << std::setw(w - 2) << x << ".0f"; } else { - out << std::dec << std::fixed << std::setprecision(GetPrecision(x)) << std::setfill(' ') << std::setw(w) << x << "f"; + out << std::dec << std::fixed << std::setprecision(GetPrecision(x)) << std::setfill(' ') << std::setw(w) << x + << "f"; } } -SF64::HitboxData::HitboxData(std::vector<float> data, std::vector<int> types): mData(data), mTypes(types) { - +SF64::HitboxData::HitboxData(std::vector<float> data, std::vector<int> types) : mData(data), mTypes(types) { } -ExportResult SF64::HitboxHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::HitboxHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -42,7 +43,8 @@ ExportResult SF64::HitboxHeaderExporter::Export(std::ostream &write, std::shared return std::nullopt; } -ExportResult SF64::HitboxCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::HitboxCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto hitbox = std::static_pointer_cast<SF64::HitboxData>(raw); @@ -50,8 +52,8 @@ ExportResult SF64::HitboxCodeExporter::Export(std::ostream &write, std::shared_p auto count = hitbox->mData[index++]; auto hasRot = false; - for(int type : hitbox->mTypes) { - if(type == 2) { + for (int type : hitbox->mTypes) { + if (type == 2) { hasRot = true; break; } @@ -60,8 +62,8 @@ ExportResult SF64::HitboxCodeExporter::Export(std::ostream &write, std::shared_p write << "f32 " << symbol << "[] = {\n"; write << fourSpaceTab << count << ",\n"; - for(int i = 0; i < (int)count; i++) { - if(hitbox->mTypes[i] == 4) { + for (int i = 0; i < (int)count; i++) { + if (hitbox->mTypes[i] == 4) { write << fourSpaceTab << "HITBOX_WHOOSH, "; index++; } else if (hitbox->mTypes[i] == 3) { @@ -70,7 +72,7 @@ ExportResult SF64::HitboxCodeExporter::Export(std::ostream &write, std::shared_p } else if (hitbox->mTypes[i] == 2) { write << fourSpaceTab << "HITBOX_ROTATED, "; index++; - for(int j = 0; j < 3; j++) { + for (int j = 0; j < 3; j++) { auto tempf = hitbox->mData[index++]; FormatFloat(write, tempf, 6); write << ", "; @@ -78,12 +80,12 @@ ExportResult SF64::HitboxCodeExporter::Export(std::ostream &write, std::shared_p } else { write << " /* HITBOX_STANDARD */ "; } - if(hasRot && hitbox->mTypes[i] != 2) { - for(int j = 0; j < 7; j++) { + if (hasRot && hitbox->mTypes[i] != 2) { + for (int j = 0; j < 7; j++) { write << fourSpaceTab; } } - for(int j = 0; j < 6; j++) { + for (int j = 0; j < 6; j++) { auto tempf = hitbox->mData[index++]; FormatFloat(write, tempf, 7); write << ", "; @@ -95,15 +97,16 @@ ExportResult SF64::HitboxCodeExporter::Export(std::ostream &write, std::shared_p return offset + sizeof(float) * index; } -ExportResult SF64::HitboxBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::HitboxBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto hitbox = std::static_pointer_cast<SF64::HitboxData>(raw); auto writer = LUS::BinaryWriter(); WriteHeader(writer, Torch::ResourceType::Hitbox, 0); auto count = hitbox->mData.size(); - writer.Write((uint32_t) count); - for(size_t i = 0; i < hitbox->mData.size(); i++) { + writer.Write((uint32_t)count); + for (size_t i = 0; i < hitbox->mData.size(); i++) { writer.Write(hitbox->mData[i]); } writer.Finish(write); @@ -121,10 +124,10 @@ std::optional<std::shared_ptr<IParsedData>> SF64::HitboxFactory::parse(std::vect data.push_back(reader.ReadFloat()); count = data[0]; - while(count > 0) { + while (count > 0) { auto typecode = reader.ReadFloat(); auto readCount = 0; - if(typecode == 300000.0f || typecode == 400000.0f) { + if (typecode == 300000.0f || typecode == 400000.0f) { readCount = 6; types.push_back((typecode == 300000.0f) ? 3 : 4); } else if (typecode == 200000.0f) { @@ -135,7 +138,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::HitboxFactory::parse(std::vect types.push_back(1); } data.push_back(typecode); - for(int i = 0; i < readCount; i++) { + for (int i = 0; i < readCount; i++) { data.push_back(reader.ReadFloat()); } count--; diff --git a/src/factories/sf64/MessageFactory.cpp b/src/factories/sf64/MessageFactory.cpp index 0d1b527..e71283d 100644 --- a/src/factories/sf64/MessageFactory.cpp +++ b/src/factories/sf64/MessageFactory.cpp @@ -32,47 +32,37 @@ #define PIP 59 std::vector<std::string> gCharCodeEnums = { - "END", "NWL", "NP2", "NP3", "NP4", "NP5", "NP6", "NP7", - "PRI0", "PRI1", "PRI2", "PRI3", "SPC", "HSP", "QSP", "NXT", - "CLF", "CUP", "CRT", "CDN", "AUP", "ALF", "ADN", "ART", - "_A", "_B", "_C", "_D", "_E", "_F", "_G", "_H", - "_I", "_J", "_K", "_L", "_M", "_N", "_O", "_P", - "_Q", "_R", "_S", "_T", "_U", "_V", "_W", "_X", - "_Y", "_Z", "_a", "_b", "_c", "_d", "_e", "_f", - "_g", "_h", "_i", "_j", "_k", "_l", "_m", "_n", - "_o", "_p", "_q", "_r", "_s", "_t", "_u", "_v", - "_w", "_x", "_y", "_z", "EXM", "QST", "DSH", "CMA", - "PRD", "_0", "_1", "_2", "_3", "_4", "_5", "_6", - "_7", "_8", "_9", "APS", "LPR", "RPR", "CLN", "PIP", + "END", "NWL", "NP2", "NP3", "NP4", "NP5", "NP6", "NP7", "PRI0", "PRI1", "PRI2", "PRI3", "SPC", "HSP", "QSP", "NXT", + "CLF", "CUP", "CRT", "CDN", "AUP", "ALF", "ADN", "ART", "_A", "_B", "_C", "_D", "_E", "_F", "_G", "_H", + "_I", "_J", "_K", "_L", "_M", "_N", "_O", "_P", "_Q", "_R", "_S", "_T", "_U", "_V", "_W", "_X", + "_Y", "_Z", "_a", "_b", "_c", "_d", "_e", "_f", "_g", "_h", "_i", "_j", "_k", "_l", "_m", "_n", + "_o", "_p", "_q", "_r", "_s", "_t", "_u", "_v", "_w", "_x", "_y", "_z", "EXM", "QST", "DSH", "CMA", + "PRD", "_0", "_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9", "APS", "LPR", "RPR", "CLN", "PIP", }; std::unordered_map<std::string, std::string> ASCIITable = { - { "CLF", "(C<)" }, { "CUP", "(C^)" }, { "CRT", "(C>)" }, { "CDN", "(Cv)" }, - { "AUP", "^" }, { "ALF", "<" }, { "ADN", "v" }, { "ART", ">" }, - { "EXM", "!" }, { "QST", "?" }, { "DSH", "-" }, { "CMA", "," }, - { "PRD", "." }, { "APS", "'" }, { "LPR", "(" }, { "RPR", ")" }, - { "CLN", ":" }, { "PIP", "| " } + { "CLF", "(C<)" }, { "CUP", "(C^)" }, { "CRT", "(C>)" }, { "CDN", "(Cv)" }, { "AUP", "^" }, { "ALF", "<" }, + { "ADN", "v" }, { "ART", ">" }, { "EXM", "!" }, { "QST", "?" }, { "DSH", "-" }, { "CMA", "," }, + { "PRD", "." }, { "APS", "'" }, { "LPR", "(" }, { "RPR", ")" }, { "CLN", ":" }, { "PIP", "| " } }; std::vector<std::string> gASCIIFullTable = { - "\0", "\n", "{NP:2}", "{NP:3}", "{NP:4}", "{NP:5}", "{NP:6}", "{NP:7}", - "{PRI:0}", "{PRI:1}", "{PRI:2}", "{PRI:3}", " ", "{HSP}", "{QSP}", "{NXT}", - "{C:<}", "{C:^}", "{C:>}", "{C:v}", "{^}", "{<}", "{v}", "{>}", - "A", "B", "C", "D", "E", "F", "G", "H", - "I", "J", "K", "L", "M", "N", "O", "P", - "Q", "R", "S", "T", "U", "V", "W", "X", - "Y", "Z", "a", "b", "c", "d", "e", "f", - "g", "h", "i", "j", "k", "l", "m", "n", - "o", "p", "q", "r", "s", "t", "u", "v", - "w", "x", "y", "z", "!", "?", "-", ",", - ".", "0", "1", "2", "3", "4", "5", "6", - "7", "8", "9", "'", "(", ")", ":", "|", + "\0", "\n", "{NP:2}", "{NP:3}", "{NP:4}", "{NP:5}", "{NP:6}", "{NP:7}", "{PRI:0}", "{PRI:1}", "{PRI:2}", + "{PRI:3}", " ", "{HSP}", "{QSP}", "{NXT}", "{C:<}", "{C:^}", "{C:>}", "{C:v}", "{^}", "{<}", + "{v}", "{>}", "A", "B", "C", "D", "E", "F", "G", "H", "I", + "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", + "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", + "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", + "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", + "?", "-", ",", ".", "0", "1", "2", "3", "4", "5", "6", + "7", "8", "9", "'", "(", ")", ":", "|", }; -ExportResult SF64::MessageHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::MessageHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -81,7 +71,8 @@ ExportResult SF64::MessageHeaderExporter::Export(std::ostream &write, std::share return std::nullopt; } -ExportResult SF64::MessageCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::MessageCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto message = std::static_pointer_cast<MessageData>(raw)->mMessage; auto mesgStr = std::static_pointer_cast<MessageData>(raw)->mMesgStr; const auto symbol = GetSafeNode(node, "symbol", entryName); @@ -95,7 +86,7 @@ ExportResult SF64::MessageCodeExporter::Export(std::ostream &write, std::shared_ write << gCharCodeEnums[m] << ", "; - if(m == NEWLINE_CODE){ + if (m == NEWLINE_CODE) { write << "\n" << fourSpaceTab; } } @@ -109,7 +100,8 @@ ExportResult SF64::MessageCodeExporter::Export(std::ostream &write, std::shared_ return offset + message.size() * sizeof(uint16_t); } -ExportResult SF64::MessageBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::MessageBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto data = std::static_pointer_cast<MessageData>(raw); @@ -117,14 +109,15 @@ ExportResult SF64::MessageBinaryExporter::Export(std::ostream &write, std::share auto count = data->mMessage.size(); writer.Write(static_cast<uint32_t>(count)); - for(size_t i = 0; i < count; i++) { - writer.Write((uint16_t) data->mMessage[i]); + for (size_t i = 0; i < count; i++) { + writer.Write((uint16_t)data->mMessage[i]); } writer.Finish(write); return std::nullopt; } -ExportResult SF64::MessageModdingExporter::Export(std::ostream&write, std::shared_ptr<IParsedData> raw, std::string&entryName, YAML::Node&node, std::string* replacement) { +ExportResult SF64::MessageModdingExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto data = std::static_pointer_cast<MessageData>(raw); const auto symbol = GetSafeNode(node, "symbol", entryName); *replacement += ".yml"; @@ -136,8 +129,8 @@ ExportResult SF64::MessageModdingExporter::Export(std::ostream&write, std::share out << YAML::Key << symbol; out << YAML::Value << YAML::BeginSeq; - for(size_t i = 0; i < count; i++) { - if(data->mMessage[i] == NEWLINE_CODE){ + for (size_t i = 0; i < count; i++) { + if (data->mMessage[i] == NEWLINE_CODE) { stream << "\0"; out << stream.str(); stream.str(""); @@ -152,7 +145,8 @@ ExportResult SF64::MessageModdingExporter::Export(std::ostream&write, std::share return std::nullopt; } -ExportResult SF64::MessageXMLExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::MessageXMLExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto data = std::static_pointer_cast<MessageData>(raw); const auto symbol = GetSafeNode(node, "symbol", entryName); @@ -162,8 +156,8 @@ ExportResult SF64::MessageXMLExporter::Export(std::ostream &write, std::shared_p tinyxml2::XMLElement* line = message.NewElement("Line"); std::string str; - for(size_t i = 0; i < data->mMessage.size(); i++) { - if(data->mMessage[i] == NEWLINE_CODE){ + for (size_t i = 0; i < data->mMessage.size(); i++) { + if (data->mMessage[i] == NEWLINE_CODE) { line->SetText(str.c_str()); root->InsertEndChild(line); line = message.NewElement("Line"); @@ -179,7 +173,8 @@ ExportResult SF64::MessageXMLExporter::Export(std::ostream &write, std::shared_p return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { std::vector<uint16_t> message; std::ostringstream mesgStr; auto [_, segment] = Decompressor::AutoDecode(node, buffer); @@ -193,10 +188,10 @@ std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse(std::vec message.push_back(c); std::string enumCode = gCharCodeEnums[c]; - if((enumCode.find("SP") != std::string::npos) && whitespace.empty()) { + if ((enumCode.find("SP") != std::string::npos) && whitespace.empty()) { whitespace = " "; } - if(c == NEWLINE_CODE) { + if (c == NEWLINE_CODE) { whitespace += "\n"; } if (c >= CLF_CODE) { @@ -205,24 +200,25 @@ std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse(std::vec } if (StringHelper::StartsWith(enumCode, "_")) { mesgStr << enumCode.substr(1); - } else if (Torch::contains(ASCIITable, enumCode)){ + } else if (Torch::contains(ASCIITable, enumCode)) { mesgStr << ASCIITable[enumCode]; } - } while(c != END_CODE); + } while (c != END_CODE); return std::make_shared<MessageData>(message, mesgStr.str()); } std::optional<uint16_t> getCharByCode(const std::string& code) { auto it = std::find(gASCIIFullTable.begin(), gASCIIFullTable.end(), code) - gASCIIFullTable.begin(); - if(it < gASCIIFullTable.size()){ + if (it < gASCIIFullTable.size()) { return it; } return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse_modding(std::vector<uint8_t>& buffer, YAML::Node& data) { +std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse_modding(std::vector<uint8_t>& buffer, + YAML::Node& data) { std::vector<uint16_t> message; std::ostringstream mesgStr; std::string whitespace = ""; @@ -230,25 +226,25 @@ std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse_modding( YAML::Node node; try { - std::string text((char*) buffer.data(), buffer.size()); + std::string text((char*)buffer.data(), buffer.size()); node = YAML::Load(text.c_str()); } catch (YAML::ParserException& e) { SPDLOG_ERROR("Failed to parse message data: {}", e.what()); - SPDLOG_ERROR("{}", (char*) buffer.data()); + SPDLOG_ERROR("{}", (char*)buffer.data()); return std::nullopt; } std::regex fmt("\\(([^)]+)\\)"); std::vector<std::string> lines = node.begin()->second.as<std::vector<std::string>>(); - for(auto& line : lines){ - for(size_t i = 0; i < line.size(); i++){ + for (auto& line : lines) { + for (size_t i = 0; i < line.size(); i++) { char c = line[i]; std::string enumCode; - if(c == '{' && line.substr(i).find('}') != std::string::npos){ + if (c == '{' && line.substr(i).find('}') != std::string::npos) { auto code = line.substr(i, line.substr(i).find('}') + 1); auto opcode = getCharByCode(code); - if(opcode.has_value()){ + if (opcode.has_value()) { auto x = opcode.value(); message.push_back(x); i += line.substr(i).find('}'); @@ -258,7 +254,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse_modding( } } else { auto code = getCharByCode(std::string(1, c)); - if(code.has_value()){ + if (code.has_value()) { auto x = code.value(); message.push_back(x); enumCode = gCharCodeEnums[x]; @@ -267,11 +263,11 @@ std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse_modding( } } - if(!enumCode.empty()) { - if(enumCode.find("SP") != std::string::npos && whitespace.empty()) { + if (!enumCode.empty()) { + if (enumCode.find("SP") != std::string::npos && whitespace.empty()) { whitespace = " "; } - if(c == NEWLINE_CODE) { + if (c == NEWLINE_CODE) { whitespace += "\n"; } if (c >= CLF_CODE) { @@ -280,13 +276,13 @@ std::optional<std::shared_ptr<IParsedData>> SF64::MessageFactory::parse_modding( } if (StringHelper::StartsWith(enumCode, "_")) { mesgStr << enumCode.substr(1); - } else if (Torch::contains(ASCIITable, enumCode)){ + } else if (Torch::contains(ASCIITable, enumCode)) { mesgStr << ASCIITable[enumCode]; } } } - if(line != lines.back()){ + if (line != lines.back()) { message.push_back(NEWLINE_CODE); mesgStr << "\n"; } diff --git a/src/factories/sf64/MessageLookupFactory.cpp b/src/factories/sf64/MessageLookupFactory.cpp index e214a86..1cc9da4 100644 --- a/src/factories/sf64/MessageLookupFactory.cpp +++ b/src/factories/sf64/MessageLookupFactory.cpp @@ -5,10 +5,12 @@ #include "Companion.h" #include <tinyxml2.h> -ExportResult SF64::MessageLookupHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::MessageLookupHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -17,7 +19,9 @@ ExportResult SF64::MessageLookupHeaderExporter::Export(std::ostream &write, std: return std::nullopt; } -ExportResult SF64::MessageLookupCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::MessageLookupCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto table = std::static_pointer_cast<MessageTable>(raw)->mTable; const auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -26,14 +30,14 @@ ExportResult SF64::MessageLookupCodeExporter::Export(std::ostream &write, std::s write << "MsgLookup " << symbol << "[] = {\n" << fourSpaceTab; for (int i = 0; i < table.size(); ++i) { auto m = table[i]; - if(i % 4 == 0 && i != 0){ + if (i % 4 == 0 && i != 0) { write << "\n" << fourSpaceTab; } auto dec = Companion::Instance->GetNodeByAddr(m.ptr); std::string msgSymbol = "NULL"; - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); msgSymbol = GetSafeNode<std::string>(node, "symbol"); } @@ -45,14 +49,16 @@ ExportResult SF64::MessageLookupCodeExporter::Export(std::ostream &write, std::s return offset + table.size() * sizeof(uint16_t); } -ExportResult SF64::MessageLookupXMLExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::MessageLookupXMLExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto table = std::static_pointer_cast<MessageTable>(raw)->mTable; const auto symbol = GetSafeNode(node, "symbol", entryName); tinyxml2::XMLPrinter printer; tinyxml2::XMLDocument lookup; tinyxml2::XMLElement* root = lookup.NewElement("MessageTable"); - root->SetAttribute("Size", (int) table.size()); + root->SetAttribute("Size", (int)table.size()); *replacement += ".meta"; @@ -61,7 +67,7 @@ ExportResult SF64::MessageLookupXMLExporter::Export(std::ostream &write, std::sh auto dec = Companion::Instance->GetNodeByAddr(m.ptr); std::string ref = "None"; - if(dec.has_value()){ + if (dec.has_value()) { ref = std::get<0>(dec.value()); } @@ -75,7 +81,9 @@ ExportResult SF64::MessageLookupXMLExporter::Export(std::ostream &write, std::sh return std::nullopt; } -ExportResult SF64::MessageLookupBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::MessageLookupBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto data = std::static_pointer_cast<MessageTable>(raw); @@ -84,15 +92,15 @@ ExportResult SF64::MessageLookupBinaryExporter::Export(std::ostream &write, std: const auto count = data->mTable.size(); SPDLOG_INFO("Message Count: {}", count); writer.Write(static_cast<uint32_t>(count)); - for(auto m : data->mTable) { + for (auto m : data->mTable) { writer.Write(m.id); auto dec = Companion::Instance->GetNodeByAddr(m.ptr); - if(dec.has_value()){ + if (dec.has_value()) { std::string path = std::get<0>(dec.value()); SPDLOG_INFO("Message ID: {} Ptr: {:X} Path: {}", m.id, m.ptr, path); writer.Write(CRC64(path.c_str())); } else { - writer.Write((uint64_t) 0); + writer.Write((uint64_t)0); SPDLOG_WARN("Failed to find message ID: {} Ptr: {:X}", m.id, m.ptr); } } @@ -100,7 +108,8 @@ ExportResult SF64::MessageLookupBinaryExporter::Export(std::ostream &write, std: return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SF64::MessageLookupFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SF64::MessageLookupFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { const auto vram = GetSafeNode<uint32_t>(node, "vram"); const auto offset = GetSafeNode<uint32_t>(node, "offset"); std::vector<MessageEntry> message; @@ -112,7 +121,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::MessageLookupFactory::parse(st int32_t id = reader.ReadInt32(); uint32_t ptr = reader.ReadInt32(); - while(id != -1) { + while (id != -1) { YAML::Node entry; @@ -125,12 +134,12 @@ std::optional<std::shared_ptr<IParsedData>> SF64::MessageLookupFactory::parse(st SPDLOG_INFO("Message ID: {} Ptr: {:X} Offset: {:X}", id, ptr, (SEGMENT_NUMBER(offset) << 24) | (ptr - vram)); Companion::Instance->AddAsset(entry); - message.push_back({id, ptr}); + message.push_back({ id, ptr }); id = reader.ReadInt32(); ptr = reader.ReadInt32(); } - message.push_back({-1, 0}); + message.push_back({ -1, 0 }); return std::make_shared<MessageTable>(message); }
\ No newline at end of file diff --git a/src/factories/sf64/ObjInitFactory.cpp b/src/factories/sf64/ObjInitFactory.cpp index 4a2bbfe..e250fa2 100644 --- a/src/factories/sf64/ObjInitFactory.cpp +++ b/src/factories/sf64/ObjInitFactory.cpp @@ -6,10 +6,11 @@ #define NUM(x, w) std::dec << std::setfill(' ') << std::setw(w) << x #define FLOAT(x, w) std::dec << std::setfill(' ') << std::setw(w) << std::fixed << std::setprecision(1) << x << "f" -ExportResult SF64::ObjInitHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::ObjInitHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,15 +19,16 @@ ExportResult SF64::ObjInitHeaderExporter::Export(std::ostream &write, std::share return std::nullopt; } -ExportResult SF64::ObjInitCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::ObjInitCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); auto objs = std::static_pointer_cast<ObjInitData>(raw)->mObjInit; write << "ObjectInit " << symbol << "[] = {\n"; - for(auto& obj : objs) { + for (auto& obj : objs) { auto enumName = Companion::Instance->GetEnumFromValue("ObjectId", obj.id).value_or(std::to_string(obj.id)); - if(obj.id >= 1000) { + if (obj.id >= 1000) { enumName = "ACTOR_EVENT_ID + " + std::to_string(obj.id - 1000); } write << fourSpaceTab << "{ "; @@ -46,14 +48,15 @@ ExportResult SF64::ObjInitCodeExporter::Export(std::ostream &write, std::shared_ return offset + sizeof(ObjectInit) * objs.size(); } -ExportResult SF64::ObjInitBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::ObjInitBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<ObjInitData>(raw)->mObjInit; WriteHeader(writer, Torch::ResourceType::ObjectInit, 0); auto count = data.size(); - writer.Write((uint32_t) count); - for(size_t i = 0; i < data.size(); i++) { + writer.Write((uint32_t)count); + for (size_t i = 0; i < data.size(); i++) { writer.Write(data[i].zPos1); writer.Write(data[i].zPos2); writer.Write(data[i].xPos); @@ -67,7 +70,8 @@ ExportResult SF64::ObjInitBinaryExporter::Export(std::ostream &write, std::share return std::nullopt; } -ExportResult SF64::ObjInitXMLExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::ObjInitXMLExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto data = std::static_pointer_cast<ObjInitData>(raw)->mObjInit; tinyxml2::XMLPrinter printer; @@ -76,7 +80,7 @@ ExportResult SF64::ObjInitXMLExporter::Export(std::ostream &write, std::shared_p *replacement += ".meta"; - for(auto & i : data) { + for (auto& i : data) { tinyxml2::XMLElement* obj = root->InsertNewChildElement("ObjInit"); auto enumName = Companion::Instance->GetEnumFromValue("ObjectId", i.id).value_or(std::to_string(i.id)); @@ -97,7 +101,8 @@ ExportResult SF64::ObjInitXMLExporter::Export(std::ostream &write, std::shared_p return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SF64::ObjInitFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SF64::ObjInitFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, segment.size); @@ -106,7 +111,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::ObjInitFactory::parse(std::vec bool terminator = false; bool processing = true; - while(processing) { + while (processing) { float zPos1 = reader.ReadFloat(); int16_t zPos2 = reader.ReadInt16(); int16_t xPos = reader.ReadInt16(); @@ -117,13 +122,13 @@ std::optional<std::shared_ptr<IParsedData>> SF64::ObjInitFactory::parse(std::vec int16_t id = reader.ReadInt16(); reader.ReadInt16(); - if(id == -1) { + if (id == -1) { terminator = true; } - if(terminator && ((zPos1*zPos2*xPos*yPos*rotX*rotY*rotZ) != 0 || id != -1)) { + if (terminator && ((zPos1 * zPos2 * xPos * yPos * rotX * rotY * rotZ) != 0 || id != -1)) { processing = false; } else { - objects.push_back({ zPos1, zPos2, xPos, yPos, {rotX, rotY, rotZ}, id}); + objects.push_back({ zPos1, zPos2, xPos, yPos, { rotX, rotY, rotZ }, id }); } } diff --git a/src/factories/sf64/ScriptFactory.cpp b/src/factories/sf64/ScriptFactory.cpp index ba88a14..efb33ff 100644 --- a/src/factories/sf64/ScriptFactory.cpp +++ b/src/factories/sf64/ScriptFactory.cpp @@ -12,16 +12,20 @@ #define CLAMP_MAX(val, max) (((val) < (max)) ? (val) : (max)) #define MIN(a, b) (((a) < (b)) ? (a) : (b)) -#define VALUE_TO_ENUM(val, enumname, fallback) (Companion::Instance->GetEnumFromValue(enumname, val).value_or("/*" + std::string(fallback) + " */ " + std::to_string(val))); - -SF64::ScriptData::ScriptData(std::vector<uint32_t> ptrs, std::vector<uint16_t> cmds, std::map<uint32_t, int> sizeMap, uint32_t ptrsStart, uint32_t cmdsStart): mPtrs(ptrs), mCmds(cmds), mSizeMap(sizeMap), mPtrsStart(ptrsStart), mCmdsStart(cmdsStart) { +#define VALUE_TO_ENUM(val, enumname, fallback) \ + (Companion::Instance->GetEnumFromValue(enumname, val) \ + .value_or("/*" + std::string(fallback) + " */ " + std::to_string(val))); +SF64::ScriptData::ScriptData(std::vector<uint32_t> ptrs, std::vector<uint16_t> cmds, std::map<uint32_t, int> sizeMap, + uint32_t ptrsStart, uint32_t cmdsStart) + : mPtrs(ptrs), mCmds(cmds), mSizeMap(sizeMap), mPtrsStart(ptrsStart), mCmdsStart(cmdsStart) { } -ExportResult SF64::ScriptHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::ScriptHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -34,7 +38,7 @@ std::string GetMsg(uint16_t msgId) { std::string msg = ""; auto rawmsg = Companion::Instance->GetParseDataBySymbol("gMsg_ID_" + std::to_string(msgId)); - if(rawmsg.has_value() && rawmsg.value().data.has_value()) { + if (rawmsg.has_value() && rawmsg.value().data.has_value()) { auto msgData = std::static_pointer_cast<SF64::MessageData>(rawmsg.value().data.value()); auto msg = std::regex_replace(msgData->mMesgStr, std::regex(R"(\n)"), " "); } @@ -53,11 +57,12 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { case 1: { auto f3 = arg1 & 0x7F; auto zmode = VALUE_TO_ENUM((arg1 >> 7) & 3, "EventModeZ", "EVOP_UNK"); - - if(opcode == 0 && s2 == 1) { + + if (opcode == 0 && s2 == 1) { cmd << "EVENT_UPDATE_SPEED(" << std::dec << f3 << ", " << zmode; } else { - cmd << "EVENT_SET_" << (opcode ? "ACCEL" : "SPEED") << "(" << std::dec << f3 << ", " << zmode << ", " << s2; + cmd << "EVENT_SET_" << (opcode ? "ACCEL" : "SPEED") << "(" << std::dec << f3 << ", " << zmode << ", " + << s2; waitframes = s2; } } break; @@ -84,15 +89,16 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { case 20: case 21: { auto rotcmd = VALUE_TO_ENUM(opcode, "EventOpcode", "EVOP_UNK"); - if(opcode < 16 && s2 != 0) { + if (opcode < 16 && s2 != 0) { waitframes = std::ceil(10.0f * arg1 / s2); } - if(opcode < 16 && (arg1 == s2 / 10) && arg1 != 0) { + if (opcode < 16 && (arg1 == s2 / 10) && arg1 != 0) { cmd << rotcmd.replace(0, 4, "EVENT_UPDATE") << "(" << std::dec << arg1; waitframes = 0; } else { - cmd << rotcmd.replace(0, 4, "EVENT") << "(" << std::dec << arg1 << ", " << std::fixed << std::setprecision(1) << s2 / 10.0f; - if(arg1 == 0) { + cmd << rotcmd.replace(0, 4, "EVENT") << "(" << std::dec << arg1 << ", " << std::fixed + << std::setprecision(1) << s2 / 10.0f; + if (arg1 == 0) { waitframes = 1; } } @@ -118,7 +124,7 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { cmd << "EVENT_SET_TARGET(" << teamId << ", " << std::dec << s2; } break; case 48: - if(s2 == 1) { + if (s2 == 1) { cmd << "EVENT_UPDATE_ACTOR("; } else { cmd << "EVENT_SET_WAIT(" << std::dec << s2; @@ -131,14 +137,14 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { case 57: { auto teamId = VALUE_TO_ENUM(s2, "TeamId", "TEAMID_UNK"); cmd << "EVENT_RESTORE_TEAM(" << teamId; - } break; + } break; case 58: case 59: { auto sfxIndex = VALUE_TO_ENUM(s2, "EventSfx", "EVSFX_UNK"); cmd << "EVENT_" << ((opcode == 58) ? "PLAY" : "STOP") << "_SFX(" << sfxIndex; } break; case 96: - if(s2 == 0) { + if (s2 == 0) { cmd << "EVENT_CLEAR_TRIGGER(" << std::dec << arg1; } else { if (s2 >= 100) { @@ -158,10 +164,10 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { auto teamId = VALUE_TO_ENUM(s2, "TeamId", "TEAMID_UNK"); cmd << "EVENT_SET_TEAM_ID(" << teamId; } break; - case 112:{ + case 112: { auto actiontype = VALUE_TO_ENUM(s2, "EventAction", "EVACT_UNK"); cmd << "EVENT_SET_ACTION(" << actiontype; - if((s2 == 14 || s2 == 15)) { + if ((s2 == 14 || s2 == 15)) { waitframes = 1; } } break; @@ -183,7 +189,7 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { auto rcidName = VALUE_TO_ENUM(arg1, "RadioCharacterId", "RCID_UNK"); cmd << "EVENT_PLAY_MSG(" << rcidName << ", " << std::dec << s2; auto msg = GetMsg(s2); - if(!msg.empty()) { + if (!msg.empty()) { comment << " // " << msg; } } break; @@ -203,7 +209,7 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { break; case 126: cmd << ((s2 == 0) ? "EVENT_GOTO(" : "EVENT_LOOP("); - if(s2 != 0) { + if (s2 != 0) { cmd << std::dec << s2 << ", "; } cmd << ((arg1 < 200) ? "" : "EV_CHANGE_SCRIPT + ") << std::dec << ((arg1 < 200) ? arg1 : arg1 - 200); @@ -214,13 +220,13 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { default: { auto opcodeName = VALUE_TO_ENUM(opcode, "EventOpcode", "EVOP_UNK"); cmd << "EVENT_CMD(" << opcodeName << ", " << std::dec << arg1 << ", " << s2; - if(opcode >= 40 && opcode <= 48) { + if (opcode >= 40 && opcode <= 48) { waitframes = s2; } } break; } cmd << ")," << comment.str(); - if(waitframes > 1) { + if (waitframes > 1) { cmd << "\n // wait " << waitframes << " frames"; } else if (waitframes == 1) { cmd << "\n // update actor"; @@ -228,7 +234,8 @@ std::string MakeScriptCmd(uint16_t s1, uint16_t s2) { return cmd.str(); } -ExportResult SF64::ScriptCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::ScriptCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); auto script = std::static_pointer_cast<SF64::ScriptData>(raw); @@ -238,11 +245,12 @@ ExportResult SF64::ScriptCodeExporter::Export(std::ostream &write, std::shared_p auto cmdIndex = 0; std::map<uint32_t, std::string> scriptNames; - for(int i = 0; i < sortedPtrs.size(); i++) { + for (int i = 0; i < sortedPtrs.size(); i++) { std::ostringstream scriptDefaultName; auto scriptIndex = std::find(script->mPtrs.begin(), script->mPtrs.end(), sortedPtrs[i]) - script->mPtrs.begin(); - scriptDefaultName << symbol << "_script_" << std::dec << scriptIndex << "_" << std::uppercase << std::hex << cmdOff; + scriptDefaultName << symbol << "_script_" << std::dec << scriptIndex << "_" << std::uppercase << std::hex + << cmdOff; auto scriptName = GetSafeNode(node, "script_symbol", scriptDefaultName.str()); scriptNames[sortedPtrs[i]] = scriptName; if (Companion::Instance->IsDebug()) { @@ -251,9 +259,9 @@ ExportResult SF64::ScriptCodeExporter::Export(std::ostream &write, std::shared_p write << "u16 " << scriptName << "[] = {"; auto cmdCount = script->mSizeMap[sortedPtrs[i]] / 2; - for(int j = 0; j < cmdCount; j++, cmdIndex+=2) { + for (int j = 0; j < cmdCount; j++, cmdIndex += 2) { // if((j % 3) == 0) { - write << "\n" << fourSpaceTab << "/* " << std::setfill(' ') << std::setw(2) << std::dec << j << " */ "; + write << "\n" << fourSpaceTab << "/* " << std::setfill(' ') << std::setw(2) << std::dec << j << " */ "; // } write << MakeScriptCmd(script->mCmds[cmdIndex], script->mCmds[cmdIndex + 1]); } @@ -270,8 +278,8 @@ ExportResult SF64::ScriptCodeExporter::Export(std::ostream &write, std::shared_p write << "// 0x" << std::hex << std::uppercase << ASSET_PTR(offset) << "\n"; write << "u16* " << symbol << "[] = {"; - for(int i = 0; i < script->mPtrs.size(); i++) { - if((i % 4) == 0) { + for (int i = 0; i < script->mPtrs.size(); i++) { + if ((i % 4) == 0) { write << "\n" << fourSpaceTab; } write << scriptNames[script->mPtrs[i]] << ", "; @@ -282,13 +290,11 @@ ExportResult SF64::ScriptCodeExporter::Export(std::ostream &write, std::shared_p write << "// count: " << std::dec << script->mPtrs.size() << " events\n"; } - return OffsetEntry { - script->mCmdsStart, - static_cast<uint32_t>(offset + script->mPtrs.size() * sizeof(uint32_t)) - }; + return OffsetEntry{ script->mCmdsStart, static_cast<uint32_t>(offset + script->mPtrs.size() * sizeof(uint32_t)) }; } -ExportResult SF64::ScriptBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::ScriptBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto scriptWriter = LUS::BinaryWriter(); auto script = std::static_pointer_cast<SF64::ScriptData>(raw); @@ -307,7 +313,7 @@ ExportResult SF64::ScriptBinaryExporter::Export(std::ostream &write, std::shared WriteHeader(cmdWriter, Torch::ResourceType::ScriptCmd, 0); auto cmdCount = script->mSizeMap.at(ptr) / 2; - cmdWriter.Write((uint32_t) cmdCount); + cmdWriter.Write((uint32_t)cmdCount); // Writing in pairs for readability for (uint32_t i = 0; i < cmdCount; ++i) { @@ -329,7 +335,7 @@ ExportResult SF64::ScriptBinaryExporter::Export(std::ostream &write, std::shared // Export Script WriteHeader(scriptWriter, Torch::ResourceType::Script, 0); auto count = script->mPtrs.size(); - scriptWriter.Write((uint32_t) count); + scriptWriter.Write((uint32_t)count); for (size_t i = 0; i < script->mPtrs.size(); i++) { scriptWriter.Write(ptrMap.at(script->mPtrs.at(i))); } @@ -374,7 +380,8 @@ std::string MakeXMLScriptCmd(uint16_t s1, uint16_t s2) { case 20: case 21: { auto rotcmd = VALUE_TO_ENUM(opcode, "EventOpcode", "EVOP_UNK"); - cmd << rotcmd.replace(0, 4, "EVENT") << "(" << std::dec << s2 << ", " << std::fixed << std::setprecision(1) << arg1 / 10.0f; + cmd << rotcmd.replace(0, 4, "EVENT") << "(" << std::dec << s2 << ", " << std::fixed << std::setprecision(1) + << arg1 / 10.0f; } break; case 24: cmd << "SET_ROTATE("; @@ -405,14 +412,14 @@ std::string MakeXMLScriptCmd(uint16_t s1, uint16_t s2) { case 57: { auto teamId = VALUE_TO_ENUM(s2, "TeamId", "TEAMID_UNK"); cmd << "RESTORE_TEAM(" << teamId; - } break; + } break; case 58: case 59: { auto sfxIndex = VALUE_TO_ENUM(s2, "EventSfx", "EVSFX_UNK"); cmd << "" << ((opcode == 58) ? "PLAY" : "STOP") << "_SFX(" << sfxIndex; } break; case 96: - if(s2 == 0) { + if (s2 == 0) { cmd << "CLEAR_TRIGGER(" << std::dec << arg1; } else { if (s2 >= 100) { @@ -432,7 +439,7 @@ std::string MakeXMLScriptCmd(uint16_t s1, uint16_t s2) { auto teamId = VALUE_TO_ENUM(s2, "TeamId", "TEAMID_UNK"); cmd << "SET_TEAM_ID(" << teamId; } break; - case 112:{ + case 112: { auto actiontype = VALUE_TO_ENUM(s2, "EventAction", "EVACT_UNK"); cmd << "SET_ACTION(" << actiontype; } break; @@ -470,7 +477,7 @@ std::string MakeXMLScriptCmd(uint16_t s1, uint16_t s2) { break; case 126: cmd << ((s2 == 0) ? "GOTO(" : "LOOP("); - if(s2 != 0) { + if (s2 != 0) { cmd << std::dec << s2 << ", "; } cmd << ((arg1 < 200) ? "" : "AI_CHANGE + ") << std::dec << ((arg1 < 200) ? arg1 : arg1 - 200); @@ -487,7 +494,8 @@ std::string MakeXMLScriptCmd(uint16_t s1, uint16_t s2) { return cmd.str(); } -ExportResult SF64::ScriptXMLExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::ScriptXMLExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto script = std::static_pointer_cast<SF64::ScriptData>(raw); auto sortedPtrs = script->mPtrs; @@ -503,18 +511,19 @@ ExportResult SF64::ScriptXMLExporter::Export(std::ostream &write, std::shared_pt tinyxml2::XMLElement* event = root.NewElement("EventScript"); tinyxml2::XMLElement* routine = event->InsertNewChildElement("Routine"); - for(unsigned int sortedPtr : sortedPtrs) { + for (unsigned int sortedPtr : sortedPtrs) { tinyxml2::XMLElement* src = routine->InsertNewChildElement("Script"); std::ostringstream scriptDefaultName; auto scriptIndex = std::find(script->mPtrs.begin(), script->mPtrs.end(), sortedPtr) - script->mPtrs.begin(); - scriptDefaultName << symbol << "_script_" << std::dec << scriptIndex << "_" << std::uppercase << std::hex << cmdOff; + scriptDefaultName << symbol << "_script_" << std::dec << scriptIndex << "_" << std::uppercase << std::hex + << cmdOff; auto scriptName = GetSafeNode(node, "script_symbol", scriptDefaultName.str()); scriptNames[sortedPtr] = scriptName; src->SetAttribute("ID", scriptName.c_str()); auto cmdCount = script->mSizeMap[sortedPtr] / 2; - - for(int j = 0; j < cmdCount; j++, cmdIndex+=2) { + + for (int j = 0; j < cmdCount; j++, cmdIndex += 2) { tinyxml2::XMLElement* obj = src->InsertNewChildElement("Run"); obj->SetText(MakeXMLScriptCmd(script->mCmds[cmdIndex], script->mCmds[cmdIndex + 1]).c_str()); src->InsertEndChild(obj); @@ -524,7 +533,7 @@ ExportResult SF64::ScriptXMLExporter::Export(std::ostream &write, std::shared_pt tinyxml2::XMLElement* program = event->InsertNewChildElement("Program"); - for(unsigned int mPtr : script->mPtrs) { + for (unsigned int mPtr : script->mPtrs) { tinyxml2::XMLElement* obj = program->InsertNewChildElement("Run"); obj->SetAttribute("Script", scriptNames[mPtr].c_str()); program->InsertEndChild(obj); @@ -548,7 +557,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::ScriptFactory::parse(std::vect reader.SetEndianness(Torch::Endianness::Big); auto ptr = reader.ReadUInt32(); - while(SEGMENT_NUMBER(ptr) == SEGMENT_NUMBER(offset)) { + while (SEGMENT_NUMBER(ptr) == SEGMENT_NUMBER(offset)) { scriptPtrs.push_back(ptr); ptr = reader.ReadUInt32(); } @@ -558,8 +567,8 @@ std::optional<std::shared_ptr<IParsedData>> SF64::ScriptFactory::parse(std::vect auto cmdsStart = sortedPtrs[0]; - for(int i = 0; i < sortedPtrs.size() - 1; i++) { - sizeMap[sortedPtrs[i]] = (sortedPtrs[i+1] - sortedPtrs[i]) / sizeof(uint16_t); + for (int i = 0; i < sortedPtrs.size() - 1; i++) { + sizeMap[sortedPtrs[i]] = (sortedPtrs[i + 1] - sortedPtrs[i]) / sizeof(uint16_t); } sizeMap[sortedPtrs[sortedPtrs.size() - 1]] = (ptrsStart - sortedPtrs[sortedPtrs.size() - 1]) / sizeof(uint16_t); @@ -569,7 +578,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::ScriptFactory::parse(std::vect auto [__, scriptSegment] = Decompressor::AutoDecode(scriptNode, buffer, scriptLen * sizeof(uint16_t)); LUS::BinaryReader scriptReader(scriptSegment.data, scriptSegment.size); scriptReader.SetEndianness(Torch::Endianness::Big); - for(int i = 0; i < scriptLen; i++) { + for (int i = 0; i < scriptLen; i++) { scriptCmds.push_back(scriptReader.ReadUInt16()); } return std::make_shared<SF64::ScriptData>(scriptPtrs, scriptCmds, sizeMap, ptrsStart, cmdsStart); diff --git a/src/factories/sf64/SkeletonFactory.cpp b/src/factories/sf64/SkeletonFactory.cpp index 469222c..4abc9fc 100644 --- a/src/factories/sf64/SkeletonFactory.cpp +++ b/src/factories/sf64/SkeletonFactory.cpp @@ -11,16 +11,18 @@ // #define NUM_JOINT(x) std::dec << std::setfill(' ') << std::setw(5) << x #define FLOAT(x, w, p) std::dec << std::setfill(' ') << std::setw(w) << std::fixed << std::setprecision(p) << x -SF64::LimbData::LimbData(uint32_t addr, uint32_t dList, Vec3f trans, Vec3s rot, uint32_t sibling, uint32_t child, int index): mAddr(addr), mDList(dList), mTrans(trans), mRot(rot), mSibling(sibling), mChild(child), mIndex(index) { - +SF64::LimbData::LimbData(uint32_t addr, uint32_t dList, Vec3f trans, Vec3s rot, uint32_t sibling, uint32_t child, + int index) + : mAddr(addr), mDList(dList), mTrans(trans), mRot(rot), mSibling(sibling), mChild(child), mIndex(index) { } -ExportResult SF64::SkeletonHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::SkeletonHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto skeleton = std::static_pointer_cast<SF64::SkeletonData>(raw); auto limbCount = skeleton->mSkeleton.size(); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -29,30 +31,32 @@ ExportResult SF64::SkeletonHeaderExporter::Export(std::ostream &write, std::shar return std::nullopt; } -ExportResult SF64::SkeletonCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::SkeletonCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto skeleton = std::static_pointer_cast<SF64::SkeletonData>(raw); auto limbs = skeleton->mSkeleton; - std::sort(limbs.begin(), limbs.end(), [](SF64::LimbData a, SF64::LimbData b) {return a.mAddr < b.mAddr;}); + std::sort(limbs.begin(), limbs.end(), [](SF64::LimbData a, SF64::LimbData b) { return a.mAddr < b.mAddr; }); std::unordered_map<uint32_t, std::string> limbDict; limbDict[0] = "NULL"; - for(SF64::LimbData limb : limbs) { + for (SF64::LimbData limb : limbs) { std::ostringstream limbDefaultName; auto limbOffset = ASSET_PTR(limb.mAddr); - limbDefaultName << symbol << "_limb_" << std::dec << limb.mIndex << "_" << std::uppercase << std::hex << limbOffset; + limbDefaultName << symbol << "_limb_" << std::dec << limb.mIndex << "_" << std::uppercase << std::hex + << limbOffset; limbDict[limb.mAddr] = limbDefaultName.str(); } - for(SF64::LimbData limb : limbs) { + for (SF64::LimbData limb : limbs) { write << "Limb " << limbDict[limb.mAddr] << " = {\n"; write << fourSpaceTab; - if(limb.mDList == 0) { + if (limb.mDList == 0) { write << "NULL, "; } else { auto dec = Companion::Instance->GetNodeByAddr(limb.mDList); - if(dec.has_value()){ + if (dec.has_value()) { auto node = std::get<1>(dec.value()); auto symbol = GetSafeNode<std::string>(node, "symbol"); write << symbol << ", "; @@ -68,7 +72,7 @@ ExportResult SF64::SkeletonCodeExporter::Export(std::ostream &write, std::shared } write << "Limb* " << symbol << "[] = {"; - for(int i = 0; i <= skeleton->mSkeleton.size(); i++) { + for (int i = 0; i <= skeleton->mSkeleton.size(); i++) { if ((i % 4) == 0) { write << "\n" << fourSpaceTab; } @@ -84,13 +88,11 @@ ExportResult SF64::SkeletonCodeExporter::Export(std::ostream &write, std::shared write << "// Limbs: " << std::dec << skeleton->mSkeleton.size() << "\n"; } - return OffsetEntry { - limbs[0].mAddr, - static_cast<uint32_t>(limbs[0].mAddr + skeleton->mSkeleton.size() * 0x24 + 4) - }; + return OffsetEntry{ limbs[0].mAddr, static_cast<uint32_t>(limbs[0].mAddr + skeleton->mSkeleton.size() * 0x24 + 4) }; } -ExportResult SF64::SkeletonBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::SkeletonBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto skeletonWriter = LUS::BinaryWriter(); auto skeleton = std::static_pointer_cast<SF64::SkeletonData>(raw); @@ -98,23 +100,23 @@ ExportResult SF64::SkeletonBinaryExporter::Export(std::ostream &write, std::shar std::unordered_map<uint32_t, uint64_t> limbDict; // Populate map of limbs with hashes - for (auto &limb : limbs) { + for (auto& limb : limbs) { std::ostringstream limbDefaultName; limbDefaultName << entryName << "_limb_" << std::dec << limb.mIndex; limbDict[limb.mAddr] = CRC64(limbDefaultName.str().c_str()); } // Export Each Limb - for (auto &limb : limbs) { + for (auto& limb : limbs) { auto wrapper = Companion::Instance->GetCurrentWrapper(); std::ostringstream stream; auto limbWriter = LUS::BinaryWriter(); WriteHeader(limbWriter, Torch::ResourceType::Limb, 0); - if(limb.mDList != 0){ + if (limb.mDList != 0) { auto dec = Companion::Instance->GetNodeByAddr(limb.mDList); - if (dec.has_value()){ + if (dec.has_value()) { std::string path = std::get<0>(dec.value()); limbWriter.Write(CRC64(path.c_str())); SPDLOG_INFO("Found display list: 0x{:X} at {} with size {}", limb.mDList, path, path.size()); @@ -123,7 +125,7 @@ ExportResult SF64::SkeletonBinaryExporter::Export(std::ostream &write, std::shar throw std::runtime_error("Could not find dlist at 0x" + std::to_string(limb.mDList)); } } else { - limbWriter.Write((uint64_t) 0); + limbWriter.Write((uint64_t)0); } auto [transX, transY, transZ] = limb.mTrans; limbWriter.Write(transX); @@ -145,8 +147,8 @@ ExportResult SF64::SkeletonBinaryExporter::Export(std::ostream &write, std::shar // Export Skeleton WriteHeader(skeletonWriter, Torch::ResourceType::Skeleton, 0); - skeletonWriter.Write((uint32_t) limbs.size()); - for (auto &limb : limbs) { + skeletonWriter.Write((uint32_t)limbs.size()); + for (auto& limb : limbs) { skeletonWriter.Write(limbDict.at(limb.mAddr)); } @@ -154,7 +156,8 @@ ExportResult SF64::SkeletonBinaryExporter::Export(std::ostream &write, std::shar return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SF64::SkeletonFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SF64::SkeletonFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { std::vector<SF64::LimbData> skeleton; auto [root, segment] = Decompressor::AutoDecode(node, buffer, 0x1000); LUS::BinaryReader reader(segment.data, segment.size); @@ -162,7 +165,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::SkeletonFactory::parse(std::ve auto limbAddr = reader.ReadUInt32(); auto limbIndex = 0; - while(limbAddr != 0) { + while (limbAddr != 0) { YAML::Node limbNode; Vec3f trans; Vec3s rot; @@ -182,7 +185,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::SkeletonFactory::parse(std::ve auto siblingAddr = limbReader.ReadUInt32(); auto childAddr = limbReader.ReadUInt32(); - if(dListAddr != 0 && (SEGMENT_NUMBER(dListAddr) == SEGMENT_NUMBER(limbAddr))) { + if (dListAddr != 0 && (SEGMENT_NUMBER(dListAddr) == SEGMENT_NUMBER(limbAddr))) { YAML::Node dListNode; dListNode["type"] = "GFX"; dListNode["offset"] = dListAddr; diff --git a/src/factories/sf64/TriangleFactory.cpp b/src/factories/sf64/TriangleFactory.cpp index c64d77a..c8e8cd8 100644 --- a/src/factories/sf64/TriangleFactory.cpp +++ b/src/factories/sf64/TriangleFactory.cpp @@ -6,18 +6,19 @@ #include "utils/TorchUtils.h" #include <regex> - #define NUM(x, w) std::dec << std::setfill(' ') << std::setw(w) << x #define FORMAT_FLOAT(x, w, p) std::dec << std::setfill(' ') << std::fixed << std::setprecision(p) << std::setw(w) << x -SF64::TriangleData::TriangleData(std::vector<Vec3s> tris, std::vector<YAML::Node> meshNodes): mTris(tris), mMeshNodes(meshNodes) { +SF64::TriangleData::TriangleData(std::vector<Vec3s> tris, std::vector<YAML::Node> meshNodes) + : mTris(tris), mMeshNodes(meshNodes) { } -ExportResult SF64::TriangleHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SF64::TriangleHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); auto triData = std::static_pointer_cast<SF64::TriangleData>(raw); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -26,7 +27,8 @@ ExportResult SF64::TriangleHeaderExporter::Export(std::ostream &write, std::shar return std::nullopt; } -ExportResult SF64::TriangleCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::TriangleCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); auto triData = std::static_pointer_cast<SF64::TriangleData>(raw); @@ -36,8 +38,8 @@ ExportResult SF64::TriangleCodeExporter::Export(std::ostream &write, std::shared int i = 0; write << "Triangle " << symbol << "[] = {"; - for(Vec3s tri : triData->mTris) { - if((i++ % 6) == 0) { + for (Vec3s tri : triData->mTris) { + if ((i++ % 6) == 0) { write << "\n" << fourSpaceTab; } write << NUM(tri, width) << ", "; @@ -52,14 +54,15 @@ ExportResult SF64::TriangleCodeExporter::Export(std::ostream &write, std::shared return offset + triData->mTris.size() * sizeof(Vec3s); } -ExportResult SF64::TriangleBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SF64::TriangleBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto triData = std::static_pointer_cast<TriangleData>(raw); WriteHeader(writer, Torch::ResourceType::Vec3s, 0); - writer.Write((uint32_t) triData->mTris.size()); + writer.Write((uint32_t)triData->mTris.size()); - for(Vec3s tri : triData->mTris) { + for (Vec3s tri : triData->mTris) { auto [x, y, z] = tri; writer.Write(x); writer.Write(y); @@ -70,7 +73,8 @@ ExportResult SF64::TriangleBinaryExporter::Export(std::ostream &write, std::shar return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SF64::TriangleFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SF64::TriangleFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto count = GetSafeNode<uint32_t>(node, "count"); const auto meshCount = GetSafeNode<uint32_t>(node, "mesh_count", 1); @@ -81,7 +85,7 @@ std::optional<std::shared_ptr<IParsedData>> SF64::TriangleFactory::parse(std::ve LUS::BinaryReader reader(segment.data, segment.size); reader.SetEndianness(Torch::Endianness::Big); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { Vec3s tri; tri.x = reader.ReadInt16(); @@ -95,13 +99,13 @@ std::optional<std::shared_ptr<IParsedData>> SF64::TriangleFactory::parse(std::ve } meshSize++; auto meshOffset = GetSafeNode<uint32_t>(node, "mesh_offset", offset + count * sizeof(Vec3s)); - for(int j = 0; j < meshCount; j++) { + for (int j = 0; j < meshCount; j++) { YAML::Node meshNode; - if(node["mesh_symbol"]) { + if (node["mesh_symbol"]) { auto meshSymbol = GetSafeNode<std::string>(node, "mesh_symbol"); if (meshSymbol.find("OFFSET") == std::string::npos) { - if(meshCount > 1) { + if (meshCount > 1) { meshSymbol += "_" + std::to_string(j); } } else { diff --git a/src/factories/sf64/audio/AudioDecompressor.cpp b/src/factories/sf64/audio/AudioDecompressor.cpp index b7df02e..9151490 100644 --- a/src/factories/sf64/audio/AudioDecompressor.cpp +++ b/src/factories/sf64/audio/AudioDecompressor.cpp @@ -213,7 +213,7 @@ void AudioSynth_HartleyTransform(float* arg0, int32_t arg1, float* arg2) { arg0[2] = temp_fv1 - temp_fa0; break; default: - if (length != (int32_t) *arg2) { + if (length != (int32_t)*arg2) { *arg2 = length; var_s0 = &arg2[1]; @@ -372,11 +372,11 @@ void AudioSynth_InverseDiscreteCosineTransform(float* buffer0, float* buffer1, i half = size >> 1; // Initialize buffer 2 if it is the wrong size for this calculation - if (size != (int32_t) buffer2[0]) { + if (size != (int32_t)buffer2[0]) { buf2half2 = &buffer2[half]; buf2half3 = &buf2half2[half]; var_fs0 = 0.0f; - temp_ft0 = C_M_PI / (float) (2 * size); + temp_ft0 = C_M_PI / (float)(2 * size); for (i = 0; i < half; i++) { *buf2half2++ = (cosf(var_fs0) - sinf(var_fs0)) * 0.707107f; *buf2half3++ = (cosf(var_fs0) + sinf(var_fs0)) * 0.707107f; @@ -457,7 +457,7 @@ void func_80009504(int16_t* arg0, StupidDMAStruct* arg1) { } for (i = 0; i < 0x100; i++, arg0++) { - *arg0 = (int16_t) DFT_80145D48[i]; + *arg0 = (int16_t)DFT_80145D48[i]; } } @@ -489,14 +489,14 @@ int32_t func_8000967C(int32_t length, int16_t* inputAddr, int16_t* ramAddr, Stup void SF64::DecompressAudio(std::vector<uint8_t> data, int16_t* output) { StupidDMAStruct arg3 = {}; - arg3.unk_0 = (int16_t*) data.data(); + arg3.unk_0 = (int16_t*)data.data(); arg3.unk_4 = 0; arg3.unk_8 = 0; arg3.unk18 = 0; - for(int i = 0; i < data.size() / 2; i++){ + for (int i = 0; i < data.size() / 2; i++) { arg3.unk_0[i] = BSWAP16(arg3.unk_0[i]); } - func_8000967C((int32_t) data.size(), arg3.unk_0, (int16_t*) output, &arg3); + func_8000967C((int32_t)data.size(), arg3.unk_0, (int16_t*)output, &arg3); }
\ No newline at end of file diff --git a/src/factories/sm64/AnimationFactory.cpp b/src/factories/sm64/AnimationFactory.cpp index 4b6b5e4..cde52dd 100644 --- a/src/factories/sm64/AnimationFactory.cpp +++ b/src/factories/sm64/AnimationFactory.cpp @@ -5,7 +5,8 @@ #define ANIMINDEX_COUNT(boneCount) (((boneCount) + 1) * 6) -ExportResult SM64::AnimationBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::AnimationBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto anim = std::static_pointer_cast<AnimationData>(raw); @@ -32,7 +33,8 @@ ExportResult SM64::AnimationBinaryExporter::Export(std::ostream &write, std::sha return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::AnimationFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::AnimationFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto offset = node["offset"]; auto [raw, data] = Decompressor::AutoDecode(node, buffer); @@ -54,7 +56,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::AnimationFactory::parse(std::v const auto indexLength = ANIMINDEX_COUNT(unusedBoneCount); const auto valuesSize = !segmented ? length * sizeof(int16_t) : indexAddr - valuesAddr; - if(segmented) { + if (segmented) { valuesAddr = SEGMENT_OFFSET(valuesAddr); indexAddr = SEGMENT_OFFSET(indexAddr); } @@ -86,5 +88,6 @@ std::optional<std::shared_ptr<IParsedData>> SM64::AnimationFactory::parse(std::v valuesData.push_back(values.ReadInt16()); } - return std::make_shared<AnimationData>(flags, animYTransDivisor, startFrame, loopStart, loopEnd, unusedBoneCount, length, indicesData, valuesData); + return std::make_shared<AnimationData>(flags, animYTransDivisor, startFrame, loopStart, loopEnd, unusedBoneCount, + length, indicesData, valuesData); }
\ No newline at end of file diff --git a/src/factories/sm64/BehaviorScriptFactory.cpp b/src/factories/sm64/BehaviorScriptFactory.cpp index 1033676..a8bb239 100644 --- a/src/factories/sm64/BehaviorScriptFactory.cpp +++ b/src/factories/sm64/BehaviorScriptFactory.cpp @@ -6,10 +6,12 @@ #include "utils/TorchUtils.h" #include <regex> -ExportResult SM64::BehaviorScriptHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::BehaviorScriptHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,7 +20,9 @@ ExportResult SM64::BehaviorScriptHeaderExporter::Export(std::ostream &write, std return std::nullopt; } -ExportResult SM64::BehaviorScriptCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::BehaviorScriptCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto commands = std::static_pointer_cast<BehaviorScriptData>(raw)->mCommands; @@ -26,10 +30,11 @@ ExportResult SM64::BehaviorScriptCodeExporter::Export(std::ostream &write, std:: write << "static const BehaviorScript " << symbol << "[] = {\n"; - for(auto& [opcode, arguments] : commands) { + for (auto& [opcode, arguments] : commands) { bool commaFlag = false; - if (opcode == BehaviorOpcode::END_LOOP || opcode == BehaviorOpcode::END_REPEAT || opcode == BehaviorOpcode::END_REPEAT_CONTINUE) { + if (opcode == BehaviorOpcode::END_LOOP || opcode == BehaviorOpcode::END_REPEAT || + opcode == BehaviorOpcode::END_REPEAT_CONTINUE) { --indentCount; } @@ -42,14 +47,14 @@ ExportResult SM64::BehaviorScriptCodeExporter::Export(std::ostream &write, std:: } write << opcode << "("; - for(auto& args : arguments) { + for (auto& args : arguments) { if (commaFlag) { write << ", "; } else { commaFlag = true; } - switch(static_cast<BehaviorArgumentType>(args.index())) { + switch (static_cast<BehaviorArgumentType>(args.index())) { case BehaviorArgumentType::U8: { write << std::hex << "0x" << static_cast<uint32_t>(std::get<uint8_t>(args)); break; @@ -110,7 +115,9 @@ ExportResult SM64::BehaviorScriptCodeExporter::Export(std::ostream &write, std:: return offset + size; } -ExportResult SM64::BehaviorScriptBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::BehaviorScriptBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto commands = std::static_pointer_cast<BehaviorScriptData>(raw)->mCommands; @@ -118,11 +125,11 @@ ExportResult SM64::BehaviorScriptBinaryExporter::Export(std::ostream &write, std writer.Write((uint32_t)commands.size()); - for(auto& [opcode, arguments] : commands) { + for (auto& [opcode, arguments] : commands) { writer.Write(static_cast<uint8_t>(opcode)); - for(auto& args : arguments) { - switch(static_cast<BehaviorArgumentType>(args.index())) { + for (auto& args : arguments) { + switch (static_cast<BehaviorArgumentType>(args.index())) { case BehaviorArgumentType::U8: { writer.Write(std::get<uint8_t>(args)); break; @@ -176,13 +183,14 @@ ExportResult SM64::BehaviorScriptBinaryExporter::Export(std::ostream &write, std return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::BehaviorScriptFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::BehaviorScriptFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); auto cmd = segment.data; bool processing = true; std::vector<BehaviorCommand> commands; - while(processing) { + while (processing) { auto opcode = static_cast<BehaviorOpcode>(cmd[0x00]); SPDLOG_INFO("Processing Command {}", opcode); diff --git a/src/factories/sm64/CollisionFactory.cpp b/src/factories/sm64/CollisionFactory.cpp index 8ccc3ff..6271af6 100644 --- a/src/factories/sm64/CollisionFactory.cpp +++ b/src/factories/sm64/CollisionFactory.cpp @@ -90,7 +90,8 @@ std::unordered_map<int16_t, SpecialPresetTypes> specialPresetMap = { { 0xFF, SpecialPresetTypes::SPTYPE_NO_YROT_OR_PARAMS }, }; -ExportResult SM64::CollisionCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> data, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::CollisionCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto symbol = GetSafeNode(node, "symbol", entryName); auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto collision = std::static_pointer_cast<Collision>(data).get(); @@ -109,7 +110,7 @@ ExportResult SM64::CollisionCodeExporter::Export(std::ostream &write, std::share write << "COL_VERTEX_INIT(" << FORMAT_HEX(collision->mVertices.size()) << "),\n"; ++count; } - for (auto &vertex : collision->mVertices) { + for (auto& vertex : collision->mVertices) { write << fourSpaceTab; write << "COL_VERTEX("; write << vertex.x << ", "; @@ -119,7 +120,7 @@ ExportResult SM64::CollisionCodeExporter::Export(std::ostream &write, std::share } // Surfaces - for (auto &surface : collision->mSurfaces) { + for (auto& surface : collision->mSurfaces) { // size check is probably not necessary here if (surface.tris.size() > 0) { write << fourSpaceTab; @@ -130,19 +131,19 @@ ExportResult SM64::CollisionCodeExporter::Export(std::ostream &write, std::share } bool hasForce = false; switch (surface.surfaceType) { - case SurfaceType::SURFACE_0004: - case SurfaceType::SURFACE_FLOWING_WATER: - case SurfaceType::SURFACE_DEEP_MOVING_QUICKSAND: - case SurfaceType::SURFACE_SHALLOW_MOVING_QUICKSAND: - case SurfaceType::SURFACE_MOVING_QUICKSAND: - case SurfaceType::SURFACE_HORIZONTAL_WIND: - case SurfaceType::SURFACE_INSTANT_MOVING_QUICKSAND: - hasForce = true; - break; - default: - break; - } - for (auto &tri : surface.tris) { + case SurfaceType::SURFACE_0004: + case SurfaceType::SURFACE_FLOWING_WATER: + case SurfaceType::SURFACE_DEEP_MOVING_QUICKSAND: + case SurfaceType::SURFACE_SHALLOW_MOVING_QUICKSAND: + case SurfaceType::SURFACE_MOVING_QUICKSAND: + case SurfaceType::SURFACE_HORIZONTAL_WIND: + case SurfaceType::SURFACE_INSTANT_MOVING_QUICKSAND: + hasForce = true; + break; + default: + break; + } + for (auto& tri : surface.tris) { write << fourSpaceTab; if (hasForce) { write << "COL_TRI_SPECIAL("; @@ -174,7 +175,7 @@ ExportResult SM64::CollisionCodeExporter::Export(std::ostream &write, std::share write << "COL_SPECIAL_INIT(" << collision->mSpecialObjects.size() << "),\n"; count += 2; } - for (auto &specialObject : collision->mSpecialObjects) { + for (auto& specialObject : collision->mSpecialObjects) { write << fourSpaceTab; if (specialPresetMap.find((int16_t)specialObject.presetId) == specialPresetMap.end()) { throw std::runtime_error("Special Preset Id has no associated Type"); @@ -218,7 +219,7 @@ ExportResult SM64::CollisionCodeExporter::Export(std::ostream &write, std::share write << "COL_WATER_BOX_INIT(" << collision->mEnvRegionBoxes.size() << "),\n"; count += 2; } - for (auto &envRegionBox : collision->mEnvRegionBoxes) { + for (auto& envRegionBox : collision->mEnvRegionBoxes) { write << fourSpaceTab; write << "COL_WATER_BOX("; write << envRegionBox.id << ", "; @@ -243,10 +244,11 @@ ExportResult SM64::CollisionCodeExporter::Export(std::ostream &write, std::share return offset + count * sizeof(int16_t); } -ExportResult SM64::CollisionHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> data, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::CollisionHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -255,7 +257,8 @@ ExportResult SM64::CollisionHeaderExporter::Export(std::ostream &write, std::sha return std::nullopt; } -ExportResult SM64::CollisionBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> data, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::CollisionBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto collision = std::static_pointer_cast<Collision>(data).get(); std::vector<int16_t> commands; @@ -266,14 +269,14 @@ ExportResult SM64::CollisionBinaryExporter::Export(std::ostream &write, std::sha if (collision->mVertices.size() > 0) { commands.push_back((int16_t)COL_VERTEX_INIT(collision->mVertices.size())); } - for (auto &vertex : collision->mVertices) { + for (auto& vertex : collision->mVertices) { commands.push_back(vertex.x); commands.push_back(vertex.y); commands.push_back(vertex.z); } // Surfaces - for (auto &surface : collision->mSurfaces) { + for (auto& surface : collision->mSurfaces) { // size check is probably not necessary here if (surface.tris.size() > 0) { commands.push_back((int16_t)surface.surfaceType); @@ -293,7 +296,7 @@ ExportResult SM64::CollisionBinaryExporter::Export(std::ostream &write, std::sha default: break; } - for (auto &tri : surface.tris) { + for (auto& tri : surface.tris) { commands.push_back(tri.x); commands.push_back(tri.y); commands.push_back(tri.z); @@ -311,7 +314,7 @@ ExportResult SM64::CollisionBinaryExporter::Export(std::ostream &write, std::sha commands.push_back((int16_t)TERRAIN_LOAD_OBJECTS); commands.push_back((int16_t)collision->mSpecialObjects.size()); } - for (auto &specialObject : collision->mSpecialObjects) { + for (auto& specialObject : collision->mSpecialObjects) { commands.push_back((int16_t)specialObject.presetId); commands.push_back(specialObject.x); commands.push_back(specialObject.y); @@ -326,7 +329,7 @@ ExportResult SM64::CollisionBinaryExporter::Export(std::ostream &write, std::sha commands.push_back((int16_t)TERRAIN_LOAD_ENVIRONMENT); commands.push_back((int16_t)collision->mEnvRegionBoxes.size()); } - for (auto &envRegionBox : collision->mEnvRegionBoxes) { + for (auto& envRegionBox : collision->mEnvRegionBoxes) { commands.push_back(envRegionBox.id); commands.push_back(envRegionBox.x1); commands.push_back(envRegionBox.z1); @@ -335,19 +338,20 @@ ExportResult SM64::CollisionBinaryExporter::Export(std::ostream &write, std::sha commands.push_back(envRegionBox.height); } - commands.push_back((int16_t) COL_END()); + commands.push_back((int16_t)COL_END()); LUS::BinaryWriter output = LUS::BinaryWriter(); WriteHeader(output, Torch::ResourceType::Collision, 0); output.Write(static_cast<uint32_t>(commands.size())); - output.Write((char*) commands.data(), commands.size() * sizeof(int16_t)); + output.Write((char*)commands.data(), commands.size() * sizeof(int16_t)); output.Finish(write); output.Close(); return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::CollisionFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::CollisionFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { std::vector<CollisionVertex> vertices; std::vector<CollisionSurface> surfaces; std::vector<SpecialObject> specialObjects; @@ -441,7 +445,8 @@ std::optional<std::shared_ptr<IParsedData>> SM64::CollisionFactory::parse(std::v envRegionBoxes.emplace_back(id, x1, z1, x2, z2, height); } } else if (terrainLoadType == TERRAIN_LOAD_CONTINUE) { - // need to figure out a way to handle when this should appear in exporters. seems to always be after vertices + // need to figure out a way to handle when this should appear in exporters. seems to always be after + // vertices } else if (terrainLoadType == TERRAIN_LOAD_END) { processing = false; } else if (TERRAIN_LOAD_IS_SURFACE_TYPE_HIGH(terrainLoadType)) { diff --git a/src/factories/sm64/DialogFactory.cpp b/src/factories/sm64/DialogFactory.cpp index c223dbe..d3bc057 100644 --- a/src/factories/sm64/DialogFactory.cpp +++ b/src/factories/sm64/DialogFactory.cpp @@ -2,18 +2,19 @@ #include "spdlog/spdlog.h" #include "utils/Decompressor.h" -ExportResult SM64::DialogBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::DialogBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto dialog = std::static_pointer_cast<DialogData>(raw); WriteHeader(writer, Torch::ResourceType::SDialog, 0); - writer.Write((uint32_t) dialog->mUnused); - writer.Write((int8_t) dialog->mLinesPerBox); - writer.Write((int16_t) dialog->mLeftOffset); - writer.Write((int16_t) dialog->mWidth); + writer.Write((uint32_t)dialog->mUnused); + writer.Write((int8_t)dialog->mLinesPerBox); + writer.Write((int16_t)dialog->mLeftOffset); + writer.Write((int16_t)dialog->mWidth); - writer.Write((uint32_t) dialog->mText.size()); - writer.Write((char*) dialog->mText.data(), dialog->mText.size()); + writer.Write((uint32_t)dialog->mText.size()); + writer.Write((char*)dialog->mText.data(), dialog->mText.size()); writer.Finish(write); return std::nullopt; } @@ -37,7 +38,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::DialogFactory::parse(std::vect auto str = SEGMENT_OFFSET(reader.ReadInt32()); std::vector<uint8_t> text; - while(root->data[str] != 0xFF){ + while (root->data[str] != 0xFF) { auto c = root->data[str++]; text.push_back(c); } diff --git a/src/factories/sm64/DictionaryFactory.cpp b/src/factories/sm64/DictionaryFactory.cpp index 4da939c..268e060 100644 --- a/src/factories/sm64/DictionaryFactory.cpp +++ b/src/factories/sm64/DictionaryFactory.cpp @@ -2,14 +2,16 @@ #include "spdlog/spdlog.h" -ExportResult SM64::DictionaryBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::DictionaryBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto data = std::static_pointer_cast<DictionaryData>(raw); WriteHeader(writer, Torch::ResourceType::Dictionary, 0); writer.Write(static_cast<uint32_t>(data->mDictionary.size())); - for(auto& [key, value] : data->mDictionary){ + for (auto& [key, value] : data->mDictionary) { writer.Write(key); writer.Write(static_cast<uint32_t>(value.size())); writer.Write(reinterpret_cast<char*>(value.data()), value.size()); @@ -18,7 +20,8 @@ ExportResult SM64::DictionaryBinaryExporter::Export(std::ostream &write, std::sh return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::DictionaryFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& data) { +std::optional<std::shared_ptr<IParsedData>> SM64::DictionaryFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& data) { std::unordered_map<std::string, std::vector<uint8_t>> dictionary; for (auto it = data["keys"].begin(); it != data["keys"].end(); ++it) { @@ -28,7 +31,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::DictionaryFactory::parse(std:: std::vector<uint8_t> text; const auto bytes = buffer.data(); - while(bytes[offset] != 0xFF){ + while (bytes[offset] != 0xFF) { auto c = bytes[offset++]; text.push_back(c); } diff --git a/src/factories/sm64/GeoLayoutFactory.cpp b/src/factories/sm64/GeoLayoutFactory.cpp index 73e4a2e..124a6ad 100644 --- a/src/factories/sm64/GeoLayoutFactory.cpp +++ b/src/factories/sm64/GeoLayoutFactory.cpp @@ -28,7 +28,7 @@ uint64_t RegisterAutoGen(uint32_t ptr, std::string type) { void StoreFunc(uint32_t vram) { return; - if(!Torch::contains(gFunctionMap, vram)) { + if (!Torch::contains(gFunctionMap, vram)) { return; } @@ -57,7 +57,8 @@ SM64::GeoLayoutFactory::GeoLayoutFactory() { // } } -ExportResult SM64::GeoCodeExporter::Export(std::ostream&write, std::shared_ptr<IParsedData> data, std::string&entryName, YAML::Node&node, std::string* replacement) { +ExportResult SM64::GeoCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto cmds = std::static_pointer_cast<GeoLayout>(data)->commands; const auto symbol = GetSafeNode(node, "symbol", entryName); uint32_t indentCount = 1; @@ -65,7 +66,7 @@ ExportResult SM64::GeoCodeExporter::Export(std::ostream&write, std::shared_ptr<I write << "GeoLayout " << symbol << "[] = {\n"; - for(auto& [opcode, arguments, skip] : cmds) { + for (auto& [opcode, arguments, skip] : cmds) { bool commaFlag = false; if (opcode == GeoOpcode::OpenNode) { @@ -81,14 +82,14 @@ ExportResult SM64::GeoCodeExporter::Export(std::ostream&write, std::shared_ptr<I } write << opcode << "("; - for(auto& args : arguments) { + for (auto& args : arguments) { if (commaFlag) { write << ", "; } else { commaFlag = true; } - switch(static_cast<GeoArgumentType>(args.index())) { + switch (static_cast<GeoArgumentType>(args.index())) { case GeoArgumentType::U8: { write << std::hex << "0x" << static_cast<uint32_t>(std::get<uint8_t>(args)); break; @@ -143,12 +144,12 @@ ExportResult SM64::GeoCodeExporter::Export(std::ostream&write, std::shared_ptr<I } case GeoArgumentType::VEC3S: { const auto [x, y, z] = std::get<Vec3s>(args); - write << std::dec << x << ", " << y << ", " << z; + write << std::dec << x << ", " << y << ", " << z; break; } case GeoArgumentType::VEC3I: { const auto [x, y, z] = std::get<Vec3i>(args); - write << std::dec << x << ", " << y << ", " << z; + write << std::dec << x << ", " << y << ", " << z; break; } case GeoArgumentType::VEC4F: { @@ -158,7 +159,7 @@ ExportResult SM64::GeoCodeExporter::Export(std::ostream&write, std::shared_ptr<I } case GeoArgumentType::VEC4S: { const auto [x, y, z, w] = std::get<Vec4s>(args); - write << std::dec << x << ", " << y << ", " << z << ", " << w; + write << std::dec << x << ", " << y << ", " << z << ", " << w; break; } case GeoArgumentType::STRING: { @@ -170,7 +171,7 @@ ExportResult SM64::GeoCodeExporter::Export(std::ostream&write, std::shared_ptr<I } } } - if(skip){ + if (skip) { write << "), //! more close than open nodes\n"; } else { write << "),\n"; @@ -189,20 +190,21 @@ ExportResult SM64::GeoCodeExporter::Export(std::ostream&write, std::shared_ptr<I return std::nullopt; } -ExportResult SM64::GeoBinaryExporter::Export(std::ostream&write, std::shared_ptr<IParsedData> data, std::string&entryName, YAML::Node&node, std::string* replacement) { +ExportResult SM64::GeoBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto layout = std::static_pointer_cast<GeoLayout>(data).get(); auto writer = LUS::BinaryWriter(); - for(auto& [opcode, arguments, skip] : layout->commands) { - if(skip){ + for (auto& [opcode, arguments, skip] : layout->commands) { + if (skip) { opcode = GeoOpcode::End; arguments.clear(); } writer.Write(static_cast<uint8_t>(opcode)); - for(auto& args : arguments) { - switch(static_cast<GeoArgumentType>(args.index())) { + for (auto& args : arguments) { + switch (static_cast<GeoArgumentType>(args.index())) { case GeoArgumentType::U8: { writer.Write(std::get<uint8_t>(args)); break; @@ -304,10 +306,11 @@ ExportResult SM64::GeoBinaryExporter::Export(std::ostream&write, std::shared_ptr return std::nullopt; } -ExportResult SM64::GeoHeaderExporter::Export(std::ostream&write, std::shared_ptr<IParsedData> data, std::string&entryName, YAML::Node&node, std::string* replacement) { +ExportResult SM64::GeoHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> data, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const ALIGN_ASSET(2) char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -317,7 +320,8 @@ ExportResult SM64::GeoHeaderExporter::Export(std::ostream&write, std::shared_ptr return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::GeoLayoutFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::GeoLayoutFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); auto cmd = segment.data; @@ -325,7 +329,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::GeoLayoutFactory::parse(std::v int32_t openCount = 0; std::vector<GeoCommand> commands; - while(processing) { + while (processing) { auto opcode = static_cast<GeoOpcode>(cmd[0x00]); auto skip = false; @@ -333,7 +337,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::GeoLayoutFactory::parse(std::v std::vector<GeoArgument> arguments; - switch(opcode){ + switch (opcode) { case GeoOpcode::BranchAndLink: { auto ptr = cur_geo_cmd_u32(0x04); if (ptr == 0) { @@ -498,7 +502,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::GeoLayoutFactory::parse(std::v Vec3s translation = {}; Vec3s rotation = {}; auto params = cur_geo_cmd_u8(0x01); - auto cmd_pos = reinterpret_cast<int16_t *>(cmd); + auto cmd_pos = reinterpret_cast<int16_t*>(cmd); arguments.emplace_back(params); @@ -532,14 +536,14 @@ std::optional<std::shared_ptr<IParsedData>> SM64::GeoLayoutFactory::parse(std::v cmd_pos += 2 << CMD_SIZE_SHIFT; } - cmd = reinterpret_cast<uint8_t *>(cmd_pos); + cmd = reinterpret_cast<uint8_t*>(cmd_pos); break; } - case GeoOpcode::NodeTranslation: + case GeoOpcode::NodeTranslation: case GeoOpcode::NodeRotation: { Vec3s vector = {}; auto params = cur_geo_cmd_u8(0x01); - auto cmd_pos = reinterpret_cast<int16_t *>(cmd); + auto cmd_pos = reinterpret_cast<int16_t*>(cmd); arguments.emplace_back(params); @@ -553,7 +557,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::GeoLayoutFactory::parse(std::v cmd_pos += 2 << CMD_SIZE_SHIFT; } - cmd = reinterpret_cast<uint8_t *>(cmd_pos); + cmd = reinterpret_cast<uint8_t*>(cmd_pos); break; } case GeoOpcode::NodeAnimatedPart: { @@ -672,7 +676,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::GeoLayoutFactory::parse(std::v } case GeoOpcode::NodeScale: { auto params = cur_geo_cmd_u8(0x01); - auto scale = cur_geo_cmd_u32(0x04); + auto scale = cur_geo_cmd_u32(0x04); arguments.emplace_back(params); arguments.emplace_back(scale); diff --git a/src/factories/sm64/LevelScriptFactory.cpp b/src/factories/sm64/LevelScriptFactory.cpp index c866a0a..10fd53b 100644 --- a/src/factories/sm64/LevelScriptFactory.cpp +++ b/src/factories/sm64/LevelScriptFactory.cpp @@ -20,10 +20,12 @@ uint64_t RegisterPtr(uint32_t ptr, std::string type) { return ptr; } -ExportResult SM64::LevelScriptHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::LevelScriptHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -32,7 +34,8 @@ ExportResult SM64::LevelScriptHeaderExporter::Export(std::ostream &write, std::s return std::nullopt; } -ExportResult SM64::LevelScriptCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::LevelScriptCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto commands = std::static_pointer_cast<LevelScriptData>(raw)->mCommands; @@ -40,7 +43,7 @@ ExportResult SM64::LevelScriptCodeExporter::Export(std::ostream &write, std::sha write << "static const LevelScript " << symbol << "[] = {\n"; - for(auto& [opcode, arguments] : commands) { + for (auto& [opcode, arguments] : commands) { bool commaFlag = false; if (opcode == LevelOpcode::END_AREA) { @@ -56,14 +59,14 @@ ExportResult SM64::LevelScriptCodeExporter::Export(std::ostream &write, std::sha } write << opcode << "("; - for(auto& args : arguments) { + for (auto& args : arguments) { if (commaFlag) { write << ", "; } else { commaFlag = true; } - switch(static_cast<LevelArgumentType>(args.index())) { + switch (static_cast<LevelArgumentType>(args.index())) { case LevelArgumentType::U8: { write << std::hex << "0x" << static_cast<uint32_t>(std::get<uint8_t>(args)); break; @@ -124,7 +127,9 @@ ExportResult SM64::LevelScriptCodeExporter::Export(std::ostream &write, std::sha return offset + size; } -ExportResult SM64::LevelScriptBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::LevelScriptBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); const auto commands = std::static_pointer_cast<LevelScriptData>(raw)->mCommands; @@ -132,11 +137,11 @@ ExportResult SM64::LevelScriptBinaryExporter::Export(std::ostream &write, std::s writer.Write((uint32_t)commands.size()); - for(auto& [opcode, arguments] : commands) { + for (auto& [opcode, arguments] : commands) { writer.Write(static_cast<uint8_t>(opcode)); - for(auto& args : arguments) { - switch(static_cast<LevelArgumentType>(args.index())) { + for (auto& args : arguments) { + switch (static_cast<LevelArgumentType>(args.index())) { case LevelArgumentType::U8: { writer.Write(std::get<uint8_t>(args)); break; @@ -190,7 +195,8 @@ ExportResult SM64::LevelScriptBinaryExporter::Export(std::ostream &write, std::s return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::LevelScriptFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::LevelScriptFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); auto cmd = segment.data; bool processing = true; @@ -203,7 +209,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::LevelScriptFactory::parse(std: count = 0; } - while(processing) { + while (processing) { auto opcode = static_cast<LevelOpcode>(cmd[0x00]); SPDLOG_INFO("Processing Command {}", opcode); diff --git a/src/factories/sm64/MacroFactory.cpp b/src/factories/sm64/MacroFactory.cpp index f5073d4..354bff4 100644 --- a/src/factories/sm64/MacroFactory.cpp +++ b/src/factories/sm64/MacroFactory.cpp @@ -6,10 +6,11 @@ #include "utils/TorchUtils.h" #include <regex> -ExportResult SM64::MacroHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::MacroHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,7 +19,8 @@ ExportResult SM64::MacroHeaderExporter::Export(std::ostream &write, std::shared_ return std::nullopt; } -ExportResult SM64::MacroCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::MacroCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -45,15 +47,16 @@ ExportResult SM64::MacroCodeExporter::Export(std::ostream &write, std::shared_pt return offset + size; } -ExportResult SM64::MacroBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::MacroBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto macro = std::static_pointer_cast<SM64::MacroDataAlt>(raw); WriteHeader(writer, Torch::ResourceType::MacroObject, 0); - writer.Write((uint32_t) macro->mMacroData.size()); + writer.Write((uint32_t)macro->mMacroData.size()); - for(auto &entry : macro->mMacroData){ + for (auto& entry : macro->mMacroData) { writer.Write(entry); } /* @@ -66,7 +69,7 @@ ExportResult SM64::MacroBinaryExporter::Export(std::ostream &write, std::shared_ writer.Write(object.behParam); } */ - + writer.Finish(write); return std::nullopt; } @@ -78,9 +81,9 @@ std::optional<std::shared_ptr<IParsedData>> SM64::MacroFactory::parse(std::vecto std::vector<int16_t> entries; - while(reader.GetBaseAddress() < segment.size) { + while (reader.GetBaseAddress() < segment.size) { int16_t raw = reader.ReadInt16(); - if(raw == 0x1E){ + if (raw == 0x1E) { break; } diff --git a/src/factories/sm64/MovtexFactory.cpp b/src/factories/sm64/MovtexFactory.cpp index 28e0170..5d9566f 100644 --- a/src/factories/sm64/MovtexFactory.cpp +++ b/src/factories/sm64/MovtexFactory.cpp @@ -6,10 +6,11 @@ #include "utils/TorchUtils.h" #include <regex> -ExportResult SM64::MovtexHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::MovtexHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,7 +19,8 @@ ExportResult SM64::MovtexHeaderExporter::Export(std::ostream &write, std::shared return std::nullopt; } -ExportResult SM64::MovtexCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::MovtexCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -35,10 +37,14 @@ ExportResult SM64::MovtexCodeExporter::Export(std::ostream &write, std::shared_p uint32_t base = 1 + (i * 14); write << fourSpaceTab << "MOV_TEX_ROT_SPEED(" << movtex->mMovtexData.at(base + 0) << "),\n"; write << fourSpaceTab << "MOV_TEX_ROT_SCALE(" << movtex->mMovtexData.at(base + 1) << "),\n"; - write << fourSpaceTab << "MOV_TEX_4_BOX_TRIS(" << movtex->mMovtexData.at(base + 2) << ", " << movtex->mMovtexData.at(base + 3) << "),\n"; - write << fourSpaceTab << "MOV_TEX_4_BOX_TRIS(" << movtex->mMovtexData.at(base + 4) << ", " << movtex->mMovtexData.at(base + 5) << "),\n"; - write << fourSpaceTab << "MOV_TEX_4_BOX_TRIS(" << movtex->mMovtexData.at(base + 6) << ", " << movtex->mMovtexData.at(base + 7) << "),\n"; - write << fourSpaceTab << "MOV_TEX_4_BOX_TRIS(" << movtex->mMovtexData.at(base + 8) << ", " << movtex->mMovtexData.at(base + 9) << "),\n"; + write << fourSpaceTab << "MOV_TEX_4_BOX_TRIS(" << movtex->mMovtexData.at(base + 2) << ", " + << movtex->mMovtexData.at(base + 3) << "),\n"; + write << fourSpaceTab << "MOV_TEX_4_BOX_TRIS(" << movtex->mMovtexData.at(base + 4) << ", " + << movtex->mMovtexData.at(base + 5) << "),\n"; + write << fourSpaceTab << "MOV_TEX_4_BOX_TRIS(" << movtex->mMovtexData.at(base + 6) << ", " + << movtex->mMovtexData.at(base + 7) << "),\n"; + write << fourSpaceTab << "MOV_TEX_4_BOX_TRIS(" << movtex->mMovtexData.at(base + 8) << ", " + << movtex->mMovtexData.at(base + 9) << "),\n"; write << fourSpaceTab << "MOV_TEX_ROT(" << movtex->mMovtexData.at(base + 10) << "),\n"; write << fourSpaceTab << "MOV_TEX_ALPHA(" << movtex->mMovtexData.at(base + 11) << "),\n"; write << fourSpaceTab << "MOV_TEX_DEFINE(" << movtex->mMovtexData.at(base + 12) << "),\n"; @@ -50,7 +56,8 @@ ExportResult SM64::MovtexCodeExporter::Export(std::ostream &write, std::shared_p additionalSize += 1; if (movtex->mHasColor) { for (uint32_t i = 0; i < movtex->mVertexCount; ++i) { - // There is also a MOV_TEX_LIGHT_TRIS macro, however this is identical in result to using MOV_TEX_ROT_TRIS and would require more params on the yaml + // There is also a MOV_TEX_LIGHT_TRIS macro, however this is identical in result to using + // MOV_TEX_ROT_TRIS and would require more params on the yaml write << fourSpaceTab << "MOV_TEX_ROT_TRIS("; write << movtex->mMovtexData.at(i * 8 + 1) << ", "; write << movtex->mMovtexData.at(i * 8 + 2) << ", "; @@ -82,7 +89,8 @@ ExportResult SM64::MovtexCodeExporter::Export(std::ostream &write, std::shared_p return offset + (additionalSize * sizeof(int16_t)); } -ExportResult SM64::MovtexBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::MovtexBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto movtex = std::static_pointer_cast<SM64::MovtexData>(raw); @@ -92,28 +100,28 @@ ExportResult SM64::MovtexBinaryExporter::Export(std::ostream &write, std::shared if (movtex->mIsQuad) { auto numLists = movtex->mMovtexData.at(0); - + buffer.push_back(numLists); buffer.push_back(0); // Alignment padding - + for (uint32_t i = 0; i < numLists; ++i) { - for(size_t j = 0; j < 14; j++){ + for (size_t j = 0; j < 14; j++) { buffer.push_back(movtex->mMovtexData.at(1 + (i * 14) + j)); } } } else { buffer.push_back(movtex->mMovtexData.at(0)); - + size_t triSize = movtex->mHasColor ? 8 : 5; for (uint32_t i = 0; i < movtex->mVertexCount * triSize; ++i) { buffer.push_back(movtex->mMovtexData.at(1 + i)); } - + buffer.push_back(0); // MOV_TEX_END } - writer.Write((uint32_t) buffer.size()); - writer.Write((char*) buffer.data(), buffer.size() * sizeof(int16_t)); + writer.Write((uint32_t)buffer.size()); + writer.Write((char*)buffer.data(), buffer.size() * sizeof(int16_t)); writer.Finish(write); return std::nullopt; diff --git a/src/factories/sm64/MovtexQuadFactory.cpp b/src/factories/sm64/MovtexQuadFactory.cpp index 250d268..b7285bd 100644 --- a/src/factories/sm64/MovtexQuadFactory.cpp +++ b/src/factories/sm64/MovtexQuadFactory.cpp @@ -6,10 +6,12 @@ #include "utils/TorchUtils.h" #include <regex> -ExportResult SM64::MovtexQuadHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::MovtexQuadHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,7 +20,8 @@ ExportResult SM64::MovtexQuadHeaderExporter::Export(std::ostream &write, std::sh return std::nullopt; } -ExportResult SM64::MovtexQuadCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::MovtexQuadCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -26,7 +29,7 @@ ExportResult SM64::MovtexQuadCodeExporter::Export(std::ostream &write, std::shar write << "const struct MovtexQuadCollection " << symbol << "[] = {\n"; - for (auto &quad: quadData->mMovtexQuads) { + for (auto& quad : quadData->mMovtexQuads) { write << fourSpaceTab << "{" << quad.first << ", "; if (quad.second == 0) { write << "NULL"; @@ -53,17 +56,19 @@ ExportResult SM64::MovtexQuadCodeExporter::Export(std::ostream &write, std::shar return offset + quadData->mMovtexQuads.size() * 4; } -ExportResult SM64::MovtexQuadBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::MovtexQuadBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); auto quadData = std::static_pointer_cast<SM64::MovtexQuadData>(raw); WriteHeader(writer, Torch::ResourceType::MovtexQuad, 0); - writer.Write((uint32_t) quadData->mMovtexQuads.size()); + writer.Write((uint32_t)quadData->mMovtexQuads.size()); - for (auto &quad: quadData->mMovtexQuads) { + for (auto& quad : quadData->mMovtexQuads) { writer.Write(quad.first); if (quad.second == 0) { - writer.Write((uint64_t) quad.second); + writer.Write((uint64_t)quad.second); } else { auto dec = Companion::Instance->GetNodeByAddr(quad.second); if (dec.has_value()) { @@ -82,7 +87,8 @@ ExportResult SM64::MovtexQuadBinaryExporter::Export(std::ostream &write, std::sh return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::MovtexQuadFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::MovtexQuadFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { const auto offset = GetSafeNode<uint32_t>(node, "offset"); const auto symbol = GetSafeNode<std::string>(node, "symbol"); const auto count = GetSafeNode<size_t>(node, "count"); diff --git a/src/factories/sm64/PaintingFactory.cpp b/src/factories/sm64/PaintingFactory.cpp index d9b40a4..fc40f49 100644 --- a/src/factories/sm64/PaintingFactory.cpp +++ b/src/factories/sm64/PaintingFactory.cpp @@ -6,10 +6,11 @@ #include "utils/TorchUtils.h" #include <regex> -ExportResult SM64::PaintingHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::PaintingHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,7 +19,8 @@ ExportResult SM64::PaintingHeaderExporter::Export(std::ostream &write, std::shar return std::nullopt; } -ExportResult SM64::PaintingCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::PaintingCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -96,24 +98,34 @@ ExportResult SM64::PaintingCodeExporter::Export(std::ostream &write, std::shared write << fourSpaceTab << "/* id */ " << std::hex << "0x" << painting->id << ",\n"; write << fourSpaceTab << "/* Image Count */ " << std::hex << "0x" << (uint32_t)painting->imageCount << ",\n"; write << fourSpaceTab << "/* Texture Type */ " << textureType.str() << ",\n"; - write << fourSpaceTab << "/* Floor Status */ " << std::hex << "0x" << (uint32_t)painting->lastFloor << ", " << std::hex << "0x" << (uint32_t)painting->currFloor << ", " << std::hex << "0x" << (uint32_t)painting->floorEntered << ",\n"; + write << fourSpaceTab << "/* Floor Status */ " << std::hex << "0x" << (uint32_t)painting->lastFloor << ", " + << std::hex << "0x" << (uint32_t)painting->currFloor << ", " << std::hex << "0x" + << (uint32_t)painting->floorEntered << ",\n"; write << fourSpaceTab << "/* Ripple Status */ " << (uint32_t)painting->state << ",\n"; write << fourSpaceTab << "/* Rotation */ " << painting->pitch << ", " << painting->yaw << ",\n"; - write << fourSpaceTab << "/* Position */ " << painting->posX << ", " << painting->posY << ", " << painting->posZ << ",\n"; - write << fourSpaceTab << "/* Ripple Magnitude */ " << painting->currRippleMag << ", " << painting->passiveRippleMag << ", " << painting->entryRippleMag << ",\n"; - write << fourSpaceTab << "/* Ripple Decay */ " << painting->rippleDecay << ", " << painting->passiveRippleDecay << ", " << painting->entryRippleDecay << ",\n"; - write << fourSpaceTab << "/* Ripple Rate */ " << painting->currRippleRate << ", " << painting->passiveRippleRate << ", " << painting->entryRippleRate << ",\n"; - write << fourSpaceTab << "/* Ripple Dispersion */ " << painting->dispersionFactor << ", " << painting->passiveDispersionFactor << ", " << painting->entryDispersionFactor << ",\n"; + write << fourSpaceTab << "/* Position */ " << painting->posX << ", " << painting->posY << ", " << painting->posZ + << ",\n"; + write << fourSpaceTab << "/* Ripple Magnitude */ " << painting->currRippleMag << ", " << painting->passiveRippleMag + << ", " << painting->entryRippleMag << ",\n"; + write << fourSpaceTab << "/* Ripple Decay */ " << painting->rippleDecay << ", " << painting->passiveRippleDecay + << ", " << painting->entryRippleDecay << ",\n"; + write << fourSpaceTab << "/* Ripple Rate */ " << painting->currRippleRate << ", " << painting->passiveRippleRate + << ", " << painting->entryRippleRate << ",\n"; + write << fourSpaceTab << "/* Ripple Dispersion */ " << painting->dispersionFactor << ", " + << painting->passiveDispersionFactor << ", " << painting->entryDispersionFactor << ",\n"; write << fourSpaceTab << "/* Curr Ripple Timer */ " << painting->rippleTimer << ",\n"; write << fourSpaceTab << "/* Curr Ripple x, y */ " << painting->rippleX << ", " << painting->rippleY << ",\n"; write << fourSpaceTab << "/* Normal DList */ " << nDLSymbol.str() << ",\n"; write << fourSpaceTab << "/* Texture Maps */ " << tMapSymbol.str() << ",\n"; write << fourSpaceTab << "/* Textures */ " << tArrSymbol.str() << ",\n"; - write << fourSpaceTab << "/* Texture w, h */ " << std::dec << painting->textureWidth << ", " << painting->textureHeight << ",\n"; + write << fourSpaceTab << "/* Texture w, h */ " << std::dec << painting->textureWidth << ", " + << painting->textureHeight << ",\n"; write << fourSpaceTab << "/* Ripple DList */ " << rDLSymbol.str() << ",\n"; write << fourSpaceTab << "/* Ripple Trigger */ " << rippleTrigger.str() << ",\n"; write << fourSpaceTab << "/* Alpha */ " << std::dec << (uint32_t)painting->alpha << ",\n"; - write << fourSpaceTab << "/* Mario Below */ " << std::hex << "0x" << (uint32_t)painting->marioWasUnder << ", " << std::hex << "0x" << (uint32_t)painting->marioIsUnder << ", " << std::hex << "0x" << (uint32_t)painting->marioWentUnder << ",\n"; + write << fourSpaceTab << "/* Mario Below */ " << std::hex << "0x" << (uint32_t)painting->marioWasUnder << ", " + << std::hex << "0x" << (uint32_t)painting->marioIsUnder << ", " << std::hex << "0x" + << (uint32_t)painting->marioWentUnder << ",\n"; write << fourSpaceTab << "/* Size */ " << painting->size << ",\n"; write << "};\n"; @@ -121,7 +133,8 @@ ExportResult SM64::PaintingCodeExporter::Export(std::ostream &write, std::shared return offset + 120; } -ExportResult SM64::PaintingBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::PaintingBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto painting = std::static_pointer_cast<SM64::Painting>(raw); uint32_t ptr; @@ -165,7 +178,7 @@ ExportResult SM64::PaintingBinaryExporter::Export(std::ostream &write, std::shar writer.Write(hash); } else { SPDLOG_WARN("Could not find DisplayList at 0x{:X}", ptr); - writer.Write((uint64_t) 0); + writer.Write((uint64_t)0); } } @@ -178,7 +191,7 @@ ExportResult SM64::PaintingBinaryExporter::Export(std::ostream &write, std::shar writer.Write(hash); } else { SPDLOG_WARN("Could not find Texture Maps at 0x{:X}", ptr); - writer.Write((uint64_t) 0); + writer.Write((uint64_t)0); } } @@ -191,7 +204,7 @@ ExportResult SM64::PaintingBinaryExporter::Export(std::ostream &write, std::shar writer.Write(hash); } else { SPDLOG_WARN("Could not find Texture Arrays at 0x{:X}", ptr); - writer.Write((uint64_t) 0); + writer.Write((uint64_t)0); } } @@ -207,7 +220,7 @@ ExportResult SM64::PaintingBinaryExporter::Export(std::ostream &write, std::shar writer.Write(hash); } else { SPDLOG_WARN("Could not find DisplayList at 0x{:X}", ptr); - writer.Write((uint64_t) 0); + writer.Write((uint64_t)0); } } @@ -222,7 +235,8 @@ ExportResult SM64::PaintingBinaryExporter::Export(std::ostream &write, std::shar return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::PaintingFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::PaintingFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, segment.size); reader.SetEndianness(Torch::Endianness::Big); @@ -280,5 +294,11 @@ std::optional<std::shared_ptr<IParsedData>> SM64::PaintingFactory::parse(std::ve rDLNode["offset"] = rippleDisplayList; Companion::Instance->AddAsset(rDLNode); - return std::make_shared<SM64::Painting>(id, imageCount, textureType, lastFloor, currFloor, floorEntered, state, pitch, yaw, posX, posY, posZ, currRippleMag, passiveRippleMag, entryRippleMag, rippleDecay, passiveRippleDecay, entryRippleDecay, currRippleRate, passiveRippleRate, entryRippleRate, dispersionFactor, passiveDispersionFactor, entryDispersionFactor, rippleTimer, rippleX, rippleY, normalDisplayList, textureMaps, textureArray, textureWidth, textureHeight, rippleDisplayList, rippleTrigger, alpha, marioWasUnder, marioIsUnder, marioWentUnder, size); + return std::make_shared<SM64::Painting>( + id, imageCount, textureType, lastFloor, currFloor, floorEntered, state, pitch, yaw, posX, posY, posZ, + currRippleMag, passiveRippleMag, entryRippleMag, rippleDecay, passiveRippleDecay, entryRippleDecay, + currRippleRate, passiveRippleRate, entryRippleRate, dispersionFactor, passiveDispersionFactor, + entryDispersionFactor, rippleTimer, rippleX, rippleY, normalDisplayList, textureMaps, textureArray, + textureWidth, textureHeight, rippleDisplayList, rippleTrigger, alpha, marioWasUnder, marioIsUnder, + marioWentUnder, size); } diff --git a/src/factories/sm64/PaintingMapFactory.cpp b/src/factories/sm64/PaintingMapFactory.cpp index 0366287..de367d3 100644 --- a/src/factories/sm64/PaintingMapFactory.cpp +++ b/src/factories/sm64/PaintingMapFactory.cpp @@ -8,10 +8,12 @@ // #define FORMAT_INT(x, w) std::dec << std::setfill(' ') << std::setw(w) << x -ExportResult SM64::PaintingMapHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::PaintingMapHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -20,7 +22,8 @@ ExportResult SM64::PaintingMapHeaderExporter::Export(std::ostream &write, std::s return std::nullopt; } -ExportResult SM64::PaintingMapCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::PaintingMapCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -30,26 +33,29 @@ ExportResult SM64::PaintingMapCodeExporter::Export(std::ostream &write, std::sha write << fourSpaceTab << paintingData->mPaintingMappings.size() << ",\n"; - for (auto &mapping : paintingData->mPaintingMappings) { + for (auto& mapping : paintingData->mPaintingMappings) { write << fourSpaceTab; write << mapping.vtxId << ", " << mapping.texX << ", " << mapping.texY << ",\n"; } write << fourSpaceTab << paintingData->mPaintingGroups.size() << ",\n"; - for (auto &group : paintingData->mPaintingGroups) { + for (auto& group : paintingData->mPaintingGroups) { write << fourSpaceTab; write << group.x << ", " << group.y << ", " << group.z << ",\n"; } write << "};\n"; - size_t size = (paintingData->mPaintingMappings.size() + paintingData->mPaintingGroups.size()) * 3 * sizeof(int16_t) + 2; + size_t size = + (paintingData->mPaintingMappings.size() + paintingData->mPaintingGroups.size()) * 3 * sizeof(int16_t) + 2; return offset + size; } -ExportResult SM64::PaintingMapBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::PaintingMapBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); auto paintingData = std::static_pointer_cast<SM64::PaintingData>(raw); @@ -58,19 +64,19 @@ ExportResult SM64::PaintingMapBinaryExporter::Export(std::ostream &write, std::s uint32_t mappingsSize = paintingData->mPaintingMappings.size(); uint32_t groupsSize = paintingData->mPaintingGroups.size(); - writer.Write((uint32_t) ((mappingsSize * 3) + (groupsSize * 3)) + 2); + writer.Write((uint32_t)((mappingsSize * 3) + (groupsSize * 3)) + 2); - writer.Write((int16_t) mappingsSize); + writer.Write((int16_t)mappingsSize); - for (auto &mapping : paintingData->mPaintingMappings) { + for (auto& mapping : paintingData->mPaintingMappings) { writer.Write(mapping.vtxId); writer.Write(mapping.texX); writer.Write(mapping.texY); } - writer.Write((int16_t) groupsSize); + writer.Write((int16_t)groupsSize); - for (auto &group : paintingData->mPaintingGroups) { + for (auto& group : paintingData->mPaintingGroups) { writer.Write(group.x); writer.Write(group.y); writer.Write(group.z); @@ -80,7 +86,8 @@ ExportResult SM64::PaintingMapBinaryExporter::Export(std::ostream &write, std::s return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::PaintingMapFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::PaintingMapFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { std::vector<PaintingMapping> paintingMappings; std::vector<Vec3s> paintingGroups; auto [_, segment] = Decompressor::AutoDecode(node, buffer); diff --git a/src/factories/sm64/TextFactory.cpp b/src/factories/sm64/TextFactory.cpp index 2b058dc..35b80c5 100644 --- a/src/factories/sm64/TextFactory.cpp +++ b/src/factories/sm64/TextFactory.cpp @@ -1,13 +1,14 @@ #include "TextFactory.h" #include "utils/Decompressor.h" -ExportResult SM64::TextBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::TextBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { auto writer = LUS::BinaryWriter(); auto data = std::static_pointer_cast<RawBuffer>(raw)->mBuffer; WriteHeader(writer, Torch::ResourceType::Blob, 0); - writer.Write((uint32_t) data.size()); - writer.Write((char*) data.data(), data.size()); + writer.Write((uint32_t)data.size()); + writer.Write((char*)data.data(), data.size()); writer.Finish(write); return std::nullopt; } @@ -18,7 +19,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::TextFactory::parse(std::vector auto [_, segment] = Decompressor::AutoDecode(node, buffer); size_t idx = 0; - while(segment.data[idx] != 0xFF){ + while (segment.data[idx] != 0xFF) { auto c = segment.data[idx++]; text.push_back(c); } diff --git a/src/factories/sm64/TrajectoryFactory.cpp b/src/factories/sm64/TrajectoryFactory.cpp index 5e43f93..5849a96 100644 --- a/src/factories/sm64/TrajectoryFactory.cpp +++ b/src/factories/sm64/TrajectoryFactory.cpp @@ -6,10 +6,12 @@ #include "utils/TorchUtils.h" #include <regex> -ExportResult SM64::TrajectoryHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::TrajectoryHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -18,7 +20,8 @@ ExportResult SM64::TrajectoryHeaderExporter::Export(std::ostream &write, std::sh return std::nullopt; } -ExportResult SM64::TrajectoryCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::TrajectoryCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -26,14 +29,15 @@ ExportResult SM64::TrajectoryCodeExporter::Export(std::ostream &write, std::shar write << "const Trajectory " << symbol << "[] = {\n"; - for (auto &trajectory : trajectoryData) { + for (auto& trajectory : trajectoryData) { write << fourSpaceTab; - if(trajectory.trajId == -1) { + if (trajectory.trajId == -1) { write << "TRAJECTORY_END(),\n"; break; } write << "TRAJECTORY_POS("; - write << trajectory.trajId << ", " << trajectory.posX << ", " << trajectory.posY << ", " << trajectory.posZ << "),\n"; + write << trajectory.trajId << ", " << trajectory.posX << ", " << trajectory.posY << ", " << trajectory.posZ + << "),\n"; } write << "\n};\n"; @@ -43,7 +47,9 @@ ExportResult SM64::TrajectoryCodeExporter::Export(std::ostream &write, std::shar return offset + size; } -ExportResult SM64::TrajectoryBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::TrajectoryBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); auto trajectoryData = std::static_pointer_cast<SM64::TrajectoryData>(raw)->mTrajectoryData; @@ -51,7 +57,7 @@ ExportResult SM64::TrajectoryBinaryExporter::Export(std::ostream &write, std::sh writer.Write((uint32_t)trajectoryData.size()); - for (auto &trajectory : trajectoryData) { + for (auto& trajectory : trajectoryData) { writer.Write(trajectory.trajId); writer.Write(trajectory.posX); writer.Write(trajectory.posY); @@ -62,7 +68,8 @@ ExportResult SM64::TrajectoryBinaryExporter::Export(std::ostream &write, std::sh return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::TrajectoryFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::TrajectoryFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { std::vector<Trajectory> trajectoryData; auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, segment.size); diff --git a/src/factories/sm64/WaterDropletFactory.cpp b/src/factories/sm64/WaterDropletFactory.cpp index a6b2d41..a15bd1b 100644 --- a/src/factories/sm64/WaterDropletFactory.cpp +++ b/src/factories/sm64/WaterDropletFactory.cpp @@ -8,10 +8,12 @@ #define FORMAT_FLOAT(x) std::fixed << std::setprecision(1) << x << "f" -ExportResult SM64::WaterDropletHeaderExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement) { +ExportResult SM64::WaterDropletHeaderExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); - if(Companion::Instance->IsOTRMode()){ + if (Companion::Instance->IsOTRMode()) { write << "static const char " << symbol << "[] = \"__OTR__" << (*replacement) << "\";\n\n"; return std::nullopt; } @@ -20,7 +22,9 @@ ExportResult SM64::WaterDropletHeaderExporter::Export(std::ostream &write, std:: return std::nullopt; } -ExportResult SM64::WaterDropletCodeExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::WaterDropletCodeExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { const auto symbol = GetSafeNode(node, "symbol", entryName); const auto offset = GetSafeNode<uint32_t>(node, "offset"); @@ -101,18 +105,24 @@ ExportResult SM64::WaterDropletCodeExporter::Export(std::ostream &write, std::sh write << fourSpaceTab << "/* Flags */ " << flagData.str() << ",\n"; write << fourSpaceTab << "/* Model */ " << model.str() << ",\n"; write << fourSpaceTab << "/* Behavior */ " << bhvSymbol.str() << ",\n"; - write << fourSpaceTab << "/* Move angle range */ " << std::hex << "0x" << waterDropletData->moveAngleRange << std::dec << ",\n"; + write << fourSpaceTab << "/* Move angle range */ " << std::hex << "0x" << waterDropletData->moveAngleRange + << std::dec << ",\n"; write << fourSpaceTab << "/* Unused (flag-specific) */ " << waterDropletData->moveRange << ",\n"; - write << fourSpaceTab << "/* Random fvel offset, scale */ " << FORMAT_FLOAT(waterDropletData->randForwardVelOffset) << ", " << FORMAT_FLOAT(waterDropletData->randForwardVelScale) << ",\n"; - write << fourSpaceTab << "/* Random yvel offset, scale */ " << FORMAT_FLOAT(waterDropletData->randYVelOffset) << ", " << FORMAT_FLOAT(waterDropletData->randYVelScale) << ",\n"; - write << fourSpaceTab << "/* Random size offset, scale */ " << FORMAT_FLOAT(waterDropletData->randSizeOffset) << ", " << FORMAT_FLOAT(waterDropletData->randSizeScale) << ",\n"; + write << fourSpaceTab << "/* Random fvel offset, scale */ " << FORMAT_FLOAT(waterDropletData->randForwardVelOffset) + << ", " << FORMAT_FLOAT(waterDropletData->randForwardVelScale) << ",\n"; + write << fourSpaceTab << "/* Random yvel offset, scale */ " << FORMAT_FLOAT(waterDropletData->randYVelOffset) + << ", " << FORMAT_FLOAT(waterDropletData->randYVelScale) << ",\n"; + write << fourSpaceTab << "/* Random size offset, scale */ " << FORMAT_FLOAT(waterDropletData->randSizeOffset) + << ", " << FORMAT_FLOAT(waterDropletData->randSizeScale) << ",\n"; write << "};\n"; return offset + 36; } -ExportResult SM64::WaterDropletBinaryExporter::Export(std::ostream &write, std::shared_ptr<IParsedData> raw, std::string& entryName, YAML::Node &node, std::string* replacement ) { +ExportResult SM64::WaterDropletBinaryExporter::Export(std::ostream& write, std::shared_ptr<IParsedData> raw, + std::string& entryName, YAML::Node& node, + std::string* replacement) { auto writer = LUS::BinaryWriter(); auto waterDropletData = std::static_pointer_cast<SM64::WaterDropletData>(raw); @@ -142,7 +152,8 @@ ExportResult SM64::WaterDropletBinaryExporter::Export(std::ostream &write, std:: return std::nullopt; } -std::optional<std::shared_ptr<IParsedData>> SM64::WaterDropletFactory::parse(std::vector<uint8_t>& buffer, YAML::Node& node) { +std::optional<std::shared_ptr<IParsedData>> SM64::WaterDropletFactory::parse(std::vector<uint8_t>& buffer, + YAML::Node& node) { auto [_, segment] = Decompressor::AutoDecode(node, buffer); LUS::BinaryReader reader(segment.data, segment.size); reader.SetEndianness(Torch::Endianness::Big); @@ -165,5 +176,7 @@ std::optional<std::shared_ptr<IParsedData>> SM64::WaterDropletFactory::parse(std // bhvNode["offset"] = behavior; // Companion::Instance->AddAsset(bhvNode); - return std::make_shared<SM64::WaterDropletData>(flags, model, behavior, moveAngleRange, moveRange, randForwardVelOffset, randForwardVelScale, randYVelOffset, randYVelScale, randSizeOffset, randSizeScale); + return std::make_shared<SM64::WaterDropletData>(flags, model, behavior, moveAngleRange, moveRange, + randForwardVelOffset, randForwardVelScale, randYVelOffset, + randYVelScale, randSizeOffset, randSizeScale); } diff --git a/src/factories/sm64/geo/GeoUtils.cpp b/src/factories/sm64/geo/GeoUtils.cpp index c42386b..075c473 100644 --- a/src/factories/sm64/geo/GeoUtils.cpp +++ b/src/factories/sm64/geo/GeoUtils.cpp @@ -2,14 +2,14 @@ #define next_s16_in_geo_script(src) (int16_t) BSWAP16((*(*src)++)) -int16_t* read_vec3s_to_vec3f(Vec3f& dst, int16_t *src) { +int16_t* read_vec3s_to_vec3f(Vec3f& dst, int16_t* src) { dst.x = next_s16_in_geo_script(&src); dst.y = next_s16_in_geo_script(&src); dst.z = next_s16_in_geo_script(&src); return src; } -int16_t* read_vec3s(Vec3s& dst, int16_t *src) { +int16_t* read_vec3s(Vec3s& dst, int16_t* src) { dst.x = next_s16_in_geo_script(&src); dst.y = next_s16_in_geo_script(&src); dst.z = next_s16_in_geo_script(&src); diff --git a/src/main.cpp b/src/main.cpp index dd09b31..55b49d6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,11 +4,10 @@ #if defined(STANDALONE) && !defined(__EMSCRIPTEN__) -int main(int argc, char *argv[]) { - CLI::App app{"Torch - [T]orch is [O]ur [R]esource [C]onversion [H]elper\n\ +int main(int argc, char* argv[]) { + CLI::App app{ "Torch - [T]orch is [O]ur [R]esource [C]onversion [H]elper\n\ * It extracts from a baserom and generates code or an otr.\n\ - * It can also generate an otr from a folder of assets.\n" - }; + * It can also generate an otr from a folder of assets.\n" }; std::string mode; std::string filename; std::string target; @@ -30,7 +29,9 @@ int main(int argc, char *argv[]) { otr->add_option("<baserom.z64>", filename, "")->required()->check(CLI::ExistingFile); otr->add_flag("-v,--verbose", debug, "Verbose Debug Mode"); - otr->add_option("-s,--srcdir", srcdir, "Set source directory to locate config.yml and asset metadata for processing")->check(CLI::ExistingDirectory); + otr->add_option("-s,--srcdir", srcdir, + "Set source directory to locate config.yml and asset metadata for processing") + ->check(CLI::ExistingDirectory); otr->add_option("-d,--destdir", destdir, "Set destination directory for export"); otr->parse_complete_callback([&] { @@ -43,9 +44,13 @@ int main(int argc, char *argv[]) { o2r->add_option("<baserom.z64>", filename, "")->required()->check(CLI::ExistingFile); o2r->add_flag("-v,--verbose", debug, "Verbose Debug Mode"); - o2r->add_option("-s,--srcdir", srcdir, "Set source directory to locate config.yml and asset metadata for processing")->check(CLI::ExistingDirectory); + o2r->add_option("-s,--srcdir", srcdir, + "Set source directory to locate config.yml and asset metadata for processing") + ->check(CLI::ExistingDirectory); o2r->add_option("-d,--destdir", destdir, "Set destination directory for export"); - o2r->add_option("-a,--additional-files", additionalFiles, "Additional files to include in the o2r archive (e.g., mods.toml)")->check(CLI::ExistingFile); + o2r->add_option("-a,--additional-files", additionalFiles, + "Additional files to include in the o2r archive (e.g., mods.toml)") + ->check(CLI::ExistingFile); o2r->add_option("-u,--version", version, "Version to set in the o2r archive"); o2r->parse_complete_callback([&] { @@ -60,7 +65,9 @@ int main(int argc, char *argv[]) { code->add_option("<baserom.z64>", filename, "")->required()->check(CLI::ExistingFile); code->add_flag("-v,--verbose", debug, "Verbose Debug Mode; adds offsets to C code"); - code->add_option("-s,--srcdir", srcdir, "Set source directory to locate config.yml and asset metadata for processing")->check(CLI::ExistingDirectory); + code->add_option("-s,--srcdir", srcdir, + "Set source directory to locate config.yml and asset metadata for processing") + ->check(CLI::ExistingDirectory); code->add_option("-d,--destdir", destdir, "Set destination directory to place C code to"); code->parse_complete_callback([&]() { @@ -72,7 +79,10 @@ int main(int argc, char *argv[]) { const auto binary = app.add_subcommand("binary", "Binary - Generates a binary\n"); binary->add_option("<baserom.z64>", filename, "")->required()->check(CLI::ExistingFile); - binary->add_option("-s,--srcdir", srcdir, "Set source directory to locate config.yml and asset metadata for processing")->check(CLI::ExistingDirectory); + binary + ->add_option("-s,--srcdir", srcdir, + "Set source directory to locate config.yml and asset metadata for processing") + ->check(CLI::ExistingDirectory); binary->add_option("-d,--destdir", destdir, "Set destination directory to place binary to"); binary->parse_complete_callback([&] { @@ -85,7 +95,10 @@ int main(int argc, char *argv[]) { header->add_option("<baserom.z64>", filename, "")->required()->check(CLI::ExistingFile); header->add_flag("-o,--otr", otrModeSelected, "OTR/O2R Mode"); - header->add_option("-s,--srcdir", srcdir, "Set source directory to locate config.yml and asset metadata for processing")->check(CLI::ExistingDirectory); + header + ->add_option("-s,--srcdir", srcdir, + "Set source directory to locate config.yml and asset metadata for processing") + ->check(CLI::ExistingDirectory); header->add_option("-d,--destdir", destdir, "Set destination directory to place headers to"); header->parse_complete_callback([&] { @@ -102,7 +115,9 @@ int main(int argc, char *argv[]) { /* Pack an archive from a folder */ const auto pack = app.add_subcommand("pack", "Pack - Packs an archive from a folder\n"); - pack->add_option("<folder>", folder, "Generate OTR from a directory of assets")->required()->check(CLI::ExistingDirectory); + pack->add_option("<folder>", folder, "Generate OTR from a directory of assets") + ->required() + ->check(CLI::ExistingDirectory); pack->add_option("<target>", target, "Archive output destination")->required(); pack->add_option("<archive-type>", archive, "Archive type: otr or o2r")->required(); pack->add_option("-u,--version", version, "Version to set in the o2r archive"); @@ -125,13 +140,18 @@ int main(int argc, char *argv[]) { /* Generate modding files */ const auto modding_root = app.add_subcommand("modding", "Modding - Generates modding files like png\n"); - const auto modding_import = modding_root->add_subcommand("import", "Import - Import modified files to generate C code\n"); + const auto modding_import = + modding_root->add_subcommand("import", "Import - Import modified files to generate C code\n"); const auto modding_export = modding_root->add_subcommand("export", "Export - Export modified files to a folder\n"); modding_import->add_option("mode", mode, "code, otr, o2r or header")->required(); modding_import->add_option("<baserom.z64>", filename, "")->required()->check(CLI::ExistingFile); modding_import->add_flag("-v,--verbose", debug, "Verbose Debug Mode"); - modding_import->add_option("-s,--srcdir", srcdir, "Set source directory to locate config.yml and asset metadata for processing, including modified files")->check(CLI::ExistingDirectory); + modding_import + ->add_option( + "-s,--srcdir", srcdir, + "Set source directory to locate config.yml and asset metadata for processing, including modified files") + ->check(CLI::ExistingDirectory); modding_import->add_option("-d,--destdir", destdir, "Set destination directory to place for generating C code"); modding_import->parse_complete_callback([&] { @@ -159,8 +179,13 @@ int main(int argc, char *argv[]) { modding_export->add_flag("-x,--xml", xmlMode, "XML Mode"); modding_export->add_option("<baserom.z64>", filename, "")->required()->check(CLI::ExistingFile); - modding_export->add_option("-s,--srcdir", srcdir, "Set source directory to locate config.yml and asset metadata for processing, including modified files")->check(CLI::ExistingDirectory); - modding_export->add_option("-d,--destdir", destdir, "Set destination directory to place for generating modified files"); + modding_export + ->add_option( + "-s,--srcdir", srcdir, + "Set source directory to locate config.yml and asset metadata for processing, including modified files") + ->check(CLI::ExistingDirectory); + modding_export->add_option("-d,--destdir", destdir, + "Set destination directory to place for generating modified files"); modding_export->parse_complete_callback([&] { const auto instance = Companion::Instance = new Companion(filename, ArchiveType::None, debug, srcdir, destdir); @@ -173,7 +198,7 @@ int main(int argc, char *argv[]) { try { app.parse(argc, argv); - } catch (const CLI::ParseError &e) { + } catch (const CLI::ParseError& e) { std::cout << app.help() << std::endl; return app.exit(e); } diff --git a/src/n64/Cartridge.cpp b/src/n64/Cartridge.cpp index f3c1f83..cca2f78 100644 --- a/src/n64/Cartridge.cpp +++ b/src/n64/Cartridge.cpp @@ -4,7 +4,7 @@ #include <Companion.h> void N64::Cartridge::Initialize() { - LUS::BinaryReader reader((char*) this->gRomData.data(), this->gRomData.size()); + LUS::BinaryReader reader((char*)this->gRomData.data(), this->gRomData.size()); reader.SetEndianness(Torch::Endianness::Big); reader.Seek(0x10, LUS::SeekOffsetType::Start); this->gRomCRC = BSWAP32(reader.ReadUInt32()); @@ -32,7 +32,7 @@ void N64::Cartridge::Initialize() { reader.Close(); } -const std::string &N64::Cartridge::GetGameTitle() { +const std::string& N64::Cartridge::GetGameTitle() { return this->gGameTitle; } diff --git a/src/preprocess/CompTool.cpp b/src/preprocess/CompTool.cpp index bd7182e..3b04a2e 100644 --- a/src/preprocess/CompTool.cpp +++ b/src/preprocess/CompTool.cpp @@ -6,15 +6,17 @@ #include <cstring> uint32_t CompTool::FindFileTable(std::vector<uint8_t>& rom) { - uint8_t query_one[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x50, 0x00, 0x00, 0x00, 0x00 }; - uint8_t query_two[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x60, 0x00, 0x00, 0x00, 0x00 }; + uint8_t query_one[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x50, 0x00, 0x00, 0x00, 0x00 }; + uint8_t query_two[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x60, 0x00, 0x00, 0x00, 0x00 }; - for(size_t i = 0; i < rom.size() - sizeof(query_one); i++) { - if(memcmp(rom.data() + i, query_one, sizeof(query_one)) == 0){ + for (size_t i = 0; i < rom.size() - sizeof(query_one); i++) { + if (memcmp(rom.data() + i, query_one, sizeof(query_one)) == 0) { return i; } - if(memcmp(rom.data() + i, query_two, sizeof(query_two)) == 0){ + if (memcmp(rom.data() + i, query_two, sizeof(query_two)) == 0) { return i; } } @@ -24,8 +26,7 @@ uint32_t CompTool::FindFileTable(std::vector<uint8_t>& rom) { #define ROL(i, b) ((i << (b)) | (i >> (32 - (b)))) -std::pair<uint32_t, uint32_t> CompTool::CalculateCRCs(LUS::BinaryWriter& decompFile) -{ +std::pair<uint32_t, uint32_t> CompTool::CalculateCRCs(LUS::BinaryWriter& decompFile) { uint32_t start = 0x1000; uint32_t end = 0x101000; LUS::BinaryReader readFile(decompFile.GetStream()); @@ -55,8 +56,8 @@ std::pair<uint32_t, uint32_t> CompTool::CalculateCRCs(LUS::BinaryWriter& decompF return std::make_pair(t6 ^ t4 ^ t3, t5 ^ t2 ^ t1); } -std::vector<uint8_t> CompTool::Decompress(std::vector<uint8_t> rom){ - LUS::BinaryReader basefile((char*) rom.data(), rom.size()); +std::vector<uint8_t> CompTool::Decompress(std::vector<uint8_t> rom) { + LUS::BinaryReader basefile((char*)rom.data(), rom.size()); basefile.SetEndianness(Torch::Endianness::Big); LUS::BinaryWriter decompfile; @@ -65,7 +66,7 @@ std::vector<uint8_t> CompTool::Decompress(std::vector<uint8_t> rom){ uint32_t table = CompTool::FindFileTable(rom); uint32_t count = 0; - while (true){ + while (true) { auto entry = table + 0x10 * count; basefile.Seek(entry, LUS::SeekOffsetType::Start); @@ -75,19 +76,19 @@ std::vector<uint8_t> CompTool::Decompress(std::vector<uint8_t> rom){ auto comp_flag = basefile.ReadInt32(); auto p_size = p_end - p_begin; - auto v_size = (int32_t) 0; + auto v_size = (int32_t)0; DataChunk* decoded = nullptr; - if(v_begin == 0 && p_end == 0){ + if (v_begin == 0 && p_end == 0) { break; } basefile.Seek(p_begin, LUS::SeekOffsetType::Start); auto bytes = new uint8_t[p_size]; - basefile.Read((char*) bytes, p_size); + basefile.Read((char*)bytes, p_size); - switch ((CompType) comp_flag) { + switch ((CompType)comp_flag) { case CompType::UNCOMPRESSED: v_size = p_size; break; @@ -101,13 +102,13 @@ std::vector<uint8_t> CompTool::Decompress(std::vector<uint8_t> rom){ } decompfile.Seek(v_begin, LUS::SeekOffsetType::Start); - decompfile.Write((char*) bytes, v_size); + decompfile.Write((char*)bytes, v_size); auto v_end = v_begin + v_size; decompfile.Seek(entry + 4, LUS::SeekOffsetType::Start); decompfile.Write(v_begin); decompfile.Write(v_end); - decompfile.Write((uint32_t) CompType::UNCOMPRESSED); + decompfile.Write((uint32_t)CompType::UNCOMPRESSED); count++; } @@ -115,9 +116,9 @@ std::vector<uint8_t> CompTool::Decompress(std::vector<uint8_t> rom){ decompfile.Seek(0x10, LUS::SeekOffsetType::Start); - decompfile.Write(crcs.first); // CRC1 + decompfile.Write(crcs.first); // CRC1 decompfile.Write(crcs.second); // CRC2 auto result = decompfile.ToVector(); - return { (uint8_t*) result.data(), (uint8_t*) result.data() + result.size() }; + return { (uint8_t*)result.data(), (uint8_t*)result.data() + result.size() }; }
\ No newline at end of file diff --git a/src/types/Vec3D.cpp b/src/types/Vec3D.cpp index ab263f8..8962c1e 100644 --- a/src/types/Vec3D.cpp +++ b/src/types/Vec3D.cpp @@ -6,7 +6,7 @@ static int GetPrecision(float f) { int shift = 1; float approx = std::round(f); - while(f != approx && p < 12 ){ + while (f != approx && p < 12) { shift *= 10; p++; approx = std::round(f * shift) / shift; @@ -18,16 +18,17 @@ static int GetMagnitude(float f) { int w = 1; float a = std::abs(f); - if(a >= 1) { + if (a >= 1) { w += std::log10(a); - } - if(f < 0) { + } + if (f < 0) { w++; } return w; } -Vec3f::Vec3f(float xv, float yv, float zv) : x(xv), y(yv), z(zv) {} +Vec3f::Vec3f(float xv, float yv, float zv) : x(xv), y(yv), z(zv) { +} int Vec3f::precision() { auto px = GetPrecision(this->x); @@ -45,14 +46,16 @@ int Vec3f::width() { return std::max(wx, std::max(wy, wz)) + 1 + this->precision(); } -std::ostream& operator<< (std::ostream& stream, const Vec3f& vec) { +std::ostream& operator<<(std::ostream& stream, const Vec3f& vec) { int width = stream.width(); - stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " << std::setw(width) << vec.z << "}"; + stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " + << std::setw(width) << vec.z << "}"; return stream; } -Vec3s::Vec3s(int16_t xv, int16_t yv, int16_t zv) : x(xv), y(yv), z(zv) {} +Vec3s::Vec3s(int16_t xv, int16_t yv, int16_t zv) : x(xv), y(yv), z(zv) { +} int Vec3s::width() { auto wx = GetMagnitude(this->x); @@ -62,14 +65,16 @@ int Vec3s::width() { return std::max(wx, std::max(wy, wz)); } -std::ostream& operator<< (std::ostream& stream, const Vec3s& vec) { +std::ostream& operator<<(std::ostream& stream, const Vec3s& vec) { int width = stream.width(); - stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " << std::setw(width) << vec.z << "}"; + stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " + << std::setw(width) << vec.z << "}"; return stream; } -Vec3i::Vec3i(int32_t xv, int32_t yv, int32_t zv) : x(xv), y(yv), z(zv) {} +Vec3i::Vec3i(int32_t xv, int32_t yv, int32_t zv) : x(xv), y(yv), z(zv) { +} int Vec3i::width() { auto wx = GetMagnitude(this->x); @@ -79,14 +84,16 @@ int Vec3i::width() { return std::max(wx, std::max(wy, wz)); } -std::ostream& operator<< (std::ostream& stream, const Vec3i& vec) { +std::ostream& operator<<(std::ostream& stream, const Vec3i& vec) { int width = stream.width(); - stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " << std::setw(width) << vec.z << "}"; + stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " + << std::setw(width) << vec.z << "}"; return stream; } -Vec3iu::Vec3iu(uint32_t xv, uint32_t yv, uint32_t zv) : x(xv), y(yv), z(zv) {} +Vec3iu::Vec3iu(uint32_t xv, uint32_t yv, uint32_t zv) : x(xv), y(yv), z(zv) { +} int Vec3iu::width() { auto wx = GetMagnitude(this->x); @@ -96,14 +103,16 @@ int Vec3iu::width() { return std::max(wx, std::max(wy, wz)); } -std::ostream& operator<< (std::ostream& stream, const Vec3iu& vec) { +std::ostream& operator<<(std::ostream& stream, const Vec3iu& vec) { int width = stream.width(); - stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " << std::setw(width) << vec.z << "}"; + stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " + << std::setw(width) << vec.z << "}"; return stream; } -Vec2f::Vec2f(float xv, float zv) : x(xv), z(zv) {} +Vec2f::Vec2f(float xv, float zv) : x(xv), z(zv) { +} int Vec2f::precision() { auto px = GetPrecision(this->x); @@ -116,17 +125,18 @@ int Vec2f::width() { auto wx = GetMagnitude(this->x) + 1 + GetPrecision(this->x); auto wz = GetMagnitude(this->z) + 1 + GetPrecision(this->z); - return std::max(wx, wz); + return std::max(wx, wz); } -std::ostream& operator<< (std::ostream& stream, const Vec2f& vec) { +std::ostream& operator<<(std::ostream& stream, const Vec2f& vec) { int width = stream.width(); stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.z << "}"; return stream; } -Vec4f::Vec4f(float xv, float yv, float zv, float wv) : x(xv), y(yv), z(zv), w(wv) {} +Vec4f::Vec4f(float xv, float yv, float zv, float wv) : x(xv), y(yv), z(zv), w(wv) { +} int Vec4f::width() { auto wx = GetMagnitude(this->x) + 1 + GetPrecision(this->x); @@ -134,7 +144,7 @@ int Vec4f::width() { auto wz = GetMagnitude(this->z) + 1 + GetPrecision(this->z); auto ww = GetMagnitude(this->w) + 1 + GetPrecision(this->w); - return std::max(std::max(wy, ww), std::max(wx, wz)); + return std::max(std::max(wy, ww), std::max(wx, wz)); } int Vec4f::precision() { @@ -146,14 +156,16 @@ int Vec4f::precision() { return std::max(std::max(px, pw), std::max(py, pz)); } -std::ostream& operator<< (std::ostream& stream, const Vec4f& vec) { +std::ostream& operator<<(std::ostream& stream, const Vec4f& vec) { int width = stream.width(); - stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " << std::setw(width) << vec.z << ", " << std::setw(width) << vec.w << "}"; + stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " + << std::setw(width) << vec.z << ", " << std::setw(width) << vec.w << "}"; return stream; } -Vec4s::Vec4s(int16_t xv, int16_t yv, int16_t zv, int16_t wv) : x(xv), y(yv), z(zv), w(wv) {} +Vec4s::Vec4s(int16_t xv, int16_t yv, int16_t zv, int16_t wv) : x(xv), y(yv), z(zv), w(wv) { +} int Vec4s::width() { auto wx = GetMagnitude(this->x); @@ -164,9 +176,10 @@ int Vec4s::width() { return std::max(std::max(wx, ww), std::max(wy, wz)); } -std::ostream& operator<< (std::ostream& stream, const Vec4s& vec) { +std::ostream& operator<<(std::ostream& stream, const Vec4s& vec) { int width = stream.width(); - stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " << std::setw(width) << vec.z << ", " << std::setw(width) << vec.w << "}"; + stream << std::setw(0) << "{" << std::setw(width) << vec.x << ", " << std::setw(width) << vec.y << ", " + << std::setw(width) << vec.z << ", " << std::setw(width) << vec.w << "}"; return stream; } diff --git a/src/utils/Decompressor.cpp b/src/utils/Decompressor.cpp index 9181099..2cf9412 100644 --- a/src/utils/Decompressor.cpp +++ b/src/utils/Decompressor.cpp @@ -14,9 +14,10 @@ extern "C" { std::unordered_map<uint32_t, DataChunk*> gCachedChunks; -DataChunk* Decompressor::Decode(const std::vector<uint8_t>& buffer, const uint32_t offset, const CompressionType type, bool ignoreCache) { +DataChunk* Decompressor::Decode(const std::vector<uint8_t>& buffer, const uint32_t offset, const CompressionType type, + bool ignoreCache) { - if(!ignoreCache && Torch::contains(gCachedChunks, offset)){ + if (!ignoreCache && Torch::contains(gCachedChunks, offset)) { return gCachedChunks[offset]; } @@ -25,7 +26,7 @@ DataChunk* Decompressor::Decode(const std::vector<uint8_t>& buffer, const uint32 switch (type) { case CompressionType::MIO0: { mio0_header_t head; - if(!mio0_decode_header(in_buf, &head)){ + if (!mio0_decode_header(in_buf, &head)) { throw std::runtime_error("Failed to decode MIO0 header"); } @@ -38,7 +39,7 @@ DataChunk* Decompressor::Decode(const std::vector<uint8_t>& buffer, const uint32 uint32_t size = 0; uint8_t* decompressed = yay0_decode(in_buf, &size); - if(!decompressed){ + if (!decompressed) { throw std::runtime_error("Failed to decode YAY0"); } @@ -49,7 +50,7 @@ DataChunk* Decompressor::Decode(const std::vector<uint8_t>& buffer, const uint32 uint32_t size = 0; uint8_t* decompressed = yay1_decode(in_buf, &size); - if(!decompressed){ + if (!decompressed) { throw std::runtime_error("Failed to decode YAY1"); } @@ -61,8 +62,9 @@ DataChunk* Decompressor::Decode(const std::vector<uint8_t>& buffer, const uint32 } } -DataChunk* Decompressor::DecodeTKMK00(const std::vector<uint8_t>& buffer, const uint32_t offset, const uint32_t size, const uint32_t alpha) { - if(Torch::contains(gCachedChunks, offset)){ +DataChunk* Decompressor::DecodeTKMK00(const std::vector<uint8_t>& buffer, const uint32_t offset, const uint32_t size, + const uint32_t alpha) { + if (Torch::contains(gCachedChunks, offset)) { return gCachedChunks[offset]; } @@ -75,7 +77,8 @@ DataChunk* Decompressor::DecodeTKMK00(const std::vector<uint8_t>& buffer, const return gCachedChunks[offset]; } -DecompressedData Decompressor::AutoDecode(YAML::Node& node, std::vector<uint8_t>& buffer, std::optional<size_t> manualSize) { +DecompressedData Decompressor::AutoDecode(YAML::Node& node, std::vector<uint8_t>& buffer, + std::optional<size_t> manualSize) { auto offset = GetSafeNode<uint32_t>(node, "offset"); CompressionType type = Companion::Instance->GetCurrCompressionType(); @@ -102,15 +105,14 @@ DecompressedData Decompressor::AutoDecode(YAML::Node& node, std::vector<uint8_t> size = decodedSize; } - if(size > decodedSize) { - SPDLOG_WARN("Requested size 0x{:X} exceeds decoded MIO0 asset size 0x{:X} at offset 0x{:X}. Reducing to available size.", size, decodedSize, assetPtr); + if (size > decodedSize) { + SPDLOG_WARN("Requested size 0x{:X} exceeds decoded MIO0 asset size 0x{:X} at offset 0x{:X}. Reducing to " + "available size.", + size, decodedSize, assetPtr); size = decodedSize; } - return { - .root = decoded, - .segment = { decoded->data, size } - }; + return { .root = decoded, .segment = { decoded->data, size } }; } // Check if an asset in a yaml file is tkmk00 compressed and extract (mk64). @@ -136,19 +138,18 @@ DecompressedData Decompressor::AutoDecode(YAML::Node& node, std::vector<uint8_t> size = decodedSize; } - if(size > decodedSize) { - SPDLOG_WARN("Requested size 0x{:X} exceeds decoded TKMK00 asset size 0x{:X} at offset 0x{:X}. Reducing to available size.", size, decodedSize, assetPtr); + if (size > decodedSize) { + SPDLOG_WARN("Requested size 0x{:X} exceeds decoded TKMK00 asset size 0x{:X} at offset 0x{:X}. Reducing to " + "available size.", + size, decodedSize, assetPtr); size = decodedSize; } - return { - .root = decoded, - .segment = { decoded->data, size } - }; + return { .root = decoded, .segment = { decoded->data, size } }; } // Extract a compressed file which contains many assets. - switch(type) { + switch (type) { case CompressionType::YAY0: case CompressionType::YAY1: case CompressionType::MIO0: { @@ -166,18 +167,18 @@ DecompressedData Decompressor::AutoDecode(YAML::Node& node, std::vector<uint8_t> size = availableSize; } - if(size > availableSize) { - SPDLOG_WARN("Requested size 0x{:X} exceeds decoded asset size 0x{:X} at offset 0x{:X}. Reducing to available size.", size, availableSize, fileOffset); + if (size > availableSize) { + SPDLOG_WARN("Requested size 0x{:X} exceeds decoded asset size 0x{:X} at offset 0x{:X}. Reducing to " + "available size.", + size, availableSize, fileOffset); size = availableSize; } - return { - .root = decoded, - .segment = { decoded->data + offset, size } - }; + return { .root = decoded, .segment = { decoded->data + offset, size } }; } case CompressionType::YAZ0: - throw std::runtime_error("Found compressed yaz0 segment.\nDecompression of yaz0 has not been implemented yet."); + throw std::runtime_error( + "Found compressed yaz0 segment.\nDecompression of yaz0 has not been implemented yet."); case CompressionType::None: // The data does not have compression { fileOffset = TranslateAddr(offset, false); @@ -193,19 +194,19 @@ DecompressedData Decompressor::AutoDecode(YAML::Node& node, std::vector<uint8_t> size = availableSize; } - if(size > availableSize) { - SPDLOG_WARN("Requested size 0x{:X} exceeds available asset size 0x{:X} at offset 0x{:X}. Reducing to available size.", size, availableSize, fileOffset); + if (size > availableSize) { + SPDLOG_WARN("Requested size 0x{:X} exceeds available asset size 0x{:X} at offset 0x{:X}. Reducing to " + "available size.", + size, availableSize, fileOffset); size = availableSize; } - return { - .root = nullptr, - .segment = { buffer.data() + fileOffset, size } - }; + return { .root = nullptr, .segment = { buffer.data() + fileOffset, size } }; } } - throw std::runtime_error("Auto decode could not find a compression type nor uncompressed segment.\nThis is one of those issues that should never really happen."); + throw std::runtime_error("Auto decode could not find a compression type nor uncompressed segment.\nThis is one of " + "those issues that should never really happen."); } DecompressedData Decompressor::AutoDecode(uint32_t offset, std::optional<size_t> size, std::vector<uint8_t>& buffer) { @@ -215,11 +216,12 @@ DecompressedData Decompressor::AutoDecode(uint32_t offset, std::optional<size_t> return AutoDecode(node, buffer, size); } -uint32_t Decompressor::TranslateAddr(uint32_t addr, bool baseAddress){ - if(IS_SEGMENTED(addr)){ +uint32_t Decompressor::TranslateAddr(uint32_t addr, bool baseAddress) { + if (IS_SEGMENTED(addr)) { const auto segment = Companion::Instance->GetFileOffsetFromSegmentedAddr(SEGMENT_NUMBER(addr)); - if(!segment.has_value()) { - SPDLOG_ERROR("Segment data missing from game config\nPlease add an entry for segment {}", SEGMENT_NUMBER(addr)); + if (!segment.has_value()) { + SPDLOG_ERROR("Segment data missing from game config\nPlease add an entry for segment {}", + SEGMENT_NUMBER(addr)); return 0; } @@ -228,10 +230,10 @@ uint32_t Decompressor::TranslateAddr(uint32_t addr, bool baseAddress){ const auto vramEntry = Companion::Instance->GetCurrentVRAM(); - if(vramEntry.has_value()){ + if (vramEntry.has_value()) { const auto vram = vramEntry.value(); - if(addr >= vram.addr){ + if (addr >= vram.addr) { return vram.offset + (addr - vram.addr); } } @@ -241,7 +243,7 @@ uint32_t Decompressor::TranslateAddr(uint32_t addr, bool baseAddress){ CompressionType Decompressor::GetCompressionType(std::vector<uint8_t>& buffer, const uint32_t offset) { if (offset) { - LUS::BinaryReader reader((char*) buffer.data() + offset, sizeof(uint32_t)); + LUS::BinaryReader reader((char*)buffer.data() + offset, sizeof(uint32_t)); reader.SetEndianness(Torch::Endianness::Big); const std::string header = reader.ReadCString(); @@ -267,11 +269,12 @@ CompressionType Decompressor::GetCompressionType(std::vector<uint8_t>& buffer, c } bool Decompressor::IsSegmented(uint32_t addr) { - if(IS_SEGMENTED(addr)){ + if (IS_SEGMENTED(addr)) { const auto segment = Companion::Instance->GetFileOffsetFromSegmentedAddr(SEGMENT_NUMBER(addr)); - if(!segment.has_value()) { - SPDLOG_ERROR("Segment data missing from game config\nPlease add an entry for segment {}", SEGMENT_NUMBER(addr)); + if (!segment.has_value()) { + SPDLOG_ERROR("Segment data missing from game config\nPlease add an entry for segment {}", + SEGMENT_NUMBER(addr)); return false; } @@ -282,7 +285,7 @@ bool Decompressor::IsSegmented(uint32_t addr) { } void Decompressor::ClearCache() { - for(auto& [key, value] : gCachedChunks){ + for (auto& [key, value] : gCachedChunks) { delete[] value->data; } gCachedChunks.clear(); diff --git a/src/utils/TextureUtils.cpp b/src/utils/TextureUtils.cpp index 7b70f19..117b941 100644 --- a/src/utils/TextureUtils.cpp +++ b/src/utils/TextureUtils.cpp @@ -29,7 +29,7 @@ size_t TextureUtils::CalculateTextureSize(TextureType type, uint32_t width, uint } } -std::vector<uint8_t> TextureUtils::alloc_ia8_text_from_i1(uint16_t *in, int16_t width, int16_t height) { +std::vector<uint8_t> TextureUtils::alloc_ia8_text_from_i1(uint16_t* in, int16_t width, int16_t height) { int32_t inPos; uint16_t bitMask; int16_t outPos = 0; diff --git a/src/utils/TorchUtils.cpp b/src/utils/TorchUtils.cpp index bf8b92a..86c836f 100644 --- a/src/utils/TorchUtils.cpp +++ b/src/utils/TorchUtils.cpp @@ -8,10 +8,10 @@ namespace fs = std::filesystem; uint32_t Torch::translate(const uint32_t offset) { - if(SEGMENT_NUMBER(offset) > 0x01) { + if (SEGMENT_NUMBER(offset) > 0x01) { auto segment = SEGMENT_NUMBER(offset); const auto addr = Companion::Instance->GetFileOffsetFromSegmentedAddr(segment); - if(!addr.has_value()) { + if (!addr.has_value()) { SPDLOG_ERROR("Segment data missing from game config\nPlease add an entry for segment {}", segment); throw std::runtime_error("Failed to find offset"); } |
