From fd6a5134ecb844e2805a03e2a4f9fd71107e0a52 Mon Sep 17 00:00:00 2001 From: evanchia Date: Thu, 8 Jul 2021 14:02:26 -0700 Subject: [PATCH 001/205] Adding C++ retry command Signed-off-by: evanchia --- Code/Tools/AzTestRunner/src/main.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Code/Tools/AzTestRunner/src/main.cpp b/Code/Tools/AzTestRunner/src/main.cpp index c6d887244f..e53e2ae799 100644 --- a/Code/Tools/AzTestRunner/src/main.cpp +++ b/Code/Tools/AzTestRunner/src/main.cpp @@ -126,6 +126,14 @@ namespace AzTestRunner std::cout << "arg[" << i << "] " << argv[i] << std::endl; } + // Construct a full retry command + std::cout << "Full command: " << argv[0] << " " << lib << " " << symbol; + for (int i = 1; i < argc; i++) + { + std::cout << " " << argv[i]; + } + std::cout << std::endl; + std::cout << "LIB: " << lib << std::endl; } From b1a1f78ca685dc4089d1c32c5734eae36680d888 Mon Sep 17 00:00:00 2001 From: evanchia Date: Mon, 12 Jul 2021 16:54:57 -0700 Subject: [PATCH 002/205] Moved retry command to after the test fails Signed-off-by: evanchia --- Code/Tools/AzTestRunner/src/main.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/Code/Tools/AzTestRunner/src/main.cpp b/Code/Tools/AzTestRunner/src/main.cpp index e53e2ae799..d846cd5cbd 100644 --- a/Code/Tools/AzTestRunner/src/main.cpp +++ b/Code/Tools/AzTestRunner/src/main.cpp @@ -126,17 +126,16 @@ namespace AzTestRunner std::cout << "arg[" << i << "] " << argv[i] << std::endl; } - // Construct a full retry command - std::cout << "Full command: " << argv[0] << " " << lib << " " << symbol; - for (int i = 1; i < argc; i++) - { - std::cout << " " << argv[i]; - } - std::cout << std::endl; - std::cout << "LIB: " << lib << std::endl; } + // Construct a retry command if test fails + std::string retry_command = "Retry command: " + std::string(argv[0]) + " " + lib + " " + symbol; + for (int i = 1; i < argc; i++) + { + retry_command.append(" " + std::string(argv[i])); + } + // Wait for debugger if (waitForDebugger) { @@ -230,6 +229,10 @@ namespace AzTestRunner if (testMainFunction->IsValid()) { result = (*testMainFunction)(argc, argv); + if (result != 0) + { + std::cout << retry_command << std::endl; + } std::cout << "OKAY " << symbol << "() returned " << result << std::endl; testMainFunction.reset(); } From 9bd5b9fbd62273693963bbd28c52c05476d07490 Mon Sep 17 00:00:00 2001 From: evanchia Date: Wed, 14 Jul 2021 16:09:00 -0700 Subject: [PATCH 003/205] Simplified and moved aztestrunner retry command Signed-off-by: evanchia --- Code/Tools/AzTestRunner/src/main.cpp | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Code/Tools/AzTestRunner/src/main.cpp b/Code/Tools/AzTestRunner/src/main.cpp index d846cd5cbd..96832c3fed 100644 --- a/Code/Tools/AzTestRunner/src/main.cpp +++ b/Code/Tools/AzTestRunner/src/main.cpp @@ -129,13 +129,6 @@ namespace AzTestRunner std::cout << "LIB: " << lib << std::endl; } - // Construct a retry command if test fails - std::string retry_command = "Retry command: " + std::string(argv[0]) + " " + lib + " " + symbol; - for (int i = 1; i < argc; i++) - { - retry_command.append(" " + std::string(argv[i])); - } - // Wait for debugger if (waitForDebugger) { @@ -229,14 +222,16 @@ namespace AzTestRunner if (testMainFunction->IsValid()) { result = (*testMainFunction)(argc, argv); - if (result != 0) - { - std::cout << retry_command << std::endl; - } std::cout << "OKAY " << symbol << "() returned " << result << std::endl; testMainFunction.reset(); } + // Construct a retry command if the test fails + if (result != 0) + { + std::cout << "Retry command: " << std::string(argv[0]) << " " << lib << " " << symbol << std::endl; + } + // unload and reset the module here, because it needs to release resources that were used / activated in // system allocator / etc. module.reset(); From ae60bd0167483bad342bcaae9fa2638ee5df91d9 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Fri, 16 Jul 2021 14:33:39 -0700 Subject: [PATCH 004/205] [installer/2106-font] revert back to default install bootstrapper font Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- .../Windows/Packaging/BootstrapperTheme.xml.in | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in b/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in index 8d8416539e..c670ef3d9a 100644 --- a/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in +++ b/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in @@ -4,15 +4,15 @@ #(loc.WindowTitle) - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI From 679ecf480197d234cc86fd123c5535a33c25d474 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 16 Jul 2021 17:40:27 -0500 Subject: [PATCH 005/205] External Gem and Projects now appear in Editor AssetBrowser (#2227) * External Gem and Projects now appear in Editor AssetBrowser Optimized logic populating the FolderAssetBrowserEntries in the Editor AssetBrowser. Added an "[External]" tag to scan folders which reside outside of the Engine Root Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Fixed conversion of fixed_string to string when normalizing an added AssetBrowser file path. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * RootAssetBrowserEntry.cpp Linux conditional expression fix Because an AZ::IO::PathView is convertible to an AZ::IO::FixedMaxPath and vice-versa, the conversion of the second part of the ternary expression absolutePathView needs to explicitly convert to an AZ::IO::FixedMaxPath Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- .../Entries/AssetBrowserEntry.cpp | 4 +- .../AssetBrowser/Entries/AssetBrowserEntry.h | 5 +- .../Entries/FolderAssetBrowserEntry.cpp | 4 +- .../Entries/RootAssetBrowserEntry.cpp | 201 ++++++++---------- .../Entries/RootAssetBrowserEntry.h | 12 +- .../Entries/SourceAssetBrowserEntry.cpp | 4 +- 6 files changed, 105 insertions(+), 125 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp index 17a20a9d19..7eae7621d2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.cpp @@ -206,12 +206,12 @@ namespace AzToolsFramework const AZStd::string& AssetBrowserEntry::GetRelativePath() const { - return m_relativePath; + return m_relativePath.Native(); } const AZStd::string& AssetBrowserEntry::GetFullPath() const { - return m_fullPath; + return m_fullPath.Native(); } const AssetBrowserEntry* AssetBrowserEntry::GetChild(int index) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h index e4a7b6b4cb..24f037a623 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h @@ -9,6 +9,7 @@ #if !defined(Q_MOC_RUN) #include #include +#include #include #include @@ -130,8 +131,8 @@ namespace AzToolsFramework protected: AZStd::string m_name; QString m_displayName; - AZStd::string m_relativePath; - AZStd::string m_fullPath; + AZ::IO::Path m_relativePath; + AZ::IO::Path m_fullPath; AZStd::vector m_children; AssetBrowserEntry* m_parentAssetEntry = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp index 3c5afab0d0..febd406f23 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/FolderAssetBrowserEntry.cpp @@ -37,8 +37,8 @@ namespace AzToolsFramework void FolderAssetBrowserEntry::UpdateChildPaths(AssetBrowserEntry* child) const { - child->m_relativePath = m_relativePath + AZ_CORRECT_DATABASE_SEPARATOR + child->m_name; - child->m_fullPath = m_fullPath + AZ_CORRECT_DATABASE_SEPARATOR + child->m_name; + child->m_relativePath = m_relativePath / child->m_name; + child->m_fullPath = m_fullPath / child->m_name; AssetBrowserEntry::UpdateChildPaths(child); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp index 090ad0d6ca..0e132d2581 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -24,8 +25,6 @@ namespace AzToolsFramework { namespace AssetBrowser { - const char* GEMS_FOLDER_NAME = "Gems"; - RootAssetBrowserEntry::RootAssetBrowserEntry() : AssetBrowserEntry() { @@ -53,13 +52,7 @@ namespace AzToolsFramework EntryCache::GetInstance()->Clear(); m_enginePath = enginePath; - - // there is no "Gems" scan folder registered in db, create one manually - auto gemFolder = aznew FolderAssetBrowserEntry(); - gemFolder->m_name = m_enginePath + AZ_CORRECT_DATABASE_SEPARATOR + GEMS_FOLDER_NAME; - gemFolder->m_displayName = GEMS_FOLDER_NAME; - gemFolder->m_isGemsFolder = true; - AddChild(gemFolder); + m_fullPath = enginePath; } bool RootAssetBrowserEntry::IsInitialUpdate() const @@ -80,8 +73,17 @@ namespace AzToolsFramework if (AZ::IO::FileIOBase::GetInstance()->IsDirectory(scanFolderDatabaseEntry.m_scanFolder.c_str())) { - const auto scanFolder = CreateFolders(scanFolderDatabaseEntry.m_scanFolder.c_str(), this); - scanFolder->m_displayName = QString::fromUtf8(scanFolderDatabaseEntry.m_displayName.c_str()); + const auto scanFolder = CreateFolders(scanFolderDatabaseEntry.m_scanFolder, this); + // Append an "[External]" to the display if the Scan Folder is NOT relative to the Engine Root path + if (!AZ::IO::PathView(scanFolderDatabaseEntry.m_scanFolder).IsRelativeTo(m_enginePath)) + { + scanFolder->m_displayName += " [External]"; + } + else + { + scanFolder->m_displayName = QString::fromUtf8(scanFolderDatabaseEntry.m_displayName.c_str()); + } + EntryCache::GetInstance()->m_scanFolderIdMap[scanFolderDatabaseEntry.m_scanFolderID] = scanFolder; } } @@ -121,38 +123,34 @@ namespace AzToolsFramework return; } - const char* filePath = fileDatabaseEntry.m_fileName.c_str(); + AZ::IO::FixedMaxPath absoluteFilePath = AZ::IO::FixedMaxPath(AZStd::string_view{ scanFolder->GetFullPath() }) + / fileDatabaseEntry.m_fileName.c_str(); AssetBrowserEntry* file; // file can be either folder or actual file if (fileDatabaseEntry.m_isFolder) { - file = CreateFolders(filePath, scanFolder); + file = CreateFolders(absoluteFilePath.Native(), scanFolder); } else { - AZStd::string sourcePath; - AZStd::string sourceName; - AZStd::string sourceExtension; - StringFunc::Path::Split(filePath, nullptr, &sourcePath, &sourceName, &sourceExtension); // if missing create folders leading to file's location and get immediate parent // (we don't need to have fileIds for any folders created yet, they will be added later) - auto parent = CreateFolders(sourcePath.c_str(), scanFolder); + auto parent = CreateFolders(absoluteFilePath.ParentPath().Native(), scanFolder); // for simplicity in AB, files are represented as sources, but they are missing SourceDatabaseEntry-specific information such as SourceUuid auto source = aznew SourceAssetBrowserEntry(); - source->m_name = (sourceName + sourceExtension).c_str(); + source->m_name = absoluteFilePath.Filename().Native(); source->m_fileId = fileDatabaseEntry.m_fileID; source->m_displayName = QString::fromUtf8(source->m_name.c_str()); source->m_scanFolderId = fileDatabaseEntry.m_scanFolderPK; - source->m_extension = sourceExtension.c_str(); + source->m_extension = absoluteFilePath.Extension().Native(); parent->AddChild(source); file = source; } EntryCache::GetInstance()->m_fileIdMap[fileDatabaseEntry.m_fileID] = file; - AZStd::string fullPath = file->m_fullPath; - AzFramework::StringFunc::Path::Normalize(fullPath); - EntryCache::GetInstance()->m_absolutePathToFileId[fullPath] = fileDatabaseEntry.m_fileID; + AZStd::string filePath = AZ::IO::PathView(file->m_fullPath).LexicallyNormal().String(); + EntryCache::GetInstance()->m_absolutePathToFileId[filePath] = fileDatabaseEntry.m_fileID; } bool RootAssetBrowserEntry::RemoveFile(const AZ::s64& fileId) const @@ -305,116 +303,95 @@ namespace AzToolsFramework } } - FolderAssetBrowserEntry* RootAssetBrowserEntry::CreateFolder(const char* folderName, AssetBrowserEntry* parent) + AssetBrowserEntry* RootAssetBrowserEntry::GetNearestAncestor(AZ::IO::PathView absolutePathView, AssetBrowserEntry* parent, + AZStd::unordered_set& visitedSet) + { + auto IsPathRelativeToEntry = [absolutePathView](AssetBrowserEntry* assetBrowserEntry) + { + auto& childPath = assetBrowserEntry->m_fullPath; + return absolutePathView.IsRelativeTo(AZ::IO::PathView(childPath)); + }; + + if (visitedSet.contains(parent)) + { + return {}; + } + + visitedSet.insert(parent); + + AssetBrowserEntry* nearestAncestor{}; + for (AssetBrowserEntry* childBrowserEntry : parent->m_children) + { + if (IsPathRelativeToEntry(childBrowserEntry)) + { + // Walk the AssetBrowserEntry Tree looking for a nearer ancestor to the absolute path + // If one is not found in the recursive call to GetNearestAncestor, then the childBrowserEntry + // is the current best candidate + AssetBrowserEntry* candidateAncestor = GetNearestAncestor(absolutePathView, childBrowserEntry, visitedSet); + candidateAncestor = candidateAncestor != nullptr ? candidateAncestor : childBrowserEntry; + AZ::IO::PathView candidatePathView(candidateAncestor->m_fullPath); + // If the candidate is relative to the current nearest ancestor, then it is even nearer to the path + if (!nearestAncestor || candidatePathView.IsRelativeTo(nearestAncestor->m_fullPath)) + { + nearestAncestor = candidateAncestor; + // If the full path compares equal to the AssetBrowserEntry path, then no need to proceed any further + if (AZ::IO::PathView(nearestAncestor->m_fullPath) == absolutePathView) + { + break; + } + } + } + } + + return nearestAncestor; + } + + FolderAssetBrowserEntry* RootAssetBrowserEntry::CreateFolder(AZStd::string_view folderName, AssetBrowserEntry* parent) { auto it = AZStd::find_if(parent->m_children.begin(), parent->m_children.end(), [folderName](AssetBrowserEntry* entry) - { - if (!azrtti_istypeof(entry)) - { - return false; - } - return AzFramework::StringFunc::Equal(entry->m_name.c_str(), folderName); - }); + { + if (!azrtti_istypeof(entry)) + { + return false; + } + return AZ::IO::PathView(entry->m_name) == AZ::IO::PathView(folderName); + }); if (it != parent->m_children.end()) { return azrtti_cast(*it); } const auto folder = aznew FolderAssetBrowserEntry(); folder->m_name = folderName; - folder->m_displayName = folderName; + folder->m_displayName = QString::fromUtf8(folderName.data(), aznumeric_caster(folderName.size())); parent->AddChild(folder); return folder; } - AssetBrowserEntry* RootAssetBrowserEntry::CreateFolders(const char* relativePath, AssetBrowserEntry* parent) + AssetBrowserEntry* RootAssetBrowserEntry::CreateFolders(AZStd::string_view absolutePath, AssetBrowserEntry* parent) { - auto children(parent->m_children); - int n = 0; + AZ::IO::PathView absolutePathView(absolutePath); + // Find the nearest ancestor path to the absolutePath + AZStd::unordered_set visitedSet; - // check if folder with the same name already exists - // step through every character in relativePath and compare to each child's relative path of suggested parent - // if a character @n in child's rel path mismatches character at n in relativePath, remove that child from further search - while (!children.empty() && relativePath[n]) + if (AssetBrowserEntry* nearestAncestor = GetNearestAncestor(absolutePathView, parent, visitedSet); + nearestAncestor != nullptr) { - AZStd::vector toRemove; - for (auto child : children) - { - auto& childPath = azrtti_istypeof(parent) ? child->m_fullPath : child->m_relativePath; - - // child's path mismatched, remove it from search candidates - if (childPath.length() == n || childPath[n] != relativePath[n]) - { - toRemove.push_back(child); - - // it is possible that child may be a closer parent, substitute it as new potential parent - // e.g. child->m_relativePath = 'Gems', relativePath = 'Gems/Assets', old parent = root, new parent = Gems - if (childPath.length() == n && relativePath[n] == AZ_CORRECT_DATABASE_SEPARATOR) - { - parent = child; - relativePath += n; // advance relative path n characters since the parent has changed - n = 0; // Once the relative path pointer is advanced, reset n - } - } - } - for (auto entry : toRemove) - { - children.erase(AZStd::remove(children.begin(), children.end(), entry), children.end()); - } - n++; + parent = nearestAncestor; } - // filter out the remaining children that don't end with '/' or '\0' - // for example if folderName = "foo", while children may still remain with names like "foo123", - // which is not the same folder - AZStd::vector toRemove; - for (auto child : children) + // If the nearest ancestor is the absolutePath, then it is already crated + if (absolutePathView == AZ::IO::PathView(parent->GetFullPath())) { - auto& childPath = azrtti_istypeof(parent) ? child->m_fullPath : child->m_relativePath; - // check if there are non-null characters remaining @n - if (childPath.length() > n) - { - toRemove.push_back(child); - } - } - for (auto entry : toRemove) - { - children.erase(AZStd::remove(children.begin(), children.end(), entry), children.end()); + return parent; } - // at least one child remains, this means the folder with this name already exists, return it - if (!children.empty()) + // create all missing folders + auto proximateToPath = absolutePathView.IsRelativeTo(parent->m_fullPath) + ? absolutePathView.LexicallyProximate(parent->m_fullPath) + : AZ::IO::FixedMaxPath(absolutePathView); + for (AZ::IO::FixedMaxPath scanFolderSegment : proximateToPath) { - parent = children.front(); - } - // if it's a scanfolder, then do not create folders leading to it - // e.g. instead of 'C:\dev\SampleProject' just create 'SampleProject' - else if (parent->GetEntryType() == AssetEntryType::Root) - { - AZStd::string folderName; - AzFramework::StringFunc::Path::Split(relativePath, nullptr, nullptr, &folderName); - parent = CreateFolder(folderName.c_str(), parent); - parent->m_fullPath = relativePath; - } - // otherwise create all missing folders - else - { - n = 0; - AZStd::string folderName(strlen(relativePath) + 1, '\0'); - // iterate through relativePath until the first '/' - while (relativePath[n] && relativePath[n] != AZ_CORRECT_DATABASE_SEPARATOR) - { - folderName[n] = relativePath[n]; - n++; - } - if (n > 0) - { - parent = CreateFolder(folderName.c_str(), parent); - } - // n+1 also skips the '/' character - if (relativePath[n] && relativePath[n + 1]) - { - parent = CreateFolders(relativePath + n + 1, parent); - } + parent = CreateFolder(scanFolderSegment.c_str(), parent); } return parent; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h index 883f9dec01..62fbc7a39d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -77,12 +78,15 @@ namespace AzToolsFramework private: AZ_DISABLE_COPY_MOVE(RootAssetBrowserEntry); - AZStd::string m_enginePath; + AZ::IO::Path m_enginePath; //! Create folder entry child - FolderAssetBrowserEntry* CreateFolder(const char* folderName, AssetBrowserEntry* parent); - //! Recursively create folder structure leading to relative path from parent - AssetBrowserEntry* CreateFolders(const char* relativePath, AssetBrowserEntry* parent); + FolderAssetBrowserEntry* CreateFolder(AZStd::string_view folderName, AssetBrowserEntry* parent); + //! Recursively create folder structure leading to path from parent + AssetBrowserEntry* CreateFolders(AZStd::string_view absolutePath, AssetBrowserEntry* parent); + // Retrieves the nearest ancestor AssetBrowserEntry from the absolutePath + static AssetBrowserEntry* GetNearestAncestor(AZ::IO::PathView absolutePath, AssetBrowserEntry* parent, + AZStd::unordered_set& visitedSet); bool m_isInitialUpdate = false; }; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.cpp index e45c234c92..1eea909f7c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.cpp @@ -26,9 +26,7 @@ namespace AzToolsFramework if (EntryCache* cache = EntryCache::GetInstance()) { cache->m_fileIdMap.erase(m_fileId); - AZStd::string fullPath = m_fullPath; - AzFramework::StringFunc::Path::Normalize(fullPath); - cache->m_absolutePathToFileId.erase(fullPath); + cache->m_absolutePathToFileId.erase(m_fullPath.LexicallyNormal().Native()); if (m_sourceId != -1) { From 173126f5a5f1b3a1efc65e5a902c48d63b2a5ad9 Mon Sep 17 00:00:00 2001 From: Brian Herrera Date: Mon, 19 Jul 2021 16:09:47 -0700 Subject: [PATCH 006/205] Add script for license scanner (#2267) * Add script for license scanner This script will scan the source tree for license files and generate a file with the contents of all the licenses. Signed-off-by: brianherrera --- scripts/license_scanner/license_scanner.py | 129 ++++++++++++++++++++ scripts/license_scanner/scanner_config.json | 12 ++ 2 files changed, 141 insertions(+) create mode 100644 scripts/license_scanner/license_scanner.py create mode 100644 scripts/license_scanner/scanner_config.json diff --git a/scripts/license_scanner/license_scanner.py b/scripts/license_scanner/license_scanner.py new file mode 100644 index 0000000000..c0e3c1f1ba --- /dev/null +++ b/scripts/license_scanner/license_scanner.py @@ -0,0 +1,129 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +import argparse +import fnmatch +import json +import os +import pathlib +import re +import sys + + +class LicenseScanner: + """Class to contain license scanner. + + Scans source tree for license files using provided filename patterns and generates a file + with the contents of all the licenses. + + :param config_file: Config file with license patterns and scanner settings + """ + + DEFAULT_CONFIG_FILE = 'scanner_config.json' + + def __init__(self, config_file=None): + self.config_file = config_file + self.config_data = self._load_config() + self.license_regex = self._load_license_regex() + + def _load_config(self): + """Load config from the provided file. Sets default file if one is not provided.""" + if self.config_file is None: + script_directory = os.path.dirname(os.path.abspath(__file__)) # Default file expected in same dir as script + self.config_file = os.path.join(script_directory, self.DEFAULT_CONFIG_FILE) + + try: + with open(self.config_file) as f: + return json.load(f) + except FileNotFoundError: + print('Config file cannot be found') + raise + + def _load_license_regex(self): + """Returns regex object with case-insensitive matching from the list of filename patterns.""" + regex_patterns = [] + for pattern in self.config_data['license_patterns']: + regex_patterns.append(fnmatch.translate(pattern)) + return re.compile('|'.join(regex_patterns), re.IGNORECASE) + + def scan(self, path=os.curdir): + """Scan directory tree for filenames matching license_regex. + + :param path: Path of the directory to run scanner + :return: Package paths and their corresponding license file contents + :rtype: dict + """ + licenses = 0 + license_files = {} + + for dirpath, dirnames, filenames in os.walk(path): + for file in filenames: + if self.license_regex.match(file): + license_file_content = self._get_license_file_contents(os.path.join(dirpath, file)) + rel_dirpath = os.path.relpath(dirpath, path) # Limit path inside scanned directory + license_files[rel_dirpath] = license_file_content + licenses += 1 + print(f'License file: {os.path.join(dirpath, file)}') + + # Remove directories that should not be scanned + for dir in self.config_data['excluded_directories']: + if dir in dirnames: + dirnames.remove(dir) + print(f'{licenses} license files found.') + return license_files + + def _get_license_file_contents(self, filepath): + try: + with open(filepath, encoding='utf8') as f: + return f.read() + except UnicodeDecodeError: + print(f'Unable to read license file: {filepath}') + pass + + def create_license_file(self, licenses, filepath='NOTICES.txt'): + """Creates file with all the provided license file contents. + + :param licenses: Dict with package paths and their corresponding license file contents + :param filepath: Path to write the file + """ + package_separator = '------------------------------------' + with open(filepath, 'w', encoding='utf8') as f: + for directory, license in licenses.items(): + license_output = '\n\n'.join([ + f'{package_separator}', + f'Package path: {directory}', + 'License:', + f'{license}\n' + ]) + f.write(license_output) + return None + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Script to run LicenseScanner and generate license file') + parser.add_argument('--config-file', '-c', type=pathlib.Path, help='Config file for LicenseScanner') + parser.add_argument('--license-file-path', '-l', type=pathlib.Path, help='Create license file in the provided path') + parser.add_argument('--scan-path', '-s', default=os.curdir, type=pathlib.Path, help='Path to scan') + return parser.parse_args() + + +def main(): + try: + args = parse_args() + ls = LicenseScanner(args.config_file) + licenses = ls.scan(args.scan_path) + + if args.license_file_path: + ls.create_license_file(licenses, args.license_file_path) + except FileNotFoundError as e: + print(f'Type: {type(e).__name__}, Error: {e}') + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/license_scanner/scanner_config.json b/scripts/license_scanner/scanner_config.json new file mode 100644 index 0000000000..b5863a7d31 --- /dev/null +++ b/scripts/license_scanner/scanner_config.json @@ -0,0 +1,12 @@ +{ + "excluded_directories": [ + ".git", + ".venv", + "build", + "license_scanner" + ], + "license_patterns": [ + "LICENSE*", + "COPYING*" + ] +} From afb57c9cf679592a209dbccdd5f38126e03d6b59 Mon Sep 17 00:00:00 2001 From: Scott Romero <24445312+AMZN-ScottR@users.noreply.github.com> Date: Mon, 19 Jul 2021 18:17:55 -0700 Subject: [PATCH 007/205] [stabliziation/2106] update 3rd party license file name to be pulled into the installer package (#2281) License file name was changed in #2267 Signed-off-by: AMZN-ScottR 24445312+AMZN-ScottR@users.noreply.github.com --- cmake/Packaging.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index a07e1ec1d3..2240ff472c 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -128,7 +128,7 @@ install(FILES ${_cmake_package_dest} # the version string and git tags are intended to be synchronized so it should be safe to use that instead # of directly calling into git which could get messy in certain scenarios if(${CPACK_PACKAGE_VERSION} VERSION_GREATER "0.0.0.0") - set(_3rd_party_license_filename SPDX-Licenses.txt) + set(_3rd_party_license_filename NOTICES.txt) set(_3rd_party_license_url "https://raw.githubusercontent.com/o3de/3p-package-source/${CPACK_PACKAGE_VERSION}/${_3rd_party_license_filename}") set(_3rd_party_license_dest ${CPACK_BINARY_DIR}/${_3rd_party_license_filename}) From abce54b3cd0a574fff1a8612be838779ab597a73 Mon Sep 17 00:00:00 2001 From: Axel Nana Date: Tue, 20 Jul 2021 01:05:09 +0100 Subject: [PATCH 008/205] Add missing `*.hxx` pattern Signed-off-by: Axel Nana --- cmake/Platform/Common/Install_common.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 5b476667e2..0a84d3ceb2 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -64,6 +64,7 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar PATTERN *.h PATTERN *.hpp PATTERN *.inl + PATTERN *.hxx ) endif() endforeach() From b58286d9b1022c3e3051c3225b7000935066fd4c Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 20 Jul 2021 20:40:04 -0500 Subject: [PATCH 009/205] Fixed RootAssetBrowserEntry setting of child AssetBrowserEntries The issue is due to RootAssetBrowserEntry::UpdateChildPaths not taking the RootAssetBrowserEntry fullpath into account when appending the child path entry Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- .../AssetBrowser/Entries/RootAssetBrowserEntry.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp index 0e132d2581..eec9970ca3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.cpp @@ -399,7 +399,7 @@ namespace AzToolsFramework void RootAssetBrowserEntry::UpdateChildPaths(AssetBrowserEntry* child) const { child->m_relativePath = child->m_name; - child->m_fullPath = child->m_name; + child->m_fullPath = m_fullPath / child->m_name; AssetBrowserEntry::UpdateChildPaths(child); } From 3050a4db479fb2dacf59942f7b0b42d7d82fcdcd Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Wed, 21 Jul 2021 10:18:18 -0500 Subject: [PATCH 010/205] Removing obsolete Vegetation Debugger test Signed-off-by: jckand-amzn --- .../EditorScripts/Debugger_DebugCVarsWorks.py | 55 ------------------ .../largeworlds/dyn_veg/test_Debugger.py | 56 ------------------- 2 files changed, 111 deletions(-) delete mode 100755 AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py delete mode 100755 AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py deleted file mode 100755 index 40fd67d957..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py +++ /dev/null @@ -1,55 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import sys - -import azlmbr.legacy.general as general -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper - - -class TestDebuggerDebugCVarsWorks(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="Debugger_DebugCVarsWorks", args=["level"]) - - def run_test(self): - """ - Summary: - C2789148 Vegetation Debug CVars are enabled when the Debugger component is present - - Expected Result: - The following commands are available in the Editor only when the Vegetation Debugger Level component is present: - veg_debugDumpReport (Command) - veg_debugRefreshAllAreas (Command) - - :return: None - """ - - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - # Initially run the command in console without Debugger component - general.run_console("veg_debugDumpReport") - - # Add the Vegetation Debugger component to the Level Inspector - hydra.add_level_component("Vegetation Debugger") - - # Run a command again after adding the Vegetation debugger - general.run_console("veg_debugRefreshAllAreas") - - -test = TestDebuggerDebugCVarsWorks() -test.run() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py deleted file mode 100755 index ed979136e0..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import logging - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.file_system as file_system -import editor_python_test_tools.hydra_test_utils as hydra - -logger = logging.getLogger(__name__) -test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts") - - -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["tmp_level"]) -@pytest.mark.usefixtures("automatic_process_killer") -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -class TestDebugger(object): - @pytest.fixture(autouse=True) - def setup_teardown(self, request, workspace, project, level): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - def teardown(): - # Cleanup our temp level - file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True) - - request.addfinalizer(teardown) - - @pytest.mark.test_case_id("C2789148") - @pytest.mark.SUITE_periodic - @pytest.mark.dynveg_misc - def test_Debugger_DebugCVarsWork(self, request, editor, level, workspace, launcher_platform): - cfg_args = [level] - - expected_lines = [ - "Debugger_DebugCVarsWorks: test started", - "[Warning] Unknown command: veg_debugDumpReport", - "[CONSOLE] Executing console command 'veg_debugRefreshAllAreas'", - "Debugger_DebugCVarsWorks: result=SUCCESS", - ] - - hydra.launch_and_validate_results( - request, - test_directory, - editor, - "Debugger_DebugCVarsWorks.py", - expected_lines=expected_lines, - cfg_args=cfg_args - ) From 7ebdde0be01477ba036bad7f5a1e36ae50e2d879 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Wed, 21 Jul 2021 10:25:48 -0500 Subject: [PATCH 011/205] Adding xfail mark to test_LandscapeCanvas_GraphClosed_OnEntityDelete Signed-off-by: jckand-amzn --- .../landscape_canvas/test_GeneralGraphFunctionality.py | 1 + 1 file changed, 1 insertion(+) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py index bbca71461c..e2aa222c3f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py @@ -104,6 +104,7 @@ class TestGeneralGraphFunctionality(object): @pytest.mark.test_case_id("C17488412") @pytest.mark.SUITE_periodic + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2201") def test_LandscapeCanvas_GraphClosed_OnEntityDelete(self, request, editor, level, launcher_platform): cfg_args = [level] From fc1ccb9e8574a1d997bbc791fb46a6a1325ee3a2 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 21 Jul 2021 17:17:09 -0700 Subject: [PATCH 012/205] Issues/2126 PhysX Gem can't be used as build dependency in engine SDK Part (#2337) * Applying GENEX_EVAL to 2 cases where the genex can produce another genex Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * Missing case when the folder is an external one to the engine/project (e.g. external gems) Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/LauncherUnified/launcher_generator.cmake | 4 ++-- cmake/LYWrappers.cmake | 15 ++++++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Code/LauncherUnified/launcher_generator.cmake b/Code/LauncherUnified/launcher_generator.cmake index 628b5fffac..28fddad1eb 100644 --- a/Code/LauncherUnified/launcher_generator.cmake +++ b/Code/LauncherUnified/launcher_generator.cmake @@ -40,9 +40,9 @@ foreach(project_name project_path IN ZIP_LISTS LY_PROJECTS_TARGET_NAME LY_PROJEC add_custom_target(${project_name}.Assets COMMENT "Processing ${project_name} assets..." COMMAND "${CMAKE_COMMAND}" - -DLY_LOCK_FILE=$/project_assets.lock + -DLY_LOCK_FILE=$>/project_assets.lock -P ${LY_ROOT_FOLDER}/cmake/CommandExecution.cmake - EXEC_COMMAND $ + EXEC_COMMAND $> --zeroAnalysisMode --project-path=${project_real_path} --platforms=${LY_ASSET_DEPLOY_ASSET_TYPE} diff --git a/cmake/LYWrappers.cmake b/cmake/LYWrappers.cmake index 40bf6ef541..cfe6df5c81 100644 --- a/cmake/LYWrappers.cmake +++ b/cmake/LYWrappers.cmake @@ -391,10 +391,10 @@ function(ly_delayed_target_link_libraries) endif() if(item_type STREQUAL MODULE_LIBRARY) - target_include_directories(${target} ${visibility} $) - target_link_libraries(${target} ${visibility} $) - target_compile_definitions(${target} ${visibility} $) - target_compile_options(${target} ${visibility} $) + target_include_directories(${target} ${visibility} $>) + target_link_libraries(${target} ${visibility} $>) + target_compile_definitions(${target} ${visibility} $>) + target_compile_options(${target} ${visibility} $>) else() ly_parse_third_party_dependencies(${item}) target_link_libraries(${target} ${visibility} ${item}) @@ -659,7 +659,12 @@ function(ly_get_vs_folder_directory absolute_target_source_dir output_source_dir if(is_target_prefix_of_engine_root) cmake_path(RELATIVE_PATH absolute_target_source_dir BASE_DIRECTORY ${LY_ROOT_FOLDER} OUTPUT_VARIABLE relative_target_source_dir) else() - cmake_path(GET absolute_target_source_dir RELATIVE_PART relative_target_source_dir) + cmake_path(IS_PREFIX CMAKE_SOURCE_DIR ${absolute_target_source_dir} is_target_prefix_of_source_dir) + if(is_target_prefix_of_source_dir) + cmake_path(RELATIVE_PATH absolute_target_source_dir BASE_DIRECTORY ${CMAKE_SOURCE_DIR} OUTPUT_VARIABLE relative_target_source_dir) + else() + cmake_path(GET absolute_target_source_dir RELATIVE_PART relative_target_source_dir) + endif() endif() set(${output_source_dir} ${relative_target_source_dir} PARENT_SCOPE) From 9358428bebd7d3b0166af8cf447d58d7caf37f72 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Sun, 25 Jul 2021 22:39:22 -0700 Subject: [PATCH 013/205] Added object release queue notification to the RHI Device and ObjectCollector. Signed-off-by: dmcdiar --- Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h | 4 ++ .../Code/Include/Atom/RHI/ObjectCollector.h | 60 +++++++++++++++++++ Gems/Atom/RHI/Code/Tests/Device.h | 2 + Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp | 5 ++ Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h | 1 + .../Atom/RHI/Metal/Code/Source/RHI/Device.cpp | 7 ++- Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h | 3 +- Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp | 5 ++ Gems/Atom/RHI/Null/Code/Source/RHI/Device.h | 1 + .../RHI/Vulkan/Code/Source/RHI/Device.cpp | 5 ++ Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h | 1 + Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h | 1 + 12 files changed, 93 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h index 3f79392403..4232658980 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h @@ -8,6 +8,7 @@ #pragma once +#include #include #include #include @@ -140,6 +141,9 @@ namespace AZ //! Get the memory requirements for allocating a buffer resource. virtual ResourceMemoryRequirements GetResourceMemoryRequirements(const BufferDescriptor& descriptor) = 0; + //! Notifies after all objects currently in the platform release queue are released + virtual void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) = 0; + protected: DeviceFeatures m_features; DeviceLimits m_limits; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h index cb66225286..d79a86afea 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h @@ -34,6 +34,8 @@ namespace AZ using MutexType = NullMutex; }; + using ObjectCollectorNotifyFunction = AZStd::function; + /** * Deferred-releases reference-counted objects at a specific latency. Example: Use to batch-release * objects that exist on the GPU timeline at the end of the frame after syncing the oldest GPU frame. @@ -85,6 +87,9 @@ namespace AZ /// Must not be called at collection time. size_t GetObjectCount() const; + /// Notifies after the current set of pending objects is released. + void Notify(ObjectCollectorNotifyFunction notifyFunction); + private: void QueueForCollectInternal(ObjectPtrType object); @@ -92,6 +97,7 @@ namespace AZ { AZStd::vector m_objects; uint64_t m_collectIteration; + AZStd::vector m_notifies; }; inline bool IsGarbageReady(size_t collectIteration) @@ -106,6 +112,7 @@ namespace AZ mutable typename Traits::MutexType m_mutex; AZStd::vector m_pendingObjects; AZStd::vector m_pendingGarbage; + AZStd::vector m_pendingNotifies; }; template @@ -174,6 +181,45 @@ namespace AZ } m_mutex.unlock(); + if (m_pendingNotifies.size()) + { + if (m_pendingGarbage.size()) + { + // find the newest garbage entry and add any pending notifies + Garbage& latestGarbage = m_pendingGarbage.front(); + size_t latestGarbageAge = m_currentIteration - latestGarbage.m_collectIteration; + size_t i = 1; + while (i < m_pendingGarbage.size()) + { + size_t age = m_currentIteration - m_pendingGarbage[i].m_collectIteration; + if (age < latestGarbageAge) + { + latestGarbage = m_pendingGarbage[i]; + latestGarbageAge = age; + } + } + + latestGarbage.m_notifies.insert(latestGarbage.m_notifies.end(), m_pendingNotifies.begin(), m_pendingNotifies.end()); + + m_mutex.lock(); + m_pendingNotifies.clear(); + m_mutex.unlock(); + + } + else + { + // garbage queue is empty, notify now + m_mutex.lock(); + for (auto& notifyFunction : m_pendingNotifies) + { + notifyFunction(); + } + + m_pendingNotifies.clear(); + m_mutex.unlock(); + } + } + size_t objectCount = 0; size_t i = 0; while (i < m_pendingGarbage.size()) @@ -189,6 +235,12 @@ namespace AZ } } objectCount += garbage.m_objects.size(); + + for (auto& notifyFunction : garbage.m_notifies) + { + notifyFunction(); + } + garbage = AZStd::move(m_pendingGarbage.back()); m_pendingGarbage.pop_back(); } @@ -215,5 +267,13 @@ namespace AZ return objectCount; } + + template + void ObjectCollector::Notify(ObjectCollectorNotifyFunction notifyFunction) + { + m_mutex.lock(); + m_pendingNotifies.push_back(notifyFunction); + m_mutex.unlock(); + } } } diff --git a/Gems/Atom/RHI/Code/Tests/Device.h b/Gems/Atom/RHI/Code/Tests/Device.h index 3a7c513c8b..e11bd75983 100644 --- a/Gems/Atom/RHI/Code/Tests/Device.h +++ b/Gems/Atom/RHI/Code/Tests/Device.h @@ -60,6 +60,8 @@ namespace UnitTest AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::ImageDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::BufferDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; + + void ObjectCollectionNotify(AZ::RHI::ObjectCollectorNotifyFunction notifyFunction) override {} }; AZ::RHI::Ptr MakeTestDevice(); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp index 88c9098952..9d23dfa43d 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp @@ -292,6 +292,11 @@ namespace AZ return memoryRequirements; } + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + //AZStd::vector Device::GetValidSwapChainImageFormats(const RHI::WindowHandle& windowHandle) const //{ // AZStd::vector formatsList; diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h index 149508307a..9119545342 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h @@ -162,6 +162,7 @@ namespace AZ void PreShutdown() override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor & descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor & descriptor) override; + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// RHI::ResultCode InitSubPlatform(RHI::PhysicalDevice& physicalDevice); diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp index f0771d7c45..dbd2204e93 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp @@ -315,7 +315,12 @@ namespace AZ memoryRequirements.m_sizeInBytes = bufferSizeAndAlign.size; return memoryRequirements; } - + + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + void Device::InitFeatures() { diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h index d8c3092c59..9cdeee7eae 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h @@ -151,7 +151,8 @@ namespace AZ NullDescriptorManager& GetNullDescriptorManager(); RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor & descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor & descriptor) override; - + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; + private: Device() = default; diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp index 7b94efb69f..08a2c4f411 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp @@ -20,5 +20,10 @@ namespace AZ { formatsCapabilities.fill(static_cast(~0)); } + + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + notifyFunction(); + } } } diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h index 3aa045212b..cd44135e62 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h @@ -42,6 +42,7 @@ namespace AZ void PreShutdown() override {} RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const RHI::ImageDescriptor& descriptor) override { return RHI::ResourceMemoryRequirements();} RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const RHI::BufferDescriptor& descriptor) override { return RHI::ResourceMemoryRequirements();} + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// }; } diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp index 6d3080dce8..05ff8bb2a6 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp @@ -652,6 +652,11 @@ namespace AZ return RHI::ResourceMemoryRequirements{ vkRequirements.alignment, vkRequirements.size }; } + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + void Device::InitFeaturesAndLimits(const PhysicalDevice& physicalDevice) { m_features.m_tessellationShader = (m_enabledDeviceFeatures.tessellationShader == VK_TRUE); diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h index d5f055f4cd..28e56d1fa9 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h @@ -134,6 +134,7 @@ namespace AZ void PreShutdown() override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor& descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor& descriptor) override; + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// void InitFeaturesAndLimits(const PhysicalDevice& physicalDevice); diff --git a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h index 1de06802b1..be362c60d6 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h +++ b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h @@ -70,6 +70,7 @@ namespace UnitTest void PreShutdown() override {} AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::ImageDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::BufferDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; + void ObjectCollectionNotify(AZ::RHI::ObjectCollectorNotifyFunction notifyFunction) override {} }; class ImageView From 26c9853ff9916b7216a5e01eef6b9f7be8bb4df1 Mon Sep 17 00:00:00 2001 From: moraaar Date: Tue, 27 Jul 2021 09:11:28 +0100 Subject: [PATCH 014/205] Fixed cloth tangent generation (#2440) - The output vectors were not properly filled with zeros when they already had the expected size. - The tolerance was too large and was causing patches while computing tangents and bitangents. - The handedness was inverted to what is expected in the shader (which always inverts tangent's w). Signed-off-by: moraaar --- .../ClothComponentMesh/ClothComponentMesh.cpp | 2 +- .../Code/Source/System/TangentSpaceHelper.cpp | 20 ++++++++++++------- .../ClothConstraintsTest.cpp | 12 ++++++++--- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp index b791e8a543..7e0ac2f230 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp @@ -577,7 +577,7 @@ namespace NvCloth const AZ::Vector3& renderTangent = renderTangents[renderVertexIndex]; destTangentsBuffer[index].Set( renderTangent, - 1.0f); + -1.0f); // Shader function ConstructTBN inverts w to change bitangent sign, but the bitangents passed are already corrected, so passing -1.0 to counteract. } if (destBitangentsBuffer) diff --git a/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp b/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp index b43ad1923b..e388643c00 100644 --- a/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp +++ b/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp @@ -11,7 +11,7 @@ namespace NvCloth { namespace { - const float Tolerance = 0.0001f; + const float Tolerance = 1e-7f; } bool TangentSpaceHelper::CalculateNormals( @@ -33,7 +33,8 @@ namespace NvCloth const size_t vertexCount = vertices.size(); // Reset results - outNormals.resize(vertexCount, AZ::Vector3::CreateZero()); + outNormals.resize(vertexCount); + AZStd::fill(outNormals.begin(), outNormals.end(), AZ::Vector3::CreateZero()); // calculate the normals per triangle for (size_t i = 0; i < triangleCount; ++i) @@ -114,8 +115,10 @@ namespace NvCloth const size_t vertexCount = vertices.size(); // Reset results - outTangents.resize(vertexCount, AZ::Vector3::CreateZero()); - outBitangents.resize(vertexCount, AZ::Vector3::CreateZero()); + outTangents.resize(vertexCount); + outBitangents.resize(vertexCount); + AZStd::fill(outTangents.begin(), outTangents.end(), AZ::Vector3::CreateZero()); + AZStd::fill(outBitangents.begin(), outBitangents.end(), AZ::Vector3::CreateZero()); // calculate the base vectors per triangle for (size_t i = 0; i < triangleCount; ++i) @@ -192,9 +195,12 @@ namespace NvCloth const size_t vertexCount = vertices.size(); // Reset results - outTangents.resize(vertexCount, AZ::Vector3::CreateZero()); - outBitangents.resize(vertexCount, AZ::Vector3::CreateZero()); - outNormals.resize(vertexCount, AZ::Vector3::CreateZero()); + outTangents.resize(vertexCount); + outBitangents.resize(vertexCount); + outNormals.resize(vertexCount); + AZStd::fill(outTangents.begin(), outTangents.end(), AZ::Vector3::CreateZero()); + AZStd::fill(outBitangents.begin(), outBitangents.end(), AZ::Vector3::CreateZero()); + AZStd::fill(outNormals.begin(), outNormals.end(), AZ::Vector3::CreateZero()); // calculate the base vectors per triangle for (size_t i = 0; i < triangleCount; ++i) diff --git a/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ClothConstraintsTest.cpp b/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ClothConstraintsTest.cpp index 5f390ed45d..50ca5c17cd 100644 --- a/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ClothConstraintsTest.cpp +++ b/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ClothConstraintsTest.cpp @@ -124,6 +124,9 @@ namespace UnitTest const AZStd::vector& motionConstraints = clothConstraints->GetMotionConstraints(); EXPECT_TRUE(motionConstraints.size() == SimulationParticles.size()); + EXPECT_THAT(motionConstraints[0].GetAsVector3(), IsCloseTolerance(SimulationParticles[0].GetAsVector3(), Tolerance)); + EXPECT_THAT(motionConstraints[1].GetAsVector3(), IsCloseTolerance(SimulationParticles[1].GetAsVector3(), Tolerance)); + EXPECT_THAT(motionConstraints[2].GetAsVector3(), IsCloseTolerance(SimulationParticles[2].GetAsVector3(), Tolerance)); EXPECT_NEAR(motionConstraints[0].GetW(), 6.0f, Tolerance); EXPECT_NEAR(motionConstraints[1].GetW(), 0.0f, Tolerance); EXPECT_NEAR(motionConstraints[2].GetW(), 0.0f, Tolerance); @@ -277,6 +280,9 @@ namespace UnitTest const AZStd::vector& separationConstraints = clothConstraints->GetSeparationConstraints(); EXPECT_TRUE(motionConstraints.size() == newParticles.size()); + EXPECT_THAT(motionConstraints[0].GetAsVector3(), IsCloseTolerance(newParticles[0].GetAsVector3(), Tolerance)); + EXPECT_THAT(motionConstraints[1].GetAsVector3(), IsCloseTolerance(newParticles[1].GetAsVector3(), Tolerance)); + EXPECT_THAT(motionConstraints[2].GetAsVector3(), IsCloseTolerance(newParticles[2].GetAsVector3(), Tolerance)); EXPECT_NEAR(motionConstraints[0].GetW(), 3.0f, Tolerance); EXPECT_NEAR(motionConstraints[1].GetW(), 1.5f, Tolerance); EXPECT_NEAR(motionConstraints[2].GetW(), 0.0f, Tolerance); @@ -285,8 +291,8 @@ namespace UnitTest EXPECT_NEAR(separationConstraints[0].GetW(), 3.0f, Tolerance); EXPECT_NEAR(separationConstraints[1].GetW(), 1.5f, Tolerance); EXPECT_NEAR(separationConstraints[2].GetW(), 0.3f, Tolerance); - EXPECT_THAT(separationConstraints[0].GetAsVector3(), IsCloseTolerance(AZ::Vector3(-3.03902f, 2.80752f, 3.80752f), Tolerance)); - EXPECT_THAT(separationConstraints[1].GetAsVector3(), IsCloseTolerance(AZ::Vector3(-1.41659f, 0.651243f, -0.348757f), Tolerance)); - EXPECT_THAT(separationConstraints[2].GetAsVector3(), IsCloseTolerance(AZ::Vector3(6.15313f, -0.876132f, 0.123868f), Tolerance)); + EXPECT_THAT(separationConstraints[0].GetAsVector3(), IsCloseTolerance(AZ::Vector3(0.0f, 3.53553f, 4.53553f), Tolerance)); + EXPECT_THAT(separationConstraints[1].GetAsVector3(), IsCloseTolerance(AZ::Vector3(0.0f, 2.06066f, 1.06066f), Tolerance)); + EXPECT_THAT(separationConstraints[2].GetAsVector3(), IsCloseTolerance(AZ::Vector3(1.0f, -3.74767f, -2.74767f), Tolerance)); } } // namespace UnitTest From 9c72510a4fb6dc10cba848752b1e788a19830d0f Mon Sep 17 00:00:00 2001 From: pappeste Date: Wed, 23 Jun 2021 14:52:30 -0700 Subject: [PATCH 015/205] removing files that got added by rebase MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> (+1 squashed commits) Squashed commits: [a19269426] fixing more strings Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> (+1 squashed commits) Squashed commits: [d2a049324] fixing more strings Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> (+1 squashed commits) Squashed commits: [a1ff4c101] trying to build Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/CryEdit.cpp | 3 - Code/Editor/Export/ExportManager.cpp | 4 +- .../Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp | 2 - Code/Editor/Util/PathUtil.h | 6 +- Code/Editor/Util/StringHelpers.cpp | 120 - Code/Editor/Util/StringHelpers.h | 15 - Code/LauncherUnified/Launcher.h | 3 - Code/Legacy/CryCommon/CryArray.h | 13 +- Code/Legacy/CryCommon/CryCustomTypes.h | 46 +- Code/Legacy/CryCommon/CryFile.h | 11 +- Code/Legacy/CryCommon/CryFixedString.h | 2337 --------------- Code/Legacy/CryCommon/CryListenerSet.h | 2 +- Code/Legacy/CryCommon/CryName.h | 16 +- Code/Legacy/CryCommon/CryPath.h | 139 +- Code/Legacy/CryCommon/CrySizer.h | 6 +- Code/Legacy/CryCommon/CryString.h | 2523 ----------------- Code/Legacy/CryCommon/CryThread_windows.h | 2 +- Code/Legacy/CryCommon/CryTypeInfo.cpp | 81 +- Code/Legacy/CryCommon/CryTypeInfo.h | 9 +- Code/Legacy/CryCommon/IEntityRenderState.h | 2 +- Code/Legacy/CryCommon/IFont.h | 7 +- Code/Legacy/CryCommon/IRenderer.h | 3 +- Code/Legacy/CryCommon/ISerialize.h | 120 +- Code/Legacy/CryCommon/IShader.h | 37 +- Code/Legacy/CryCommon/ISystem.h | 2 +- Code/Legacy/CryCommon/IXml.h | 4 +- Code/Legacy/CryCommon/Linux_Win32Wrapper.h | 3 - Code/Legacy/CryCommon/LyShine/UiBase.h | 1 - .../CryCommon/LyShine/UiSerializeHelpers.h | 148 - Code/Legacy/CryCommon/StlUtils.h | 2 +- Code/Legacy/CryCommon/StringUtils.h | 1358 --------- Code/Legacy/CryCommon/TypeInfo_decl.h | 5 +- Code/Legacy/CryCommon/UnicodeBinding.h | 58 +- Code/Legacy/CryCommon/WinBase.cpp | 2 +- Code/Legacy/CryCommon/crycommon_files.cmake | 3 - Code/Legacy/CryCommon/platform.h | 9 - Code/Legacy/CryCommon/platform_impl.cpp | 6 +- Code/Legacy/CrySystem/CmdLine.cpp | 20 +- Code/Legacy/CrySystem/DebugCallStack.cpp | 22 +- .../CrySystem/LevelSystem/LevelSystem.cpp | 2 +- .../CrySystem/LocalizedStringManager.cpp | 18 +- Code/Legacy/CrySystem/Log.cpp | 6 +- Code/Legacy/CrySystem/Log.h | 2 +- Code/Legacy/CrySystem/System.cpp | 2 +- Code/Legacy/CrySystem/SystemWin32.cpp | 12 +- Code/Legacy/CrySystem/XConsole.cpp | 2 +- Code/Legacy/CrySystem/XConsole.h | 42 +- .../CrySystem/XML/SerializeXMLReader.cpp | 4 +- .../Legacy/CrySystem/XML/SerializeXMLReader.h | 8 +- Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp | 2 +- Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp | 16 +- Code/Legacy/CrySystem/XML/XMLPatcher.cpp | 6 +- Code/Legacy/CrySystem/XML/XMLPatcher.h | 2 +- Code/Legacy/CrySystem/XML/xml.cpp | 8 +- .../AtomLyIntegration/AtomFont/FFont.h | 1 - .../Platform/Windows/FFontXML_Windows.cpp | 2 +- .../Components/BlastSystemComponent.cpp | 2 - Gems/LmbrCentral/Code/Source/LmbrCentral.cpp | 8 +- .../Code/Editor/Animation/UiAnimViewNodes.cpp | 2 +- .../Code/Editor/PropertyHandlerChar.cpp | 3 +- .../Code/Source/LyShineSystemComponent.h | 4 +- .../Platform/Windows/UiClipboard_Windows.cpp | 5 +- Gems/LyShine/Code/Source/StringUtfUtils.h | 3 +- .../LyShine/Code/Source/UiButtonComponent.cpp | 41 +- Gems/LyShine/Code/Source/UiImageComponent.cpp | 13 +- Gems/LyShine/Code/Source/UiSerialize.cpp | 64 - Gems/LyShine/Code/Source/UiTextComponent.cpp | 22 +- .../Code/Source/UiTextInputComponent.cpp | 51 +- Gems/LyShine/Code/Tests/SerializationTest.cpp | 1 - Gems/LyShine/Code/Tests/SpriteTest.cpp | 1 - .../Code/Source/Cinematics/CaptureTrack.cpp | 2 +- .../Code/Source/Cinematics/CommentTrack.cpp | 2 +- .../Code/Source/Cinematics/EventTrack.cpp | 2 +- .../Code/Source/Cinematics/SceneNode.cpp | 2 +- .../Source/Cinematics/TrackEventTrack.cpp | 2 +- .../Code/Source/MaestroSystemComponent.h | 4 +- Gems/Metastream/Code/Tests/MetastreamTest.cpp | 2 - .../Code/Source/SystemComponent.cpp | 2 - 78 files changed, 330 insertions(+), 7193 deletions(-) delete mode 100644 Code/Legacy/CryCommon/CryFixedString.h delete mode 100644 Code/Legacy/CryCommon/CryString.h delete mode 100644 Code/Legacy/CryCommon/StringUtils.h diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index 4bfc6a319d..973a818b92 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -4150,15 +4150,12 @@ struct CryAllocatorsRAII CryAllocatorsRAII() { AZ_Assert(!AZ::AllocatorInstance::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); - AZ_Assert(!AZ::AllocatorInstance::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); } ~CryAllocatorsRAII() { - AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); } }; diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp index 682dcf3980..03aa0bed8b 100644 --- a/Code/Editor/Export/ExportManager.cpp +++ b/Code/Editor/Export/ExportManager.cpp @@ -88,7 +88,7 @@ Export::CObject::CObject(const char* pName) nParent = -1; - cry_strcpy(name, pName); + azstrcpy(name, pName); materialName[0] = '\0'; @@ -102,7 +102,7 @@ Export::CObject::CObject(const char* pName) void Export::CObject::SetMaterialName(const char* pName) { - cry_strcpy(materialName, pName); + azstrcpy(materialName, pName); } diff --git a/Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp b/Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp index dd2a1d602a..630ab3eb8e 100644 --- a/Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp +++ b/Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin.cpp @@ -8,8 +8,6 @@ #include "FFMPEGPlugin.h" -#include "CryString.h" -typedef CryStringT string; #include "Include/ICommandManager.h" #include "Util/PathUtil.h" diff --git a/Code/Editor/Util/PathUtil.h b/Code/Editor/Util/PathUtil.h index 0f87df0d5c..98f484ec94 100644 --- a/Code/Editor/Util/PathUtil.h +++ b/Code/Editor/Util/PathUtil.h @@ -230,7 +230,7 @@ namespace Path } template - inline bool EndsWithSlash(CryStackStringT* path) + inline bool EndsWithSlash(AZStd::fixed_string* path) { if ((!path) || (path->empty())) { @@ -271,7 +271,7 @@ namespace Path } template - inline void AddBackslash(CryStackStringT* path) + inline void AddBackslash(AZstd::fixed_string* path) { if (path->empty()) { @@ -284,7 +284,7 @@ namespace Path } template - inline void AddSlash(CryStackStringT* path) + inline void AddSlash(AZstd::fixed_string* path) { if (path->empty()) { diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp index 836090e923..a6bf622ad0 100644 --- a/Code/Editor/Util/StringHelpers.cpp +++ b/Code/Editor/Util/StringHelpers.cpp @@ -380,126 +380,6 @@ bool StringHelpers::ContainsIgnoreCase(const wstring& str, const wstring& patter return false; } -bool StringHelpers::MatchesWildcards(const string& str, const string& wildcards) -{ - using namespace CryStringUtils_Internal; - return MatchesWildcards_Tpl(str.c_str(), wildcards.c_str()); -} - -bool StringHelpers::MatchesWildcards(const wstring& str, const wstring& wildcards) -{ - using namespace CryStringUtils_Internal; - return MatchesWildcards_Tpl(str.c_str(), wildcards.c_str()); -} - -bool StringHelpers::MatchesWildcardsIgnoreCase(const string& str, const string& wildcards) -{ - using namespace CryStringUtils_Internal; - return MatchesWildcards_Tpl(str.c_str(), wildcards.c_str()); -} - -bool StringHelpers::MatchesWildcardsIgnoreCase(const wstring& str, const wstring& wildcards) -{ - using namespace CryStringUtils_Internal; - return MatchesWildcards_Tpl(str.c_str(), wildcards.c_str()); -} - - -template -static inline bool MatchesWildcardsIgnoreCaseExt_Tpl(const TS& str, const TS& wildcards, std::vector& wildcardMatches) -{ - const typename TS::value_type* savedStrBegin = 0; - const typename TS::value_type* savedStrEnd = 0; - const typename TS::value_type* savedWild = 0; - size_t savedWildCount = 0; - - const typename TS::value_type* pStr = str.c_str(); - const typename TS::value_type* pWild = wildcards.c_str(); - size_t wildCount = 0; - - while ((*pStr) && (*pWild != '*')) - { - if (*pWild == '?') - { - wildcardMatches.push_back(TS(pStr, pStr + 1)); - ++wildCount; - } - else if (ToLower(*pWild) != ToLower(*pStr)) - { - wildcardMatches.resize(wildcardMatches.size() - wildCount); - return false; - } - ++pWild; - ++pStr; - } - - while (*pStr) - { - if (*pWild == '*') - { - if (!pWild[1]) - { - wildcardMatches.push_back(TS(pStr)); - return true; - } - savedWild = pWild++; - savedStrBegin = pStr; - savedStrEnd = pStr; - savedWildCount = wildCount; - wildcardMatches.push_back(TS(savedStrBegin, savedStrEnd)); - ++wildCount; - } - else if (*pWild == '?') - { - wildcardMatches.push_back(TS(pStr, pStr + 1)); - ++wildCount; - ++pWild; - ++pStr; - } - else if (ToLower(*pWild) == ToLower(*pStr)) - { - ++pWild; - ++pStr; - } - else - { - wildcardMatches.resize(wildcardMatches.size() - (wildCount - savedWildCount)); - wildCount = savedWildCount; - ++savedStrEnd; - pWild = savedWild + 1; - pStr = savedStrEnd; - wildcardMatches.push_back(TS(savedStrBegin, savedStrEnd)); - ++wildCount; - } - } - - while (*pWild == '*') - { - ++pWild; - wildcardMatches.push_back(TS()); - ++wildCount; - } - - if (*pWild) - { - wildcardMatches.resize(wildcardMatches.size() - wildCount); - return false; - } - - return true; -} - -bool StringHelpers::MatchesWildcardsIgnoreCaseExt(const string& str, const string& wildcards, std::vector& wildcardMatches) -{ - return MatchesWildcardsIgnoreCaseExt_Tpl(str, wildcards, wildcardMatches); -} - -bool StringHelpers::MatchesWildcardsIgnoreCaseExt(const wstring& str, const wstring& wildcards, std::vector& wildcardMatches) -{ - return MatchesWildcardsIgnoreCaseExt_Tpl(str, wildcards, wildcardMatches); -} - - string StringHelpers::TrimLeft(const string& s) { const size_t first = s.find_first_not_of(" \r\t"); diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h index c05063f207..da4aa9c9cc 100644 --- a/Code/Editor/Util/StringHelpers.h +++ b/Code/Editor/Util/StringHelpers.h @@ -11,8 +11,6 @@ #define CRYINCLUDE_CRYCOMMONTOOLS_STRINGHELPERS_H #pragma once -#include - namespace StringHelpers { // compares two strings to see if they are the same or different, case sensitive @@ -65,19 +63,6 @@ namespace StringHelpers bool ContainsIgnoreCase(const string& str, const string& pattern); bool ContainsIgnoreCase(const wstring& str, const wstring& pattern); - // checks to see if a string contains a wildcard string pattern, case sensitive - // returns true if the string does match the wildcard string pattern or false if it does not - bool MatchesWildcards(const string& str, const string& wildcards); - bool MatchesWildcards(const wstring& str, const wstring& wildcards); - - // checks to see if a string contains a wildcard string pattern, case is ignored - // returns true if the string does match the wildcard string pattern or false if it does not - bool MatchesWildcardsIgnoreCase(const string& str, const string& wildcards); - bool MatchesWildcardsIgnoreCase(const wstring& str, const wstring& wildcards); - - bool MatchesWildcardsIgnoreCaseExt(const string& str, const string& wildcards, std::vector& wildcardMatches); - bool MatchesWildcardsIgnoreCaseExt(const wstring& str, const wstring& wildcards, std::vector& wildcardMatches); - string TrimLeft(const string& s); wstring TrimLeft(const wstring& s); diff --git a/Code/LauncherUnified/Launcher.h b/Code/LauncherUnified/Launcher.h index e0b3abdf95..5ff6009e43 100644 --- a/Code/LauncherUnified/Launcher.h +++ b/Code/LauncherUnified/Launcher.h @@ -21,15 +21,12 @@ namespace O3DELauncher CryAllocatorsRAII() { AZ_Assert(!AZ::AllocatorInstance::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); - AZ_Assert(!AZ::AllocatorInstance::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); } ~CryAllocatorsRAII() { - AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); } }; diff --git a/Code/Legacy/CryCommon/CryArray.h b/Code/Legacy/CryCommon/CryArray.h index 167f1cfb57..8b0cea3de6 100644 --- a/Code/Legacy/CryCommon/CryArray.h +++ b/Code/Legacy/CryCommon/CryArray.h @@ -12,6 +12,7 @@ #pragma once #include "CryLegacyAllocator.h" +#include //--------------------------------------------------------------------------- // Convenient iteration macros @@ -58,18 +59,6 @@ struct fake_move_helper } }; -// Override for string to ensure proper construction -template <> -struct fake_move_helper -{ - static void move(string& dest, string& source) - { - ::new((void*)&dest) string(); - dest = source; - source.~string(); - } -}; - // Generic move function: transfer an existing source object to uninitialized dest address. // Addresses must not overlap (requirement on caller). // May be specialized for specific types, to provide a more optimal move. diff --git a/Code/Legacy/CryCommon/CryCustomTypes.h b/Code/Legacy/CryCommon/CryCustomTypes.h index 9594f5a333..74f3cbc9dc 100644 --- a/Code/Legacy/CryCommon/CryCustomTypes.h +++ b/Code/Legacy/CryCommon/CryCustomTypes.h @@ -16,10 +16,10 @@ #pragma once #include "CryTypeInfo.h" -#include "CryFixedString.h" #include #include #include +#include #define STATIC_CONST(T, name, val) \ static inline T name() { static T t = val; return t; } @@ -46,7 +46,7 @@ inline bool HasString(const T& val, FToString flags, const void* def_data = 0) float NumToFromString(float val, int digits, bool floating, char buffer[], int buf_size); template -string NumToString(T val, int min_digits, int max_digits, bool floating) +AZStd::string NumToString(T val, int min_digits, int max_digits, bool floating) { char buffer[64]; float f(val); @@ -68,7 +68,7 @@ struct CStructInfo { CStructInfo(cstr name, size_t size, size_t align, Array vars = Array(), Array templates = Array()); virtual bool IsType(CTypeInfo const& Info) const; - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const; + virtual AZStd::string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const; virtual bool FromString(void* data, cstr str, FFromString flags = 0) const; virtual bool ToValue(const void* data, void* value, const CTypeInfo& typeVal) const; virtual bool FromValue(void* data, const void* value, const CTypeInfo& typeVal) const; @@ -86,9 +86,9 @@ struct CStructInfo } protected: - Array Vars; - CryStackStringT EndianDesc; // Encodes instructions for endian swapping. - bool HasBitfields; + Array Vars; + AZStd::fixed_string<16> EndianDesc; // Encodes instructions for endian swapping. + bool HasBitfields; Array TemplateTypes; void MakeEndianDesc(); @@ -124,11 +124,11 @@ struct TTypeInfo return false; } - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const + virtual AZStd::string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const { if (!HasString(*(const T*)data, flags, def_data)) { - return string(); + return AZStd::string(); } return ::ToString(*(const T*)data); } @@ -193,7 +193,7 @@ struct TProxyTypeInfo return false; } - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const + virtual AZStd::string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const { T val = T(*(const S*)data); T def_val = def_data ? T(*(const S*)def_data) : T(); @@ -234,32 +234,32 @@ protected: // Customisation for string. template<> -inline string TTypeInfo::ToString(const void* data, FToString flags, const void* def_data) const +inline AZStd::string TTypeInfo::ToString(const void* data, FToString flags, const void* def_data) const { - const string& val = *(const string*)data; + const AZStd::string& val = *(const AZStd::string*)data; if (def_data && flags.SkipDefault) { - if (val == *(const string*)def_data) + if (val == *(const AZStd::string*)def_data) { - return string(); + return AZStd::string(); } } return val; } template<> -inline bool TTypeInfo::FromString(void* data, cstr str, FFromString flags) const +inline bool TTypeInfo::FromString(void* data, cstr str, FFromString flags) const { if (!*str && flags.SkipEmpty) { return true; } - *(string*)data = str; + *(AZStd::string*)data = str; return true; } template<> -void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const; +void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const; //--------------------------------------------------------------------------- // @@ -632,11 +632,11 @@ protected: } // Override ToString: Limit to significant digits. - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const + virtual AZStd::string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const { if (!HasString(*(const S*)data, flags, def_data)) { - return string(); + return AZStd::string(); } static int digits = int_ceil(log10f(float(nQUANT))); return NumToString(*(const TFixed*)data, 1, digits + 3, true); @@ -907,12 +907,12 @@ struct TEnumInfo return false; } - virtual string ToString(const void* data, FToString flags, const void* def_data) const + virtual AZStd::string ToString(const void* data, FToString flags, const void* def_data) const { TInt val = *(const TInt*)(data); if (flags.SkipDefault && val == (def_data ? *(const TInt*)def_data : TInt(0))) { - return string(); + return AZStd::string(); } if (cstr sName = TEnumDef::ToName(val)) @@ -1153,13 +1153,13 @@ struct CEnumDefUuid return false; } - string ToString(const void* data, FToString flags, const void* def_data) const override + AZStd::string ToString(const void* data, FToString flags, const void* def_data) const override { const AZ::Uuid& uuidData = *reinterpret_cast(data); const AZ::Uuid& defUuidData = *reinterpret_cast(def_data); if (flags.SkipDefault && uuidData == (def_data ? defUuidData : AZ::Uuid::CreateNull())) { - return string(); + return AZStd::string(); } if (cstr sName = ToName(uuidData)) @@ -1167,7 +1167,7 @@ struct CEnumDefUuid return sName; } - return string(); + return AZStd::string(); } bool FromString(void* data, cstr str, FFromString flags) const override diff --git a/Code/Legacy/CryCommon/CryFile.h b/Code/Legacy/CryCommon/CryFile.h index a043e4fa9b..0888216f9c 100644 --- a/Code/Legacy/CryCommon/CryFile.h +++ b/Code/Legacy/CryCommon/CryFile.h @@ -18,7 +18,6 @@ #include #include #include -#include "StringUtils.h" #include ////////////////////////////////////////////////////////////////////////// @@ -222,7 +221,7 @@ inline CCryFile::~CCryFile() inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlagsEx) { char tempfilename[CRYFILE_MAX_PATH] = ""; - cry_strcpy(tempfilename, filename); + azstrcpy(tempfilename, filename); #if !defined (_RELEASE) if (gEnv && gEnv->IsEditor() && gEnv->pConsole) @@ -233,8 +232,8 @@ inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlag const int lowercasePaths = pCvar->GetIVal(); if (lowercasePaths) { - const string lowerString = PathUtil::ToLower(tempfilename); - cry_strcpy(tempfilename, lowerString.c_str()); + const AZStd::string lowerString = PathUtil::ToLower(tempfilename); + azstrcpy(tempfilename, lowerString.c_str()); } } } @@ -243,7 +242,7 @@ inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlag { Close(); } - cry_strcpy(m_filename, tempfilename); + azstrcpy(m_filename, tempfilename); if (m_pIArchive) { @@ -430,7 +429,7 @@ inline const char* CCryFile::GetAdjustedFilename() const // Returns standard path otherwise. if (gameUrl != &szAdjustedFile[0]) { - cry_strcpy(szAdjustedFile, gameUrl); + azstrcpy(szAdjustedFile, gameUrl); } return szAdjustedFile; } diff --git a/Code/Legacy/CryCommon/CryFixedString.h b/Code/Legacy/CryCommon/CryFixedString.h deleted file mode 100644 index 299a5718a7..0000000000 --- a/Code/Legacy/CryCommon/CryFixedString.h +++ /dev/null @@ -1,2337 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Stack-based fixed-size String class, similar to CryString. -// will switch to heap-based allocation when string does no longer fit -// Can easily be substituted instead of CryString. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H -#define CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include "CryString.h" - -#ifndef CRY_STRING_DEBUG -#define CRY_STRING_DEBUG(s) -#endif - -#define UNITTEST_CRYFIXEDSTRING (0) - -template -class CharTraits; - -// traits for char -template <> -class CharTraits -{ -public: - typedef size_t size_type; - typedef char value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - ILINE int _isspace(value_type c) const - { - return ::isspace((int)c); - } - - ILINE value_type _traits_toupper(value_type c) const - { - return static_cast(toupper(c)); - } - - ILINE value_type _traits_tolower(value_type c) const - { - return static_cast(tolower(c)); - } - - ILINE value_type _ascii_tolower(value_type c) const - { - return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; - } - - ILINE value_type _ascii_toupper(value_type c) const - { - return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; - } - - ILINE int _strcmp (const_str a, const_str b) const - { - return ::strcmp(a, b); - } - - ILINE int _strncmp (const_str a, const_str b, size_type n) const - { - return ::strncmp(a, b, n); - } - - ILINE int _stricmp (const_str a, const_str b) const - { - return ::azstricmp(a, b); - } - - ILINE int _strnicmp (const_str a, const_str b, size_type n) const - { - return ::azstrnicmp(a, b, n); - } - - ILINE size_type _strspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::strspn(str, strCharSet); - } - - ILINE size_type _strcspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::strcspn(str, strCharSet); - } - - static ILINE size_type _strlen(const_str str) - { - return (str == NULL) ? 0 : (size_type)::strlen(str); - } - - ILINE const_str _strchr(const_str str, value_type c) const - { - return (str == NULL) ? 0 : ::strchr(str, c); - } - - ILINE value_type* _strstr(value_type* str, const_str strSearch) const - { - return (str == NULL) ? 0 : (value_type*) ::strstr(str, strSearch); - } - - ILINE void _copy(value_type* dest, const value_type* src, size_type count) - { - memcpy(dest, src, count * sizeof(value_type)); - } - - ILINE void _move(value_type* dest, const value_type* src, size_type count) - { - memmove(dest, src, count * sizeof(value_type)); - } - - ILINE void _set(value_type* dest, value_type ch, size_type count) - { - memset(dest, ch, count * sizeof(value_type)); - } - - ILINE int _vsnprintf(value_type* str, size_type size, const_str format, va_list ap) - { - return ::azvsnprintf(str, size, format, ap); - } -}; - -// traits for wchar_t -template <> -class CharTraits -{ -public: - typedef size_t size_type; - typedef wchar_t value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - ILINE int _isspace(value_type c) const - { - return iswspace(c); - } - - ILINE value_type _traits_toupper(value_type c) const - { - return towupper(c); - } - - ILINE value_type _traits_tolower(value_type c) const - { - return towlower(c); - } - - ILINE value_type _ascii_tolower(value_type c) const - { - return ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)); - } - - ILINE value_type _ascii_toupper(value_type c) const - { - return ((((c) >= 'a') && ((c) <= 'z')) ? ((c) - 'a' + 'A') : (c)); - } - - ILINE int _strcmp (const_str a, const_str b) const - { - return wcscmp (a, b); - } - - ILINE int _strncmp (const_str a, const_str b, size_type n) const - { - return wcsncmp (a, b, n); - } - - ILINE int _stricmp (const_str a, const_str b) const - { - return azwcsicmp(a, b); - } - - ILINE int _strnicmp (const_str a, const_str b, size_type n) const - { - return azwcsnicmp(a, b, n); - } - - ILINE size_type _strspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::wcsspn(str, strCharSet); - } - - ILINE size_type _strcspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::wcscspn(str, strCharSet); - } - - static ILINE size_type _strlen(const_str str) - { - return (str == NULL) ? 0 : (size_type)::wcslen(str); - } - - ILINE const_str _strchr(const_str str, value_type c) const - { - return (str == NULL) ? 0 : ::wcschr(str, c); - } - - ILINE value_type* _strstr(value_type* str, const_str strSearch) const - { - return (str == NULL) ? 0 : ::wcsstr(str, strSearch); - } - - ILINE void _copy(value_type* dest, const value_type* src, size_type count) - { - memcpy(dest, src, count * sizeof(value_type)); - } - - ILINE void _move(value_type* dest, const value_type* src, size_type count) - { - memmove(dest, src, count * sizeof(value_type)); - } - - ILINE void _set(value_type* dest, value_type ch, size_type count) - { - wmemset(dest, ch, count); - } - - ILINE int _vsnprintf(value_type* str, size_type size, const_str format, va_list ap) - { - return ::_vsnwprintf_s(str, size + 1, size, format, ap); - } -}; - -template -class CryStackStringT - : public CharTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - // Types compatible with STL string. - ////////////////////////////////////////////////////////////////////////// - typedef CryStackStringT _Self; - typedef size_t size_type; - typedef T value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - - enum _npos_type - { - npos = (size_type) ~0 - }; - - ////////////////////////////////////////////////////////////////////////// - // Constructors - ////////////////////////////////////////////////////////////////////////// - CryStackStringT(); - -public: - - CryStackStringT(const _Self& str); - CryStackStringT(const _Self& str, size_type nOff, size_type nCount); - CryStackStringT(size_type nRepeat, value_type ch); - - // The reason of making this constructor unavailable (for a while) is - // explained in comments in front of the declaration of - // CryStringT::CryStringT(size_type nRepeat, value_type ch) - // (see CryString.h). -private: - CryStackStringT(value_type ch, size_type nRepeat); - -public: - - CryStackStringT(const_str str); - CryStackStringT(const CryStringT& str); - CryStackStringT(const_str str, size_type nLength); - CryStackStringT(const_iterator _First, const_iterator _Last); - ~CryStackStringT(); - - ////////////////////////////////////////////////////////////////////////// - // STL string like interface. - ////////////////////////////////////////////////////////////////////////// - //! Operators. - size_type length() const; - size_type size() const; - bool empty() const; - void clear(); // free up the data - - //! Returns the storage currently allocated to hold the string, a value at least as large as length(). - // Also: capacity is always >= (MAX_SIZE-1) - size_type capacity() const; - - // Sets the capacity of the string to a number at least as great as a specified number. - // nCount = 0 is shrinking string to fit number of characters in it. - // Shrink to fit post-cond: capacity() >= (MAX_SIZE-1) - void reserve(size_type nCount = 0); - - _Self& append(const value_type* _Ptr); - _Self& append(const value_type* _Ptr, size_type nCount); - _Self& append(const _Self& _Str, size_type nOff, size_type nCount); - _Self& append(const _Self& _Str); - _Self& append(size_type nCount, value_type _Ch); - _Self& append(const_iterator _First, const_iterator _Last); - - _Self& assign(const_str _Ptr); - _Self& assign(const_str _Ptr, size_type nCount); - _Self& assign(const _Self& _Str, size_type off, size_type nCount); - _Self& assign(const _Self& _Str); - _Self& assign(size_type nCount, value_type _Ch); - _Self& assign(const_iterator _First, const_iterator _Last); - - value_type at(size_type index) const; - //value_type& at( size_type index ); - - const_iterator begin() const { return m_str; }; - const_iterator end() const { return m_str + length(); }; - - iterator begin() { return m_str; }; - iterator end() { return m_str + length(); }; - - //! cast to C string operator. - operator const_str() const { - return m_str; - } - - //! cast to C string. - const value_type* c_str() const { return m_str; } - const value_type* data() const { return m_str; }; - - ////////////////////////////////////////////////////////////////////////// - // string comparison. - ////////////////////////////////////////////////////////////////////////// - int compare(const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compare(const value_type* _Ptr) const; - int compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Case insensitive comparison - int compareNoCase(const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compareNoCase(const value_type* _Ptr) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Copies at most a specified number of characters from an indexed position in a source string to a target character array. - size_type copy(value_type* _Ptr, size_type nCount, size_type nOff = 0) const; - - void push_back(value_type _Ch) { _ConcatenateInPlace(&_Ch, 1); } - void resize(size_type nCount, value_type _Ch = ' '); - - //! simple sub-string extraction - _Self substr(size_type pos, size_type count = npos) const; - - // replace part of string. - _Self& replace(value_type chOld, value_type chNew); - _Self& replace(const_str strOld, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew, size_type count2); - _Self& replace(size_type pos, size_type count, size_type nNumChars, value_type chNew); - - // insert new elements to string. - _Self& insert(size_type nIndex, value_type ch); - _Self& insert(size_type nIndex, size_type nCount, value_type ch); - _Self& insert(size_type nIndex, const_str pstr); - _Self& insert(size_type nIndex, const_str pstr, size_type nCount); - - //! delete count characters starting at zero-based index - _Self& erase(size_type nIndex, size_type count = npos); - - //! searching (return starting index, or -1 if not found) - //! look for a single character match - //! like "C" strchr - size_type find(value_type ch, size_type pos = 0) const; - //! look for a specific sub-string - //! like "C" strstr - size_type find(const_str subs, size_type pos = 0) const; - size_type rfind(value_type ch, size_type pos = npos) const; - - size_type find_first_of(value_type _Ch, size_type nOff = 0) const; - size_type find_first_of(const_str charSet, size_type nOff = 0) const; - //size_type find_first_of( const value_type* _Ptr,size_type _Off,size_type _Count ) const; - size_type find_first_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_first_not_of(value_type _Ch, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_first_not_of(const _Self& _Str, size_type _Off = 0) const; - - void swap(_Self& _Str); - - ////////////////////////////////////////////////////////////////////////// - // overloaded operators. - ////////////////////////////////////////////////////////////////////////// - // overloaded indexing. - value_type operator[](size_type index) const; - // value_type& operator[]( size_type index ); // same as at() - - // overloaded assignment - _Self& operator=(const _Self& str); - _Self& operator=(value_type ch); - _Self& operator=(const_str str); - _Self& operator=(const CryStringT& str); - - void move(_Self& src); - -#if defined(LINUX) || defined(APPLE) - template - _Self& operator=(const CryStackStringT& str) - { - _Assign(str.c_str(), str.size()); - return *this; - } -#endif - - // string concatenation - _Self& operator+=(const _Self& str); - _Self& operator+=(value_type ch); - _Self& operator+=(const_str str); - _Self& operator+=(const CryStringT& str); - - size_t GetAllocatedMemory() const - { - size_t size = sizeof(*this); - if (m_str != m_strBuf) - { - size += (m_nAllocSize + 1) * sizeof(value_type); - } - return size; - } - - ////////////////////////////////////////////////////////////////////////// - // Extended functions. - // This functions are not in the STL string. - // They have an ATL CString interface. - ////////////////////////////////////////////////////////////////////////// - //! Format string, use (sprintf) - _Self& Format(const value_type* format, ...); - - //! Format string fast, directly formats into string's buffer. - // Make sure there is enough space to hold the string - _Self& FormatFast (const value_type* format, ...); - - //! Converts the string to lower-case. - // This function uses the "C" locale for case-conversion (ie, A-Z only). - _Self& MakeLower(); - - //! Converts the string to upper-case. - // This function uses the "C" locale for case-conversion (ie, A-Z only). - _Self& MakeUpper(); - - _Self& Trim(); - _Self& Trim(value_type ch); - _Self& Trim(const value_type* sCharSet); - - _Self& TrimLeft(); - _Self& TrimLeft(value_type ch); - _Self& TrimLeft(const value_type* sCharSet); - - _Self& TrimRight(); - _Self& TrimRight(value_type ch); - _Self& TrimRight(const value_type* sCharSet); - - _Self SpanIncluding(const_str charSet) const; - _Self SpanExcluding(const_str charSet) const; - _Self Tokenize(const_str charSet, int& nStart) const; - _Self Mid(size_type nFirst, size_type nCount = npos) const { return substr(nFirst, nCount); }; - - _Self Left(size_type count) const; - _Self Right(size_type count) const; - ////////////////////////////////////////////////////////////////////////// - - // public utilities. - static bool _IsValidString(const_str str); - -public: - ////////////////////////////////////////////////////////////////////////// - // Only used for debugging statistics. - ////////////////////////////////////////////////////////////////////////// - static size_t _usedMemory(size_t size) - { - static size_t s_used_memory = 0; - s_used_memory += size; - return s_used_memory; - } - - //private: -public: - size_type m_nLength; - size_type m_nAllocSize; - value_type* m_str; // pointer to ref counted string data - value_type m_strBuf[MAX_SIZE]; - - // implementation helpers - void _AllocData(size_type nLen); - void _FreeData(value_type* pData); - void _Free(); - void _Initialize(); - - void _Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2); - void _ConcatenateInPlace(const_str sStr, size_type nLen); - void _Assign(const_str sStr, size_type nLen); - void _MakeUnique(); -}; - - -///////////////////////////////////////////////////////////////////////////// -// CryStackStringT Implementation -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -template -inline bool CryStackStringT::_IsValidString(const_str) -{ - return true; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Assign(const_str sStr, size_type nLen) -{ - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (nLen > capacity()) - { - _Free(); - _AllocData(nLen); - } - // Copy characters from new string to this buffer. - CharTraits::_copy(m_str, sStr, nLen); - // Set new length. - m_nLength = nLen; - // Make null terminated string. - m_str[nLen] = 0; - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2) -{ - size_type nLen = nLen1 + nLen2; - if (nLen1 * 2 > nLen) - { - nLen = nLen1 * 2; - } - if (nLen != 0) - { - if (nLen < 8) - { - nLen = 8; - } - _AllocData(nLen); - CharTraits::_copy(m_str, sStr1, nLen1); - CharTraits::_copy(m_str + nLen1, sStr2, nLen2); - m_nLength = nLen1 + nLen2; - m_str[nLen1 + nLen2] = 0; - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_ConcatenateInPlace(const_str sStr, size_type nLen) -{ - if (nLen != 0) - { - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (length() + nLen > capacity()) - { - value_type* pOldData = m_str; - _Concatenate(m_str, length(), sStr, nLen); - _FreeData(pOldData); - } - else - { - CharTraits::_copy(m_str + length(), sStr, nLen); - m_nLength += nLen; - m_str[m_nLength] = 0; // Make null terminated string. - } - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_MakeUnique() -{ -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Initialize() -{ - m_strBuf[0] = 0; - m_str = m_strBuf; - m_nLength = 0; - m_nAllocSize = MAX_SIZE - 1; // 0 termination not counted! -} - -// always allocate one extra character for '\0' termination -// assumes [optimistically] that data length will equal allocation length -template -inline void CryStackStringT::_AllocData(size_type nLen) -{ - assert(nLen >= 0); - assert(nLen <= INT_MAX - 1); // max size (enough room for 1 extra) - - if (nLen == 0) - { - _Initialize(); - } - else - { - size_type allocLen = (nLen + 1) * sizeof(value_type); - value_type* pData = m_strBuf; - if (allocLen > MAX_SIZE) - { - pData = (value_type*)CryModuleMalloc(allocLen); - _usedMemory(allocLen); // For statistics. - m_nAllocSize = nLen; - } - else - { - m_nAllocSize = MAX_SIZE - 1; - } - m_nLength = nLen; - m_str = pData; - m_str[nLen] = 0; // null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Free() -{ - _FreeData(m_str); - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_FreeData(value_type* pData) -{ - if (pData != m_strBuf) - { - size_t allocLen = (m_nAllocSize + 1) * sizeof(value_type); - _usedMemory(-check_cast(allocLen)); // For statistics. - CryModuleFree(pData); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT() -{ - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStackStringT& str) -{ - _Initialize(); - _Assign(str.c_str(), str.length()); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStackStringT& str, size_type nOff, size_type nCount) -{ - _Initialize(); - assign(str, nOff, nCount); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_str str) -{ - _Initialize(); - // Make a copy of C string. - size_type nLen = this->_strlen(str); - if (nLen != 0) - { - _AllocData(nLen); - CharTraits::_copy(m_str, str, nLen); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStringT& str) -{ - _Initialize(); - size_t nLength = str.size(); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, str.c_str(), nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_str str, size_type nLength) -{ - _Initialize(); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -// The reason of making this constructor unavailable (for a while) is -// explained in comments in front of the declaration of -// CryStringT::CryStringT(size_type nRepeat, value_type ch) -// (see CryString.h). -template -inline CryStackStringT::CryStackStringT(size_type nRepeat, value_type ch) -{ - _Initialize(); - if (nRepeat > 0) - { - _AllocData(nRepeat); - CharTraits::_set(m_str, ch, nRepeat); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_iterator _First, const_iterator _Last) -{ - _Initialize(); - size_type nLength = (size_type)(_Last - _First); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, _First, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::~CryStackStringT() -{ - _FreeData(m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::length() const -{ - return m_nLength; -} -template -inline typename CryStackStringT::size_type CryStackStringT::size() const -{ - return m_nLength; -} -template -inline typename CryStackStringT::size_type CryStackStringT::capacity() const -{ - return m_nAllocSize; -} - -template -inline bool CryStackStringT::empty() const -{ - return length() == 0; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::clear() -{ - if (length() == 0) - { - return; - } - _Free(); - assert(length() == 0); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::reserve(size_type nCount) -{ - // Reserve of 0 is shrinking container to fit number of characters in it.. - if (nCount > capacity()) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - _AllocData(nCount); - CharTraits::_copy(m_str, pOldData, nOldLength); - m_nLength = nOldLength; - m_str[m_nLength] = 0; - _FreeData(pOldData); - } - else if (nCount == 0) - { - if (length() != capacity()) - { - value_type* pOldData = m_str; - if (pOldData != m_strBuf) // in case we fit into our static buffer, we cannot shrink anyway - { - size_type nOldLength = m_nLength; - _AllocData(m_nLength); - // if (pOldData != m_strBuf || m_str != m_strBuf) // actually always true - // { - CharTraits::_copy(m_str, pOldData, nOldLength); // we can safely use CharTraits::_copy, as we never overlap here (in case of static buffer, we don't shrink anyway) - _FreeData(pOldData); - // } - } - } - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_str _Ptr) -{ - *this += _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_str _Ptr, size_type nCount) -{ - _ConcatenateInPlace(_Ptr, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const CryStackStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _ConcatenateInPlace(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const CryStackStringT& _Str) -{ - *this += _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(size_type nCount, value_type _Ch) -{ - if (nCount > 0) - { - if (length() + nCount >= capacity()) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - _AllocData(length() + nCount); - CharTraits::_copy(m_str, pOldData, nOldLength); - CharTraits::_set(m_str + nOldLength, _Ch, nCount); - _FreeData(pOldData); - } - else - { - size_type nOldLength = length(); - CharTraits::_set(m_str + nOldLength, _Ch, nCount); - m_nLength = nOldLength + nCount; - m_str[length()] = 0; // Make null terminated string. - } - } - CRY_STRING_DEBUG(m_str) - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_iterator _First, const_iterator _Last) -{ - append(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_str _Ptr) -{ - *this = _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_str _Ptr, size_type nCount) -{ - size_type len = this->_strlen(_Ptr); - _Assign(_Ptr, (nCount < len) ? nCount : len); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const CryStackStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _Assign(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const CryStackStringT& _Str) -{ - *this = _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(size_type nCount, value_type _Ch) -{ - if (nCount >= 1) - { - _AllocData(nCount); - CharTraits::_set(m_str, _Ch, nCount); - CRY_STRING_DEBUG(m_str) - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_iterator _First, const_iterator _Last) -{ - assign(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::value_type CryStackStringT::at(size_type index) const -{ - assert(index >= 0 && index < length()); - return m_str[index]; -} - -/* -inline value_type& CryStackStringT::at( size_type index ) -{ -// same as GetAt -assert( index >= 0 && index < length() ); -return m_str[index]; -} -*/ - -template -inline typename CryStackStringT::value_type CryStackStringT::operator[](size_type index) const -{ - assert(index < length()); - return m_str[index]; -} - - -/* -inline value_type& CryStackStringT::operator[]( size_type index ) -{ -// same as GetAt -assert( index >= 0 && index < length() ); -return m_str[index]; -} -*/ - - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStackStringT::compare(const CryStackStringT& _Str) const -{ - return CharTraits::_strcmp(m_str, _Str.m_str); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str) const -{ - return compare(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str, size_type nOff, size_type nCount) const -{ - assert(nOff < _Str.length()); - return compare(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStackStringT::compare(const value_type* _Ptr) const -{ - return CharTraits::_strcmp(m_str, _Ptr); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - assert(_Pos1 < length()); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : CharTraits::_strncmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStackStringT::compareNoCase(const CryStackStringT& _Str) const -{ - return CharTraits::_stricmp(m_str, _Str.m_str); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str) const -{ - return compareNoCase(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str, size_type nOff, size_type nCount) const -{ - assert(nOff < _Str.length()); - return compareNoCase(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStackStringT::compareNoCase(const value_type* _Ptr) const -{ - return CharTraits::_stricmp(m_str, _Ptr); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - assert(_Pos1 < length()); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : CharTraits::_strnicmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::copy(value_type* _Ptr, size_type nCount, size_type nOff) const -{ - assert(nOff < length()); - if (nCount < 0) - { - nCount = 0; - } - if (nOff + nCount > length()) // trim to offset. - { - nCount = length() - nOff; - } - - CharTraits::_copy(_Ptr, m_str + nOff, nCount); - return nCount; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::resize(size_type nCount, value_type _Ch) -{ - _MakeUnique(); - if (nCount > length()) - { - size_type numToAdd = nCount - length(); - append(numToAdd, _Ch); - } - else if (nCount < length()) - { - m_nLength = nCount; - m_str[length()] = 0; // Make null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -//! compare helpers -template -inline bool operator==(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) == 0; } -template -inline bool operator!=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) != 0; } -template -inline bool operator<(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) > 0; } -template -inline bool operator>(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) < 0; } -template -inline bool operator<=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) >= 0; } -template -inline bool operator>=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) <= 0; } - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::operator=(value_type ch) -{ - _Assign(&ch, 1); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& string1, typename CryStackStringT::value_type ch) -{ - CryStackStringT s(string1); - s.append(1, ch); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(typename CryStackStringT::value_type ch, const CryStackStringT& str) -{ - CryStackStringT s; - s.reserve(str.size() + 1); - s.append(1, ch); - s.append(str); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& string1, const CryStackStringT& string2) -{ - CryStackStringT s(string1); - s.append(string2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& str1, const typename CryStackStringT::value_type* str2) -{ - CryStackStringT s(str1); - s.append(str2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const typename CryStackStringT::value_type* str1, const CryStackStringT& str2) -{ - assert(str1 == NULL || (CryStackStringT::_IsValidString(str1))); - CryStackStringT s; - s.reserve(CharTraits::_strlen(str1) + str2.size()); - s.append(str1); - s.append(str2); - return s; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const CryStackStringT& str) -{ - _Assign (str.c_str(), str.length()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const_str str) -{ - assert(str == NULL || _IsValidString(str)); - _Assign(str, this->_strlen(str)); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const CryStringT& str) -{ - _Assign(str.c_str(), str.size()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const CryStringT& str) -{ - _ConcatenateInPlace(str.c_str(), str.size()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const_str str) -{ - assert(str == NULL || _IsValidString(str)); - _ConcatenateInPlace(str, this->_strlen(str)); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(value_type ch) -{ - _ConcatenateInPlace(&ch, 1); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const CryStackStringT& str) -{ - _ConcatenateInPlace(str.m_str, str.length()); - return *this; -} - -//! find first single character -template -inline typename CryStackStringT::size_type CryStackStringT::find(value_type ch, size_type pos) const -{ - if (!(/*pos >= 0 && */ pos <= length())) - { - return (typename CryStackStringT::size_type)npos; - } - const_str str = CharTraits::_strchr(m_str + pos, ch); - // return npos if not found and index otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find a sub-string (like strstr) -template -inline typename CryStackStringT::size_type CryStackStringT::find(const_str subs, size_type pos) const -{ - assert(_IsValidString(subs)); - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - // find first matching substring - const_str str = CharTraits::_strstr(m_str + pos, subs); - - // return npos for not found, distance from beginning otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find last single character -template -inline typename CryStackStringT::size_type CryStackStringT::rfind(value_type ch, size_type pos) const -{ - const_str str; - if (pos == npos) - { - // find last single character - str = strrchr(m_str, ch); - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); - } - else - { - if (pos == npos) - { - pos = length(); - } - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - value_type tmp = m_str[pos + 1]; - m_str[pos + 1] = 0; - str = strrchr(m_str, ch); - m_str[pos + 1] = tmp; - } - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(const CryStackStringT& _Str, size_type _Off) const -{ - return find_first_of(_Str.m_str, _Off); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(value_type _Ch, size_type nOff) const -{ - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - value_type charSet[2] = { _Ch, 0 }; - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? -1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(const_str charSet, size_type nOff) const -{ - assert(_IsValidString(charSet)); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -//size_type find_first_not_of(const _Self& __s, size_type __pos = 0) const -//{ return find_first_not_of(__s._M_start, __pos, __s.size()); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const -//{ _STLP_FIX_LITERAL_BUG(__s) return find_first_not_of(__s, __pos, _Traits::length(__s)); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const; - -//size_type find_first_not_of(_CharT __c, size_type __pos = 0) const; - - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const value_type* _Ptr, size_type _Off) const -{ return find_first_not_of(_Ptr, _Off, this->_strlen(_Ptr)); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const CryStackStringT& _Str, size_type _Off) const -{ return find_first_not_of(_Str.m_str, _Off); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(value_type _Ch, size_type _Off) const -{ - if (_Off > length()) - { - return npos; - } - else - { - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - if (*str != _Ch) - { - return size_type(str - begin()); // Character found! - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - if (_Off > length()) - { - return npos; - } - else - { - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - const value_type* c; - for (c = charsFirst; c != charsLast; ++c) - { - if (*c == *str) - { - break; - } - } - if (c == charsLast) - { - return size_type(str - begin());// Current character not in char set. - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT CryStackStringT::substr(size_type pos, size_type count) const -{ - if (pos >= length()) - { - return CryStackStringT(); - } - if (count == npos) - { - count = length() - pos; - } - if (pos + count > length()) - { - count = length() - pos; - } - return CryStackStringT(m_str + pos, count); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::erase(size_type nIndex, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - if (nCount < 0 || nCount > length() - nIndex) - { - nCount = length() - nIndex; - } - if (nCount > 0 && nIndex < length()) - { - _MakeUnique(); - size_type nNumToCopy = length() - (nIndex + nCount) + 1; - CharTraits::_move(m_str + nIndex, m_str + nIndex + nCount, nNumToCopy); - m_nLength = length() - nCount; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, value_type ch) -{ - return insert(nIndex, 1, ch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, size_type nCount, value_type ch) -{ - _MakeUnique(); - - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nNewLength = length(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nCount; - - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - const_str pstr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pstr, nOldLength + 1); - _FreeData(pOldData); - } - - CharTraits::_move(m_str + nIndex + nCount, m_str + nIndex, (nNewLength - nIndex)); - CharTraits::_set(m_str + nIndex, ch, nCount); - m_nLength = nNewLength; - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, const_str pstr, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nInsertLength = nCount; - size_type nNewLength = length(); - if (nInsertLength > 0) - { - _MakeUnique(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nInsertLength; - - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - const_str pOldStr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pOldStr, (nOldLength + 1)); - _FreeData(pOldData); - } - - CharTraits::_move(m_str + nIndex + nInsertLength, m_str + nIndex, (nNewLength - nIndex - nInsertLength + 1)); - CharTraits::_copy(m_str + nIndex, pstr, nInsertLength); - m_nLength = nNewLength; - m_str[length()] = 0; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, const_str pstr) -{ - return insert(nIndex, pstr, this->_strlen(pstr)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, const_str strNew) -{ - return replace(pos, count, strNew, this->_strlen(strNew)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, const_str strNew, size_type count2) -{ - erase(pos, count); - insert(pos, strNew, count2); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, size_type nNumChars, value_type chNew) -{ - erase(pos, count); - insert(pos, nNumChars, chNew); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(value_type chOld, value_type chNew) -{ - if (chOld != chNew) - { - _MakeUnique(); - value_type* strend = m_str + length(); - for (value_type* str = m_str; str != strend; ++str) - { - if (*str == chOld) - { - *str = chNew; - } - } - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(const_str strOld, const_str strNew) -{ - size_type nSourceLen = this->_strlen(strOld); - if (nSourceLen == 0) - { - return *this; - } - size_type nReplacementLen = this->_strlen(strNew); - - size_type nCount = 0; - value_type* strStart = m_str; - value_type* strEnd = m_str + length(); - value_type* strTarget; - while (strStart < strEnd) - { - while ((strTarget = CharTraits::_strstr(strStart, strOld)) != NULL) - { - nCount++; - strStart = strTarget + nSourceLen; - } - strStart += this->_strlen(strStart) + 1; - } - - if (nCount > 0) - { - _MakeUnique(); - - size_type nOldLength = length(); - size_type nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount; - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nPrevLength = m_nLength; - const_str pstr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pstr, nPrevLength); - _FreeData(pOldData); - } - strStart = m_str; - strEnd = m_str + length(); - - while (strStart < strEnd) - { - while ((strTarget = CharTraits::_strstr(strStart, strOld)) != NULL) - { - size_type nBalance = nOldLength - ((size_type)(strTarget - m_str) + nSourceLen); - CharTraits::_move(strTarget + nReplacementLen, strTarget + nSourceLen, nBalance); - CharTraits::_copy(strTarget, strNew, nReplacementLen); - strStart = strTarget + nReplacementLen; - strStart[nBalance] = 0; - nOldLength += (nReplacementLen - nSourceLen); - } - strStart += this->_strlen(strStart) + 1; - } - m_nLength = nNewLength; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::move(CryStackStringT& str) -{ - memcpy(this, &str, sizeof(*this)); - if (str.m_str == str.m_strBuf) - { - m_str = m_strBuf; - } -} - -template -inline void CryStackStringT::swap(CryStackStringT& _Str) -{ - CryStackStringT temp; - temp.move(*this); - move(_Str); - _Str.move(temp); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Format(const_str format, ...) -{ - assert(_IsValidString(format)); - - value_type temp[4096]; // Limited to 4096 characters! - va_list argList; - va_start(argList, format); - this->_vsnprintf(temp, 4095, format, argList); - temp[4095] = '\0'; - va_end(argList); - *this = temp; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::FormatFast(const_str format, ...) -{ - assert(_IsValidString(format)); - - va_list argList; - va_start(argList, format); - - int newLength = this->_vsnprintf(m_str, capacity(), format, argList); - if (newLength >= 0) - { - m_nLength = (size_type)newLength; - } - else - { - m_nLength = capacity(); - m_str[capacity()] = '\0'; - } - - va_end(argList); - - return *this; -} - - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::MakeLower() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - *s = this->_ascii_tolower(*s); - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::MakeUpper() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - *s = this->_ascii_toupper(*s); - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim() -{ - return TrimRight().TrimLeft(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim(value_type ch) -{ - _MakeUnique(); - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset).TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim(const value_type* sCharSet) -{ - _MakeUnique(); - return TrimRight(sCharSet).TrimLeft(sCharSet); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet) || length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (CharTraits::_strchr(sCharSet, *str) != 0)) - { - str--; - } - - if (str != last) - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight() -{ - if (length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (CharTraits::_isspace(*str) != 0)) - { - str--; - } - - if (str != last) // something changed? - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet)) - { - return *this; - } - - const value_type* str = m_str; - while ((*str != 0) && (CharTraits::_strchr(sCharSet, *str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - CharTraits::_move(m_str, m_str + nOff, nNewLength + 1); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft() -{ - const value_type* str = m_str; - while ((*str != 0) && (CharTraits::_isspace(*str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - CharTraits::_move(m_str, m_str + nOff, nNewLength + 1); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -template -inline CryStackStringT CryStackStringT::Right(size_type count) const -{ - if (count == npos) - { - return CryStackStringT(); - } - else if (count > length()) - { - return *this; - } - - return CryStackStringT(m_str + length() - count, count); -} - -template -inline CryStackStringT CryStackStringT::Left(size_type count) const -{ - if (count == npos) - { - return CryStackStringT(); - } - else if (count > length()) - { - count = length(); - } - - return CryStackStringT(m_str, count); -} - -// strspn equivalent -template -inline CryStackStringT CryStackStringT::SpanIncluding(const_str charSet) const -{ - assert(_IsValidString(charSet)); - return Left((size_type)this->_strspn(m_str, charSet)); -} - -// strcspn equivalent -template -inline CryStackStringT CryStackStringT::SpanExcluding(const_str charSet) const -{ - assert(_IsValidString(charSet)); - return Left((size_type)this->_strcspn(m_str, charSet)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT CryStackStringT::Tokenize(const_str charSet, int& nStart) const -{ - if (nStart < 0) - { - return CryStackStringT(); - } - - if (!charSet) - { - return *this; - } - - const_str sPlace = m_str + nStart; - const_str sEnd = m_str + length(); - if (sPlace < sEnd) - { - int nIncluding = (int)this->_strspn(sPlace, charSet); - - if ((sPlace + nIncluding) < sEnd) - { - sPlace += nIncluding; - int nExcluding = (int)this->_strcspn(sPlace, charSet); - int nFrom = nStart + nIncluding; - nStart = nFrom + nExcluding + 1; - - return substr(nFrom, nExcluding); - } - } - // Return empty string. - nStart = -1; - return CryStackStringT(); -} - -#if defined(_RELEASE) -#define ASSERT_LEN (void)(0) -#define ASSERT_WLEN (void)(0) -#else -#define ASSERT_LEN CRY_ASSERT_TRACE(this->length() <= S, ("String '%s' is %u character(s) longer than MAX_SIZE=%u", this->c_str(), this->length() - S, S)) -#define ASSERT_WLEN CRY_ASSERT_TRACE(this->length() <= S, ("Wide-char string '%ls' is %u character(s) longer than MAX_SIZE=%u", this->c_str(), this->length() - S, S)) -#endif - -// a template specialization for char -template -class CryFixedStringT - : public CryStackStringT -{ -public: - typedef CryStackStringT _parentType; - typedef CryFixedStringT _Self; - typedef size_t size_type; - typedef char value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - CryFixedStringT() - : _parentType() {} - CryFixedStringT(const _parentType& str) - : _parentType(str) {ASSERT_LEN; } - CryFixedStringT(const _parentType& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_LEN; } - CryFixedStringT(const _Self& str) - : _parentType(str) {ASSERT_LEN; } - CryFixedStringT(const _Self& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_LEN; } - CryFixedStringT(size_type nRepeat, value_type ch) - : _parentType(nRepeat, ch) {ASSERT_LEN; } - CryFixedStringT(const_str str) - : _parentType (str) {ASSERT_LEN; } - CryFixedStringT(const_str str, size_type nLength) - : _parentType(str, nLength) {ASSERT_LEN; } - CryFixedStringT(const_iterator _First, const_iterator _Last) - : _parentType(_First, _Last) {ASSERT_LEN; } - - template - _Self& operator=(const CryFixedStringT& str) - { - _parentType::operator = (str); - ASSERT_LEN; - return *this; - } - template - _Self& operator=(const CryStackStringT& str) - { - _parentType::operator = (str); - ASSERT_LEN; - return *this; - } - _Self& operator=(value_type ch) - { - _parentType::operator = (ch); - ASSERT_LEN; - return *this; - } - - void GetMemoryUsage(class ICrySizer* pSizer) const{} -}; - -// a template specialization for a fixed list of CryFixedString [Jan M.] -template -class CCryFixedStringListT -{ -public: - CCryFixedStringListT() - { Clear(); } - - void Clear() - { - m_currentAmount = -1; - for (int a = 0; a < NUM_MAX_ELEMENTS; ++a) - { - m_data[a] = ""; - } - } - - void Add(const char* name) - { - m_data[++m_currentAmount] = name; - if (m_currentAmount == NUM_MAX_ELEMENTS) - { - m_currentAmount = -1; - } - } - - const char* operator[](int index) - { - if (index <= m_currentAmount) - { - return m_data[index].c_str(); - } - return NULL; - } - - ILINE int Size() { return m_currentAmount + 1; } - - CryFixedStringT<32>* GetData(int& amount) - { - amount = m_currentAmount + 1; - return m_data; - } -private: - const static int NUM_MAX_ELEMENTS = maxElements; - CryFixedStringT m_data[NUM_MAX_ELEMENTS]; - int32 m_currentAmount; -}; - -// a template specialization for wchar_t -template -class CryFixedWStringT - : public CryStackStringT -{ -public: - typedef CryStackStringT _parentType; - typedef CryFixedWStringT _Self; - typedef size_t size_type; - typedef wchar_t value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - CryFixedWStringT() - : _parentType() {} - CryFixedWStringT(const _parentType& str) - : _parentType(str) {ASSERT_WLEN; } - CryFixedWStringT(const _parentType& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_WLEN; } - CryFixedWStringT(const _Self& str) - : _parentType(str) {ASSERT_WLEN; } - CryFixedWStringT(const _Self& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_WLEN; } - CryFixedWStringT(size_type nRepeat, value_type ch) - : _parentType(nRepeat, ch) {ASSERT_WLEN; } - CryFixedWStringT(const_str str) - : _parentType (str) {ASSERT_WLEN; } - CryFixedWStringT(const_str str, size_type nLength) - : _parentType(str, nLength) {ASSERT_WLEN; } - CryFixedWStringT(const_iterator _First, const_iterator _Last) - : _parentType(_First, _Last) {ASSERT_WLEN; } - - template - _Self& operator=(const CryFixedWStringT& str) - { - _parentType::operator = (str); - ASSERT_WLEN; - return *this; - } - template - _Self& operator=(const CryStackStringT& str) - { - _parentType::operator = (str); - ASSERT_WLEN; - return *this; - } -}; -#undef ASSERT_LEN -#undef ASSERT_WLEN -typedef CryStackStringT stack_string; - -// Special string type used for specifying file paths. -typedef CryStackStringT CryPathString; - - -#if UNITTEST_CRYFIXEDSTRING - -struct SUnitTest_FixedString -{ - bool UnitAssert(const char* message, const char* value, const char* refValue) - { - int res = strcmp(value, refValue); - CRY_ASSERT_MESSAGE(res == 0, message); - return res == 0; - } - - bool UnitAssert(const char* message, const wchar_t* value, const wchar_t* refValue) - { - int res = wcscmp(value, refValue); - CRY_ASSERT_MESSAGE(res == 0, message); - return res == 0; - } - - bool UnitAssert(const char* message, bool cond) - { - CRY_ASSERT_MESSAGE(cond, message); - return cond; - } - - bool UnitAssert(const char* message, size_t a, size_t b) - { - CRY_ASSERT_MESSAGE(a == b, message); - return a == b; - } - - int UnitTest() - { - CryStackStringT str1; - CryStackStringT str2; - CryStackStringT str3; - CryStackStringT str4; - CryStackStringT str5; - CryStackStringT wstr1; - CryStackStringT wstr2; - CryFixedStringT<100> fixedString100; - CryFixedStringT<200> fixedString200; - - typedef CryStackStringT T; - T* pStr = new T; - * pStr = "adads"; - delete pStr; - - str1 = "abcd"; - UnitAssert ("Assignment1-EnoughSpace", str1, "abcd"); - - str2 = "efg"; - UnitAssert ("Assignment2-EnoughSpace", str2, "efg"); - - str2 = str1; - UnitAssert ("Assignment3-EnoughSpace", str2, "abcd"); - - str3 = str1; - UnitAssert ("Assignment4-NotEnoughSpace", str3, "abcd"); - - str1 += "XY"; - UnitAssert ("Concatenate-EnoughSpace", str1, "abcdXY"); - - str2 += "efghijk"; - UnitAssert ("Concatenate-NotEnoughSpace", str2, "abcdefghijk"); - - str1.replace("bc", ""); - UnitAssert ("Replace-Shrink-EnoughSpace", str1, "adXY"); - - str1.replace("XY", "1234"); - UnitAssert ("Replace-Grow-EnoughSpace", str1, "ad1234"); - - str1.replace("1234", "1234567890"); - UnitAssert ("Replace-Grow-NotEnoughSpace", str1, "ad1234567890"); - - str1.reserve(200); - UnitAssert ("Reserve200-SameString", str1, "ad1234567890"); - UnitAssert ("Reserve200-Capacity", str1.capacity() == 200); - - str1.reserve(0); - UnitAssert ("Reserve0-SameString", str1, "ad1234567890"); - UnitAssert ("Reserve0-Capacity==Length", str1.capacity() == str1.length()); - - str1.erase(7); // doesn't change capacity - UnitAssert ("Erase-SameString", str1, "ad12345"); - - str4.assign("abc"); - UnitAssert ("Str4 Assignment", str4, "abc"); - str4.reserve(9); - UnitAssert ("Str4", str4.capacity() >= 9); // capacity is always >= MAX_SIZE-1 - str4.reserve(0); - UnitAssert ("Str4-Shrink", str4.capacity() >= 9); // capacity is always >= MAX_SIZE-1 - - size_t idx = str1.find("123"); - UnitAssert ("Str1-Find", idx == 2); - - idx = str1.find("123", 3); - UnitAssert ("Str1-Find", idx == str1.npos); - - wstr1 = L"abc"; - UnitAssert ("WStr1-Assign", wstr1, L"abc"); - UnitAssert ("WStr1-CompareCaseGT", wstr1.compare(L"aBc") > 0); - UnitAssert ("WStr1-CompareCaseLT", wstr1.compare(L"babc") < 0); - UnitAssert ("WStr1-CompareNoCase", wstr1.compareNoCase(L"aBc") == 0); - - str1.Format("This is a %s %S with %d params", "mixed", L"string", 3); - str2.Format("This is a %S %s with %d params", L"mixed", "string", 3); - UnitAssert ("Str1-Format1", str1, "This is a mixed string with 3 params"); - UnitAssert ("Str1-Format2", str1, str2); - - wstr1.Format(L"This is a %s %S with %d params", L"mixed", "string", 3); - wstr2.Format(L"This is a %S %s with %d params", "mixed", L"string", 3); - UnitAssert ("WStr1-Format1", wstr1, L"This is a mixed string with 3 params"); - UnitAssert ("WStr1-Format2", wstr1, wstr2); - - str5.FormatFast("%s", "12345"); - UnitAssert ("Str5-FormatFast", str5, "12345"); - - str5.FormatFast("%s", "012345"); - UnitAssert ("Str5-FormatFast-Truncate", str5, "01234"); - - fixedString100 = str5; - str2 = fixedString200; - fixedString200 = fixedString100; - UnitAssert ("FixedString-Test2", fixedString100, "01234"); - UnitAssert ("FixedString-Test1", fixedString100, fixedString200); - - CryStackStringT testStr; - CryFixedStringT<100> testStr2; - CryFixedWStringT<100> testWStr1; - string normalString; - wstring normalWString; - normalString = string(testStr); - normalString = string(testStr2); - normalString.assign(testStr2.c_str()); - // normalString = testStr; // <- must NOT compile, as we don't allow it! - // normalWString = testWStr1; // <- must NOT compile, as we don't allow it! - normalWString = wstring(testWStr1); - return 0; - } -}; -#endif // #if UNITTEST_CRYFIXEDSTRING - -#endif // CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H diff --git a/Code/Legacy/CryCommon/CryListenerSet.h b/Code/Legacy/CryCommon/CryListenerSet.h index 6addfa384e..6857cf7e5d 100644 --- a/Code/Legacy/CryCommon/CryListenerSet.h +++ b/Code/Legacy/CryCommon/CryListenerSet.h @@ -182,7 +182,7 @@ private: // DO NOT REMOVE - following methods only to be accessed only via CN }; typedef std::vector TListenerVec; - typedef std::vector TAllocatedNameVec; + typedef std::vector TAllocatedNameVec; inline void StartNotificationScope(); inline void EndNotificationScope(); diff --git a/Code/Legacy/CryCommon/CryName.h b/Code/Legacy/CryCommon/CryName.h index 0495ad78f1..8e62a52517 100644 --- a/Code/Legacy/CryCommon/CryName.h +++ b/Code/Legacy/CryCommon/CryName.h @@ -395,13 +395,13 @@ inline bool CCryName::operator>(const CCryName& n) const return m_str > n.m_str; } -inline bool operator==(const string& s, const CCryName& n) +inline bool operator==(const AZStd::string& s, const CCryName& n) { - return n == s; + return s == n; } -inline bool operator!=(const string& s, const CCryName& n) +inline bool operator!=(const AZStd::string& s, const CCryName& n) { - return n != s; + return s != n; } inline bool operator==(const char* s, const CCryName& n) @@ -543,13 +543,13 @@ inline bool CCryNameCRC::operator>(const CCryNameCRC& n) const return m_nID > n.m_nID; } -inline bool operator==(const string& s, const CCryNameCRC& n) +inline bool operator==(const AZStd::string& s, const CCryNameCRC& n) { - return n == s; + return s == n; } -inline bool operator!=(const string& s, const CCryNameCRC& n) +inline bool operator!=(const AZStd::string& s, const CCryNameCRC& n) { - return n != s; + return s != n; } inline bool operator==(const char* s, const CCryNameCRC& n) diff --git a/Code/Legacy/CryCommon/CryPath.h b/Code/Legacy/CryCommon/CryPath.h index 32db308a85..e01e7a2e4b 100644 --- a/Code/Legacy/CryCommon/CryPath.h +++ b/Code/Legacy/CryCommon/CryPath.h @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include "platform.h" @@ -31,26 +33,28 @@ #define CRY_NATIVE_PATH_SEPSTR DOS_PATH_SEP_STR #endif +typedef AZStd::fixed_string<512> stack_string; + namespace PathUtil { const static int maxAliasLength = 32; - inline string GetLocalizationFolder() + inline AZStd::string GetLocalizationFolder() { return gEnv->pCryPak->GetLocalizationFolder(); } - inline string GetLocalizationRoot() + inline AZStd::string GetLocalizationRoot() { return gEnv->pCryPak->GetLocalizationRoot(); } //! Convert a path to the uniform form. - inline string ToUnixPath(const string& strPath) + inline AZStd::string ToUnixPath(const AZStd::string& strPath) { - if (strPath.find(DOS_PATH_SEP_CHR) != string::npos) + if (strPath.find(DOS_PATH_SEP_CHR) != AZStd::string::npos) { - string path = strPath; - path.replace(DOS_PATH_SEP_CHR, UNIX_PATH_SEP_CHR); + AZStd::string path = strPath; + AZ::StringFunc::Replace(path, DOS_PATH_SEP_CHR, UNIX_PATH_SEP_CHR); return path; } return strPath; @@ -73,19 +77,19 @@ namespace PathUtil } //! Convert a path to the DOS form. - inline string ToDosPath(const string& strPath) + inline AZStd::string ToDosPath(const AZStd::string& strPath) { - if (strPath.find(UNIX_PATH_SEP_CHR) != string::npos) + if (strPath.find(UNIX_PATH_SEP_CHR) != AZStd::string::npos) { - string path = strPath; - path.replace(UNIX_PATH_SEP_CHR, DOS_PATH_SEP_CHR); + AZStd::string path = strPath; + AZ::StringFunc::Replace(path, UNIX_PATH_SEP_CHR, DOS_PATH_SEP_CHR); return path; } return strPath; } //! Convert a path to the Native form. - inline string ToNativePath(const string& strPath) + inline AZStd::string ToNativePath(const AZStd::string& strPath) { #if AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS return ToUnixPath(strPath); @@ -95,10 +99,10 @@ namespace PathUtil } //! Convert a path to lowercase form - inline string ToLower(const string& strPath) + inline AZStd::string ToLower(const AZStd::string& strPath) { - string path = strPath; - path.MakeLower(); + AZStd::string path = strPath; + AZStd::to_lower(path.begin(), path.end()); return path; } @@ -108,9 +112,9 @@ namespace PathUtil //! @param path [OUT] Extracted file path. //! @param filename [OUT] Extracted file (without extension). //! @param ext [OUT] Extracted files extension. - inline void Split(const string& filepath, string& path, string& filename, string& fext) + inline void Split(const AZStd::string& filepath, AZStd::string& path, AZStd::string& filename, AZStd::string& fext) { - path = filename = fext = string(); + path = filename = fext = AZStd::string(); if (filepath.empty()) { return; @@ -142,16 +146,16 @@ namespace PathUtil //! @param filepath [IN] Full file name inclusing path. //! @param path [OUT] Extracted file path. //! @param file [OUT] Extracted file (with extension). - inline void Split(const string& filepath, string& path, string& file) + inline void Split(const AZStd::string& filepath, AZStd::string& path, AZStd::string& file) { - string fext; + AZStd::string fext; Split(filepath, path, file, fext); file += fext; } // Extract extension from full specified file path // Returns - // pointer to the extension (without .) or pointer to an empty 0-terminated string + // pointer to the extension (without .) or pointer to an empty 0-terminated AZStd::string inline const char* GetExt(const char* filepath) { const char* str = filepath; @@ -174,7 +178,7 @@ namespace PathUtil } //! Extract path from full specified file path. - inline string GetPath(const string& filepath) + inline AZStd::string GetPath(const AZStd::string& filepath) { const char* str = filepath.c_str(); for (const char* p = str + filepath.length() - 1; p >= str; --p) @@ -191,9 +195,9 @@ namespace PathUtil } //! Extract path from full specified file path. - inline string GetPath(const char* filepath) + inline AZStd::string GetPath(const char* filepath) { - return GetPath(string(filepath)); + return GetPath(AZStd::string(filepath)); } //! Extract path from full specified file path. @@ -214,7 +218,7 @@ namespace PathUtil } //! Extract file name with extension from full specified file path. - inline string GetFile(const string& filepath) + inline AZStd::string GetFile(const AZStd::string& filepath) { const char* str = filepath.c_str(); for (const char* p = str + filepath.length() - 1; p >= str; --p) @@ -247,7 +251,7 @@ namespace PathUtil } //! Replace extension for given file. - inline void RemoveExtension(string& filepath) + inline void RemoveExtension(AZStd::string& filepath) { const char* str = filepath.c_str(); for (const char* p = str + filepath.length() - 1; p >= str; --p) @@ -291,15 +295,15 @@ namespace PathUtil } //! Extract file name without extension from full specified file path. - inline string GetFileName(const string& filepath) + inline AZStd::string GetFileName(const AZStd::string& filepath) { - string file = filepath; + AZStd::string file = filepath; RemoveExtension(file); return GetFile(file); } //! Removes the trailing slash or backslash from a given path. - inline string RemoveSlash(const string& path) + inline AZStd::string RemoveSlash(const AZStd::string& path) { if (path.empty() || (path[path.length() - 1] != '/' && path[path.length() - 1] != '\\')) { @@ -309,13 +313,13 @@ namespace PathUtil } //! get slash - inline string GetSlash() + inline AZStd::string GetSlash() { return CRY_NATIVE_PATH_SEPSTR; } //! add a backslash if needed - inline string AddSlash(const string& path) + inline AZStd::string AddSlash(const AZStd::string& path) { if (path.empty() || path[path.length() - 1] == '/') { @@ -343,9 +347,9 @@ namespace PathUtil } //! add a backslash if needed - inline string AddSlash(const char* path) + inline AZStd::string AddSlash(const char* path) { - return AddSlash(string(path)); + return AddSlash(AZStd::string(path)); } inline stack_string ReplaceExtension(const stack_string& filepath, const char* ext) @@ -364,9 +368,9 @@ namespace PathUtil } //! Replace extension for given file. - inline string ReplaceExtension(const string& filepath, const char* ext) + inline AZStd::string ReplaceExtension(const AZStd::string& filepath, const char* ext) { - string str = filepath; + AZStd::string str = filepath; if (ext != 0) { RemoveExtension(str); @@ -380,29 +384,30 @@ namespace PathUtil } //! Replace extension for given file. - inline string ReplaceExtension(const char* filepath, const char* ext) + inline AZStd::string ReplaceExtension(const char* filepath, const char* ext) { - return ReplaceExtension(string(filepath), ext); + return ReplaceExtension(AZStd::string(filepath), ext); } //! Makes a fully specified file path from path and file name. - inline string Make(const string& path, const string& file) + inline AZStd::string Make(const AZStd::string& path, const AZStd::string& file) { return AddSlash(path) + file; } //! Makes a fully specified file path from path and file name. - inline string Make(const string& dir, const string& filename, const string& ext) + inline AZStd::string Make(const AZStd::string& dir, const AZStd::string& filename, const AZStd::string& ext) { - string path = ReplaceExtension(filename, ext); + AZStd::string path = filename; + AZ::StringFunc::Path::ReplaceExtension(path, ext.c_str()); path = AddSlash(dir) + path; return path; } //! Makes a fully specified file path from path and file name. - inline string Make(const string& dir, const string& filename, const char* ext) + inline AZStd::string Make(const AZStd::string& dir, const AZStd::string& filename, const char* ext) { - return Make(dir, filename, string(ext)); + return Make(dir, filename, AZStd::string(ext)); } //! Makes a fully specified file path from path and file name. @@ -414,42 +419,43 @@ namespace PathUtil //! Makes a fully specified file path from path and file name. inline stack_string Make(const stack_string& dir, const stack_string& filename, const stack_string& ext) { - stack_string path = ReplaceExtension(filename, ext); - path = AddSlash(dir) + path; - return path; + AZStd::string path = filename; + AZ::StringFunc::Path::ReplaceExtension(path, ext.c_str()); + path = AddSlash(dir.c_str()) + path; + return stack_string(path.c_str()); } //! Makes a fully specified file path from path and file name. - inline string Make(const char* path, const string& file) + inline AZStd::string Make(const char* path, const AZStd::string& file) { - return Make(string(path), file); + return Make(AZStd::string(path), file); } //! Makes a fully specified file path from path and file name. - inline string Make(const string& path, const char* file) + inline AZStd::string Make(const AZStd::string& path, const char* file) { - return Make(path, string(file)); + return Make(path, AZStd::string(file)); } //! Makes a fully specified file path from path and file name. - inline string Make(const char path[], const char file[]) + inline AZStd::string Make(const char path[], const char file[]) { - return Make(string(path), string(file)); + return Make(AZStd::string(path), AZStd::string(file)); } //! Makes a fully specified file path from path and file name. - inline string Make(const char* path, const char* file, const char* ext) + inline AZStd::string Make(const char* path, const char* file, const char* ext) { - return Make(string(path), string(file), string(ext)); + return Make(AZStd::string(path), AZStd::string(file), AZStd::string(ext)); } //! Makes a fully specified file path from path and file name. - inline string MakeFullPath(const string& relativePath) + inline AZStd::string MakeFullPath(const AZStd::string& relativePath) { return relativePath; } - inline string GetParentDirectory (const string& strFilePath, int nGeneration = 1) + inline AZStd::string GetParentDirectory (const AZStd::string& strFilePath, int nGeneration = 1) { for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent p >= strFilePath.c_str(); @@ -458,23 +464,23 @@ namespace PathUtil switch (*p) { case ':': - return string (strFilePath.c_str(), p); + return AZStd::string(strFilePath.c_str(), p); case '/': case '\\': // we've reached a path separator - return everything before it. if (!--nGeneration) { - return string(strFilePath.c_str(), p); + return AZStd::string(strFilePath.c_str(), p); } break; } } // it seems the file name is a pure name, without path or extension - return string(); + return AZStd::string(); } template - inline CryStackStringT GetParentDirectoryStackString(const CryStackStringT& strFilePath, int nGeneration = 1) + inline AZStd::basic_fixed_string GetParentDirectoryStackString(const AZStd::basic_fixed_string& strFilePath, int nGeneration = 1) { for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent p >= strFilePath.c_str(); @@ -483,19 +489,19 @@ namespace PathUtil switch (*p) { case ':': - return CryStackStringT (strFilePath.c_str(), p); + return AZStd::basic_fixed_string (strFilePath.c_str(), p); case '/': case '\\': // we've reached a path separator - return everything before it. if (!--nGeneration) { - return CryStackStringT(strFilePath.c_str(), p); + return AZStd::basic_fixed_string(strFilePath.c_str(), p); } break; } } // it seems the file name is a pure name, without path or extension - return CryStackStringT(); + return AZStd::basic_fixed_string(); } ////////////////////////////////////////////////////////////////////////// @@ -503,7 +509,8 @@ namespace PathUtil // Make a game correct path out of any input path. inline stack_string MakeGamePath(const stack_string& path) { - stack_string relativePath(ToUnixPath(path)); + stack_string relativePath = path; + ToUnixPath(relativePath); if ((!gEnv) || (!gEnv->pFileIO)) { @@ -512,7 +519,7 @@ namespace PathUtil unsigned int index = 0; if (relativePath.length() && relativePath[index] == '@') // already aliased { - if (relativePath.compareNoCase(0, 9, "@assets@/") == 0) + if (AZ::StringFunc::Equal(relativePath.c_str(), "@assets@/", false, 9)) { return relativePath.substr(9); // assets is assumed. } @@ -526,7 +533,7 @@ namespace PathUtil if ( (rootPath.size() > 0) && (rootPath.size() < relativePath.size()) && - (relativePath.compareNoCase(0, rootPath.size(), rootPath) == 0) + (AZ::StringFunc::Equal(relativePath.c_str(), rootPath.c_str(), false, rootPath.size())) ) { stack_string chopped_string = relativePath.substr(rootPath.size()); @@ -543,13 +550,13 @@ namespace PathUtil ////////////////////////////////////////////////////////////////////////// // Description: // Make a game correct path out of any input path. - inline string MakeGamePath(const string& path) + inline AZStd::string MakeGamePath(const AZStd::string& path) { stack_string stackPath(path.c_str()); return MakeGamePath(stackPath).c_str(); } - // returns true if the string matches the wildcard + // returns true if the AZStd::string matches the wildcard inline bool MatchWildcard (const char* szString, const char* szWildcard) { const char* pString = szString, * pWildcard = szWildcard; @@ -595,7 +602,7 @@ namespace PathUtil if (!*pWildcard) { - return true; // the rest of the string doesn't matter: the wildcard ends with * + return true; // the rest of the AZStd::string doesn't matter: the wildcard ends with * } for (; *pString; ++pString) { diff --git a/Code/Legacy/CryCommon/CrySizer.h b/Code/Legacy/CryCommon/CrySizer.h index 9301360bd5..add2cdd397 100644 --- a/Code/Legacy/CryCommon/CrySizer.h +++ b/Code/Legacy/CryCommon/CrySizer.h @@ -208,9 +208,7 @@ public: this->AddObject(rPair.first); this->AddObject(rPair.second); } - void AddObject(const string& rString) {this->AddObject(rString.c_str(), rString.capacity()); } - void AddObject(const CryStringT& rString) {this->AddObject(rString.c_str(), rString.capacity()); } - void AddObject(const CryFixedStringT<32>&){} + void AddObject(const AZStd::string& rString) {this->AddObject(rString.c_str(), rString.capacity()); } void AddObject(const wchar_t&) {} void AddObject(const char&) {} void AddObject(const unsigned char&) {} @@ -427,7 +425,7 @@ public: #endif #ifndef NOT_USE_CRY_STRING - bool Add (const string& strText) + bool Add (const AZStd::string& strText) { AddString(strText); return true; diff --git a/Code/Legacy/CryCommon/CryString.h b/Code/Legacy/CryCommon/CryString.h deleted file mode 100644 index 72469e3dca..0000000000 --- a/Code/Legacy/CryCommon/CryString.h +++ /dev/null @@ -1,2523 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Custom reference counted string class. -// Can easily be substituted instead of string - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYSTRING_H -#define CRYINCLUDE_CRYCOMMON_CRYSTRING_H -#pragma once - -#include -#include - -#if !defined(NOT_USE_CRY_STRING) - -#include -#include -#include -#include -#include -#include "LegacyAllocator.h" - -#define CRY_STRING - -// forward declaration of CryStackString -template -class CryStackStringT; - - -class CConstCharWrapper; //forward declaration for special const char * without memory allocations - -//extern void CryDebugStr( const char *format,... ); -//#define CRY_STRING_DEBUG(s) { if (*s) CryDebugStr( "[%6d] %s",_usedMemory(0),(s) );} -#define CRY_STRING_DEBUG(s) - -class CryStringAllocator - : public AZ::SimpleSchemaAllocator -{ -public: - AZ_TYPE_INFO(CryStringAllocator, "{763DFC83-8A6E-4FD9-B6BC-BBF56E93E4EE}"); - - using Base = AZ::SimpleSchemaAllocator; - using Descriptor = Base::Descriptor; - - CryStringAllocator() - : Base("CryStringAllocator", "Allocator for CryString") - { - Descriptor desc; - desc.m_systemChunkSize = 4 * 1024 * 1024; // grow by 4 MB at a time - desc.m_subAllocator = &AZ::AllocatorInstance::Get(); - Create(desc); - } -}; - -////////////////////////////////////////////////////////////////////////// -// CryStringT class. -////////////////////////////////////////////////////////////////////////// -template -class CryStringT -{ -public: - ////////////////////////////////////////////////////////////////////////// - // Types compatible with STL string. - ////////////////////////////////////////////////////////////////////////// - typedef CryStringT _Self; - typedef size_t size_type; - typedef T value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - enum _npos_type - { - npos = (size_type) ~0 - }; - - ////////////////////////////////////////////////////////////////////////// - // Constructors - ////////////////////////////////////////////////////////////////////////// - CryStringT(); - -protected: - CryStringT(const CConstCharWrapper& str); //ctor for strings without memory allocations - friend class CConstCharWrapper; -public: - - CryStringT(const _Self& str); - CryStringT(const _Self& str, size_type nOff, size_type nCount); - - // Before September 2012 this constructor looked like this: - // explicit CryStringT( value_type ch, size_type nRepeat = 1 ); - // It was very error-prone, because the matching constructor - // std::string constructor is different: - // std::string( size_type nRepeat, value_type ch ); - // - // To prevent hard-to-catch bugs, we removed all calls of this - // constructor in the existing CryEngine code (in September 2012) - // and started using proper order of parameters (matching std::). - // - // To catch calls using the reversed arguments in other projects, - // we retain the previous function with reversed arguments, - // and declare it private. - CryStringT(size_type nRepeat, value_type ch); -private: - CryStringT(value_type ch, size_type nRepeat); - -public: - - CryStringT(const_str str); - CryStringT(const_str str, size_type nLength); - CryStringT(const_iterator _First, const_iterator _Last); - ~CryStringT(); - - ////////////////////////////////////////////////////////////////////////// - // STL string like interface. - ////////////////////////////////////////////////////////////////////////// - //! Operators. - size_type length() const; - size_type size() const; - bool empty() const; - void clear(); // free up the data - - //! Returns the storage currently allocated to hold the string, a value at least as large as length(). - size_type capacity() const; - - // Sets the capacity of the string to a number at least as great as a specified number. - // nCount = 0 is shrinking string to fit number of characters in it. - void reserve(size_type nCount = 0); - - _Self& append(const value_type* _Ptr); - _Self& append(const value_type* _Ptr, size_type nCount); - _Self& append(const _Self& _Str, size_type nOff, size_type nCount); - _Self& append(const _Self& _Str); - _Self& append(size_type nCount, value_type _Ch); - _Self& append(const_iterator _First, const_iterator _Last); - - _Self& assign(const_str _Ptr); - _Self& assign(const_str _Ptr, size_type nCount); - _Self& assign(const _Self& _Str, size_type off, size_type nCount); - _Self& assign(const _Self& _Str); - _Self& assign(size_type nCount, value_type _Ch); - _Self& assign(const_iterator _First, const_iterator _Last); - - value_type at(size_type index) const; - - const_iterator begin() const { return m_str; }; - const_iterator end() const { return m_str + length(); }; - - iterator begin() { return m_str; }; - iterator end() { return m_str + length(); }; - - // Following functions are commented out because they provide direct write access to - // the string and such access doesn't work properly with our current reference-count - // implementation. - // If you really need write access to your string's elements, please consider - // using CryStackStringT<> instead of CryString<>. Alternatively, you can modify - // your string by multiple calls of erase() and append(). - // Note: If you need *linear memory read* access to your string's elements, use data() - // or c_str(). If you need *linear memory write* access to your string's elements, - // use a non-string class (std::vector<>, DynArray<>, etc.) instead of CryString<>. - //value_type& at( size_type index ); - //iterator begin() { return m_str; }; - //iterator end() { return m_str+length(); }; - - //! cast to C string operator. - operator const_str() const { - return m_str; - } - - //! cast to C string. - const value_type* c_str() const { return m_str; } - const value_type* data() const { return m_str; }; - - ////////////////////////////////////////////////////////////////////////// - // string comparison. - ////////////////////////////////////////////////////////////////////////// - int compare(const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compare(const char* _Ptr) const; - int compare(const wchar_t* _Ptr) const; - int compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Case insensitive comparison - int compareNoCase(const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compareNoCase(const value_type* _Ptr) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Copies at most a specified number of characters from an indexed position in a source string to a target character array. - size_type copy(value_type* _Ptr, size_type nCount, size_type nOff = 0) const; - - void push_back(value_type _Ch) { _ConcatenateInPlace(&_Ch, 1); } - void resize(size_type nCount, value_type _Ch = ' '); - - //! simple sub-string extraction - _Self substr(size_type pos, size_type count = npos) const; - - // replace part of string. - _Self& replace(value_type chOld, value_type chNew); - _Self& replace(const_str strOld, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew, size_type count2); - _Self& replace(size_type pos, size_type count, size_type nNumChars, value_type chNew); - - // insert new elements to string. - _Self& insert(size_type nIndex, value_type ch); - _Self& insert(size_type nIndex, size_type nCount, value_type ch); - _Self& insert(size_type nIndex, const_str pstr); - _Self& insert(size_type nIndex, const_str pstr, size_type nCount); - - //! delete count characters starting at zero-based index - _Self& erase(size_type nIndex, size_type count = npos); - - //! searching (return starting index, or -1 if not found) - //! look for a single character match - //! like "C" strchr - size_type find(value_type ch, size_type pos = 0) const; - //! look for a specific sub-string - //! like "C" strstr - size_type find(const_str subs, size_type pos = 0) const; - size_type rfind(value_type ch, size_type pos = npos) const; - size_type rfind(const _Self& subs, size_type pos = 0) const; - - size_type find_first_of(value_type _Ch, size_type nOff = 0) const; - size_type find_first_of(const_str charSet, size_type nOff = 0) const; - //size_type find_first_of( const value_type* _Ptr,size_type _Off,size_type _Count ) const; - size_type find_first_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_first_not_of(value_type _Ch, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_first_not_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_last_of(value_type _Ch, size_type _Off = npos) const; - size_type find_last_of(const value_type* _Ptr, size_type _Off = npos) const; - size_type find_last_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_last_of(const _Self& _Str, size_type _Off = npos) const; - - size_type find_last_not_of(value_type _Ch, size_type _Off = npos) const; - size_type find_last_not_of(const value_type* _Ptr, size_type _Off = npos) const; - size_type find_last_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_last_not_of(const _Self& _Str, size_type _Off = npos) const; - - - void swap(_Self& _Str); - - ////////////////////////////////////////////////////////////////////////// - // overloaded operators. - ////////////////////////////////////////////////////////////////////////// - // overloaded indexing. - //value_type operator[]( size_type index ) const; // same as at() - // value_type& operator[]( size_type index ); // same as at() - - // overloaded assignment - _Self& operator=(const _Self& str); - _Self& operator=(value_type ch); - _Self& operator=(const_str str); - - template - CryStringT(const CryStackStringT& str); - -protected: - // we prohibit an implicit conversion from CryStackString to make user aware of allocation! - // -> use string(stackedString) instead - // as the private statement seems to be ignored (VS C++), we add a compile time error, see below - template - _Self& operator=(const CryStackStringT& str) - { - // we add a compile-time error as the Visual C++ compiler seems to ignore the private statement? -#if defined(__clang__) - //CLANG_TODO: clang verifies things differently -#else - static_assert(false, "Use explicit string assignment when assigning from_StackString"); -#endif - // not reached, as above will generate a compile time error - _Assign(str.c_str(), str.length()); - return *this; - } - -public: - // string concatenation - _Self& operator+=(const _Self& str); - _Self& operator+=(value_type ch); - _Self& operator+=(const_str str); - - //template friend CryStringT operator+( const CryStringT& str1, const CryStringT& str2 ); - //template friend CryStringT operator+( const CryStringT& str, value_type ch ); - //template friend CryStringT operator+( value_type ch, const CryStringT& str ); - //template friend CryStringT operator+( const CryStringT& str1, const_str str2 ); - //template friend CryStringT operator+( const_str str1, const CryStringT& str2 ); - - size_t GetAllocatedMemory() const - { - StrHeader* header = _header(); - if (header == _emptyHeader()) - { - return 0; - } - return sizeof(StrHeader) + (header->nAllocSize + 1) * sizeof(value_type); - } - - ////////////////////////////////////////////////////////////////////////// - // Extended functions. - // This functions are not in the STL string. - // They have an ATL CString interface. - ////////////////////////////////////////////////////////////////////////// - //! Format string, use (sprintf) - _Self& Format(const value_type* format, ...); - - //! Converts the string to lower-case - // This function uses the "C" locale for case-conversion (ie, A-Z only) - _Self& MakeLower(); - - //! Converts the string to upper-case - // This function uses the "C" locale for case-conversion (ie, A-Z only) - _Self& MakeUpper(); - - _Self& Trim(); - _Self& Trim(value_type ch); - _Self& Trim(const value_type* sCharSet); - - _Self& TrimLeft(); - _Self& TrimLeft(value_type ch); - _Self& TrimLeft(const value_type* sCharSet); - - _Self& TrimRight(); - _Self& TrimRight(value_type ch); - _Self& TrimRight(const value_type* sCharSet); - - _Self SpanIncluding(const_str charSet) const; - _Self SpanExcluding(const_str charSet) const; - _Self Tokenize(const_str charSet, int& nStart) const; - _Self Mid(size_type nFirst, size_type nCount = npos) const { return substr(nFirst, nCount); }; - - _Self Left(size_type count) const; - _Self Right(size_type count) const; - ////////////////////////////////////////////////////////////////////////// - - // public utilities. - static size_type _strlen(const_str str); - static size_type _strnlen(const_str str, size_type maxLen); - static const_str _strchr(const_str str, value_type c); - static const_str _strrchr(const_str str, value_type c); - static value_type* _strstr(value_type* str, const_str strSearch); - static bool _IsValidString(const_str str); - -#if defined(WIN32) || defined(WIN64) - static int _vscpf(const_str format, va_list args); -#endif - static int _vsnpf(value_type* buf, int cnt, const_str format, va_list args); - - -public: - ////////////////////////////////////////////////////////////////////////// - // Only used for debugging statistics. - ////////////////////////////////////////////////////////////////////////// - static size_t _usedMemory(ptrdiff_t size) - { - static size_t s_used_memory = 0; - s_used_memory += size; - return s_used_memory; - } - -protected: - value_type* m_str; // pointer to ref counted string data - - // String header. Immediately after this header in memory starts actual string data. - struct StrHeader - { - int nRefCount; - int nLength; - int nAllocSize; // Size of memory allocated at the end of this class. - - value_type* GetChars() { return (value_type*)(this + 1); } - void AddRef() { nRefCount++; /*InterlockedIncrement(&_header()->nRefCount);*/}; - int Release() { return --nRefCount; }; - }; - static StrHeader* _emptyHeader() - { - // Define 2 static buffers in a row. The 2nd is a dummy object to hold a single empty char string. - static StrHeader sEmptyStringBuffer[2] = { - {-1, 0, 0}, {0, 0, 0} - }; - return &sEmptyStringBuffer[0]; - } - - // implementation helpers - StrHeader* _header() const; - - void _AllocData(size_type nLen); - static void _FreeData(StrHeader* pData); - void _Free(); - void _Initialize(); - - void _Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2); - void _ConcatenateInPlace(const_str sStr, size_type nLen); - void _Assign(const_str sStr, size_type nLen); - void _MakeUnique(); - - static void _copy(value_type* dest, const value_type* src, size_type count); - static void _move(value_type* dest, const value_type* src, size_type count); - static void _set(value_type* dest, value_type ch, size_type count); -}; - -// Variant of CryStringT which does not share memory with other strings. -template -class CryStringLocalT - : public CryStringT -{ -public: - typedef CryStringT BaseType; - typedef typename BaseType::const_str const_str; - typedef typename BaseType::value_type value_type; - typedef typename BaseType::size_type size_type; - typedef typename BaseType::iterator iterator; - - CryStringLocalT() - {} - CryStringLocalT(const CryStringLocalT& str) - : BaseType(str.c_str()) - {} - CryStringLocalT(const BaseType& str) - : BaseType(str.c_str()) - {} - template - CryStringLocalT(const CryStackStringT& str) - : BaseType(str.c_str()) - {} - CryStringLocalT(const_str str) - : BaseType(str) - {} - CryStringLocalT(const_str str, size_t len) - : BaseType(str, len) - {} - CryStringLocalT(const_str begin, const_str end) - : BaseType(begin, end) - {} - CryStringLocalT(size_type nRepeat, value_type ch) - : BaseType(nRepeat, ch) - {} - - CryStringLocalT(const typename CryStringT::_Self& str, size_type nOff, size_type nCount) - : BaseType(str, nOff, nCount) - {} - - CryStringLocalT& operator=(const BaseType& str) - { - BaseType::operator=(str.c_str()); - return *this; - } - CryStringLocalT& operator=(const CryStringLocalT& str) - { - BaseType::operator=(str.c_str()); - return *this; - } - CryStringLocalT& operator=(const_str str) - { - BaseType::operator=(str); - return *this; - } - iterator begin() { return BaseType::m_str; } - using BaseType::begin; // const version - iterator end() { return BaseType::m_str + BaseType::length(); } - using BaseType::end; // const version -}; - -typedef CryStringLocalT CryStringLocal; - - -// wrapper class for creation of strings without memory allocation -// it creates a string with pointer pointing to const char* location -// destructor sets the string to empty -// NOTE: never copy a string from it, just use it as function parameters instead of const char* itself -class CConstCharWrapper -{ -public: - //passing *this is safe since the char pointer is already set and therefore is the this-ptr constructed complete enough -#pragma warning (push) -#pragma warning (disable : 4355) - CConstCharWrapper(const char* const cpString) - : cpChar(cpString) - , str(*this){AZ_Assert(cpString, "c-string parameter cannot be nullptr"); } //create stack string -#pragma warning (pop) - ~CConstCharWrapper(){str.m_str = CryStringT::_emptyHeader()->GetChars(); }//reset string - operator const CryStringT&() const { - return str; - } //cast operator to const string reference -private: - const char* const cpChar; - CryStringT str; - - char* GetCharPointer() const {return const_cast(cpChar); } //access function for string ctor - - friend class CryStringT; //both are bidirectional friends to avoid any other accesses -}; - - -//macro needed because compiler somehow cannot find the cast operator when not invoked directly -#define CONST_TEMP_STRING(a) ((const string&)CConstCharWrapper(a)) - -///////////////////////////////////////////////////////////////////////////// -// CryStringT Implementation -////////////////////////////////////////////////////////////////////////// - -template -inline typename CryStringT::StrHeader * CryStringT::_header() const -{ - AZ_Assert(m_str != nullptr, "string header is nullptr"); - return ((StrHeader*)m_str) - 1; -} - -template -inline typename CryStringT::size_type CryStringT::_strlen(const_str str) -{ - return (str == NULL) ? 0 : (size_type)::strlen(str); -} - -template <> -inline CryStringT::size_type CryStringT::_strlen(const_str str) -{ - return (str == NULL) ? 0 : (size_type)::wcslen(str); -} - -template -inline typename CryStringT::size_type CryStringT::_strnlen(const_str str, size_type maxLen) -{ - size_type len = 0; - if (str) - { - while (len < maxLen && *str != '\0') - { - len++; - str++; - } - } - return len; -} - -template -inline typename CryStringT::const_str CryStringT::_strchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::strchr(str, c); -} - -template <> -inline CryStringT::const_str CryStringT::_strchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::wcschr(str, c); -} - -template -inline typename CryStringT::const_str CryStringT::_strrchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::strrchr(str, c); -} - -template <> -inline CryStringT::const_str CryStringT::_strrchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::wcsrchr(str, c); -} - -template -inline typename CryStringT::value_type * CryStringT::_strstr(value_type * str, const_str strSearch) -{ - return (str == NULL) ? 0 : (value_type*)::strstr(str, strSearch); -} - -template <> -inline CryStringT::value_type * CryStringT::_strstr(value_type * str, const_str strSearch) -{ - return (str == NULL) ? 0 : ::wcsstr(str, strSearch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_copy(value_type* dest, const value_type* src, size_type count) -{ - if (dest != src) - { - memcpy(dest, src, count * sizeof(value_type)); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_move(value_type* dest, const value_type* src, size_type count) -{ - memmove(dest, src, count * sizeof(value_type)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_set(value_type* dest, value_type ch, size_type count) -{ - static_assert(sizeof(value_type) == sizeof(T)); - static_assert(sizeof(value_type) == 1); - memset(dest, ch, count); -} - -////////////////////////////////////////////////////////////////////////// -template <> -inline void CryStringT::_set(value_type* dest, value_type ch, size_type count) -{ - static_assert(sizeof(value_type) == sizeof(wchar_t)); - wmemset(dest, ch, count); -} - -#if defined(WIN32) || defined(WIN64) - -template<> -inline int CryStringT::_vscpf(const_str format, va_list args) -{ - return _vscprintf(format, args); -} - -template<> -inline int CryStringT::_vscpf(const_str format, va_list args) -{ - return _vscwprintf(format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return azvsnprintf(buf, cnt, format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return azvsnwprintf(buf, cnt, format, args); -} - -#else - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return vsnprintf(buf, cnt, format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return vswprintf(buf, cnt, format, args); -} - -#endif - -////////////////////////////////////////////////////////////////////////// -template -inline bool CryStringT::_IsValidString(const_str) -{ - /* - if (str == NULL) - return false; - int nLength = _strlen(str); - return !::IsBadStringPtrA(str, nLength); - */ - return true; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Assign(const_str sStr, size_type nLen) -{ - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (_header()->nRefCount > 1 || nLen > capacity()) - { - _Free(); - _AllocData(nLen); - } - // Copy characters from new string to this buffer. - _copy(m_str, sStr, nLen); - // Set new length. - _header()->nLength = aznumeric_cast(nLen); - // Make null terminated string. - m_str[nLen] = 0; - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2) -{ - size_type nLen = nLen1 + nLen2; - - if (nLen1 * 2 > nLen) - { - nLen = nLen1 * 2; - } - - if (nLen != 0) - { - if (nLen < 8) - { - nLen = 8; - } - - _AllocData(nLen); - _copy(m_str, sStr1, nLen1); - _copy(m_str + nLen1, sStr2, nLen2); - _header()->nLength = aznumeric_cast(nLen1 + nLen2); - m_str[nLen1 + nLen2] = 0; - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_ConcatenateInPlace(const_str sStr, size_type nLen) -{ - if (nLen != 0) - { - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (_header()->nRefCount > 1 || length() + nLen > capacity()) - { - StrHeader* pOldData = _header(); - _Concatenate(m_str, length(), sStr, nLen); - _FreeData(pOldData); - } - else - { - _copy(m_str + length(), sStr, nLen); - _header()->nLength = aznumeric_cast(_header()->nLength + nLen); - m_str[_header()->nLength] = 0; // Make null terminated string. - } - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_MakeUnique() -{ - if (_header()->nRefCount > 1) - { - // If string is shared, make a copy of string buffer. - StrHeader* pOldData = _header(); - // This will not free header because reference count is greater then 1. - _Free(); - // Allocate a new string buffer. - _AllocData(pOldData->nLength); - // Full copy of null terminated string. - _copy(m_str, pOldData->GetChars(), pOldData->nLength + 1); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Initialize() -{ - m_str = _emptyHeader()->GetChars(); -} - -// always allocate one extra character for '\0' termination -// assumes [optimistically] that data length will equal allocation length -template -inline void CryStringT::_AllocData(size_type nLen) -{ - AZ_Assert(nLen <= (std::numeric_limits::max)() - 1, "New string allocation size %zu is greater than the max allowed size of %d", - nLen, (std::numeric_limits::max)() - 1); // max size (enough room for 1 extra) - - if (nLen == 0) - { - _Initialize(); - } - else - { - size_type allocLen = sizeof(StrHeader) + (nLen + 1) * sizeof(value_type); - - StrHeader* pData = (StrHeader*)azmalloc(allocLen, 32, CryStringAllocator); - - _usedMemory(allocLen); // For statistics. - pData->nRefCount = 1; - m_str = pData->GetChars(); - pData->nLength = aznumeric_cast(nLen); - pData->nAllocSize = aznumeric_cast(nLen); - m_str[nLen] = 0; // null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Free() -{ - if (_header()->nRefCount >= 0) // Not empty string. - { - _FreeData(_header()); - _Initialize(); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_FreeData(StrHeader* pData) -{ - //Cry uses -1 to represent strings on the stack. - if (pData->nRefCount < 0) - { - return; - } - - if (pData->nRefCount == 0 || pData->Release() <= 0) - { - azfree((void*)pData, CryStringAllocator); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT() -{ - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const CryStringT& str) -{ - AZ_Assert(str._header()->nRefCount != 0, "Reference count input cry string should be greater than 0"); - if (str._header()->nRefCount >= 0) - { - m_str = str.m_str; - _header()->AddRef(); - } - else - { - _Initialize(); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const CryStringT& str, size_type nOff, size_type nCount) -{ - _Initialize(); - assign(str, nOff, nCount); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_str str) -{ - _Initialize(); - // Make a copy of C string. - size_type nLen = _strlen(str); - if (nLen != 0) - { - _AllocData(nLen); - _copy(m_str, str, nLen); - CRY_STRING_DEBUG(m_str) - } -} - -template -inline CryStringT::CryStringT(const CConstCharWrapper& str) -{ - _Initialize(); - m_str = const_cast(str.GetCharPointer()); -} - -template -template -inline CryStringT::CryStringT(const CryStackStringT& str) -{ - _Initialize(); - const size_type nLength = str.length(); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_str str, size_type nLength) -{ - _Initialize(); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(size_type nRepeat, value_type ch) -{ - _Initialize(); - if (nRepeat > 0) - { - _AllocData(nRepeat); - _set(m_str, ch, nRepeat); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_iterator _First, const_iterator _Last) -{ - _Initialize(); - size_type nLength = (size_type)(_Last - _First); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, _First, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::~CryStringT() -{ - _FreeData(_header()); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::length() const -{ - return _header()->nLength; -} -template -inline typename CryStringT::size_type CryStringT::size() const -{ - return _header()->nLength; -} -template -inline typename CryStringT::size_type CryStringT::capacity() const -{ - return _header()->nAllocSize; -} - -template -inline bool CryStringT::empty() const -{ - return length() == 0; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::clear() -{ - if (length() == 0) - { - return; - } - if (_header()->nRefCount >= 0) - { - _Free(); - } - else - { - resize(0); - } - AZ_Assert(length() == 0, "Cleared string should have a length of 0"); - AZ_Assert(_header()->nRefCount < 0 || capacity() == 0, - "Cleared string should have a reference count or capacity of 0"); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::reserve(size_type nCount) -{ - // Reserve of 0 is shrinking container to fit number of characters in it.. - if (nCount > capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(nCount); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _header()->nLength = pOldData->nLength; - m_str[pOldData->nLength] = 0; - _FreeData(pOldData); - } - else if (nCount == 0) - { - if (length() != capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(length()); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _FreeData(pOldData); - } - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_str _Ptr) -{ - *this += _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_str _Ptr, size_type nCount) -{ - _ConcatenateInPlace(_Ptr, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const CryStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _ConcatenateInPlace(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const CryStringT& _Str) -{ - *this += _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(size_type nCount, value_type _Ch) -{ - if (nCount > 0) - { - if (_header()->nRefCount > 1 || length() + nCount > capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(length() + nCount); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _set(m_str + pOldData->nLength, _Ch, nCount); - _FreeData(pOldData); - } - else - { - size_type nOldLength = length(); - _set(m_str + nOldLength, _Ch, nCount); - _header()->nLength = aznumeric_cast(nOldLength + nCount); - m_str[length()] = 0; // Make null terminated string. - } - } - CRY_STRING_DEBUG(m_str) - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_iterator _First, const_iterator _Last) -{ - append(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_str _Ptr) -{ - *this = _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_str _Ptr, size_type nCount) -{ - size_type len = _strnlen(_Ptr, nCount); - _Assign(_Ptr, len); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const CryStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _Assign(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const CryStringT& _Str) -{ - *this = _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(size_type nCount, value_type _Ch) -{ - if (nCount >= 1) - { - _AllocData(nCount); - _set(m_str, _Ch, nCount); - CRY_STRING_DEBUG(m_str) - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_iterator _First, const_iterator _Last) -{ - assign(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::value_type CryStringT::at(size_type index) const -{ - AZ_Assert(index >= 0 && index < length(), "index into CryString is out of range"); - return m_str[index]; -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStringT::compare(const CryStringT& _Str) const -{ - return compare(_Str.m_str); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const CryStringT& _Str) const -{ - return compare(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const CryStringT& _Str, size_type nOff, size_type nCount) const -{ - AZ_Assert(nOff < _Str.length(), "Offset into input string is larger than the index range"); - return compare(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStringT::compare(const char* _Ptr) const -{ - return strcmp(m_str, _Ptr); -} - -template -inline int CryStringT::compare(const wchar_t* _Ptr) const -{ - return wcscmp(m_str, _Ptr); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - AZ_Assert(_Pos1 < length(), "position index to compare is larger than the length of this string"); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : strncmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStringT::compareNoCase(const CryStringT& _Str) const -{ - return _stricmp(m_str, _Str.m_str); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStringT& _Str) const -{ - return compareNoCase(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStringT& _Str, size_type nOff, size_type nCount) const -{ - AZ_Assert(nOff < _Str.length(), "offset to start comparison within input string is larger than the string index range"); - return compareNoCase(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStringT::compareNoCase(const value_type* _Ptr) const -{ - return _stricmp(m_str, _Ptr); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - AZ_Assert(_Pos1 < length(), "Position to start case-insensitive search is larger the indexable range"); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : _strnicmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::copy(value_type* _Ptr, size_type nCount, size_type nOff) const -{ - AZ_Assert(nOff < length(), "Offset to copy from string to output address is outside the indexable range"); - if (nCount < 0) - { - nCount = 0; - } - if (nOff + nCount > length()) // trim to offset. - { - nCount = length() - nOff; - } - - _copy(_Ptr, m_str + nOff, nCount); - return nCount; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::resize(size_type nCount, value_type _Ch) -{ - _MakeUnique(); - if (nCount > length()) - { - size_type numToAdd = nCount - length(); - append(numToAdd, _Ch); - } - else if (nCount < length()) - { - _header()->nLength = nCount; - m_str[length()] = 0; // Make null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -//! compare helpers -template -inline bool operator==(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) == 0; } -template -inline bool operator!=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) != 0; } -template -inline bool operator<(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) > 0; } -template -inline bool operator>(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) < 0; } -template -inline bool operator<=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) >= 0; } -template -inline bool operator>=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) <= 0; } - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::operator=(value_type ch) -{ - _Assign(&ch, 1); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& string1, typename CryStringT::value_type ch) -{ - CryStringT s(string1); - s.append(1, ch); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(typename CryStringT::value_type ch, const CryStringT& str) -{ - CryStringT s; - s.reserve(str.size() + 1); - s.append(1, ch); - s.append(str); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& string1, const CryStringT& string2) -{ - CryStringT s(string1); - s.append(string2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& str1, const typename CryStringT::value_type* str2) -{ - CryStringT s(str1); - s.append(str2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const typename CryStringT::value_type* str1, const CryStringT& str2) -{ - AZ_Assert(str1 == nullptr || CryStringT::_IsValidString(str1), "Input string is not valid"); - CryStringT s; - s.reserve(CryStringT::_strlen(str1) + str2.size()); - s.append(str1); - s.append(str2); - return s; -} - -template -inline CryStringT& CryStringT::operator=(const CryStringT& str) -{ - if (m_str != str.m_str) - { - if (_header()->nRefCount < 0) - { - // Empty string. - // _Assign( str.m_str,str.length() ); - if (str._header()->nRefCount < 0) - { - ; // two empty strings... - } - else - { - m_str = str.m_str; - _header()->AddRef(); - } - } - else if (str._header()->nRefCount < 0) - { - // If source string is empty. - _Free(); - m_str = str.m_str; - } - else - { - // Copy string reference. - _Free(); - m_str = str.m_str; - _header()->AddRef(); - } - } - return *this; -} - -template -inline CryStringT& CryStringT::operator=(const_str str) -{ - AZ_Assert(str == nullptr || _IsValidString(str), "Input string is not valid"); - _Assign(str, _strlen(str)); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(const_str str) -{ - AZ_Assert(str == nullptr || _IsValidString(str), "Input string is not valid"); - _ConcatenateInPlace(str, _strlen(str)); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(value_type ch) -{ - _ConcatenateInPlace(&ch, 1); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(const CryStringT& str) -{ - _ConcatenateInPlace(str.m_str, str.length()); - return *this; -} - -//! find first single character -template -inline typename CryStringT::size_type CryStringT::find(value_type ch, size_type pos) const -{ - if (!(pos >= 0 && pos <= length())) - { - return (typename CryStringT::size_type)npos; - } - const_str str = _strchr(m_str + pos, ch); - // return npos if not found and index otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find a sub-string (like strstr) -template -inline typename CryStringT::size_type CryStringT::find(const_str subs, size_type pos) const -{ - AZ_Assert(_IsValidString(subs), "Input string is not valid"); - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - // find first matching substring - const_str str = _strstr(m_str + pos, subs); - - // return npos for not found, distance from beginning otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find last single character -template -inline typename CryStringT::size_type CryStringT::rfind(value_type ch, size_type pos) const -{ - const_str str; - if (pos == npos) - { - // find last single character - str = _strrchr(m_str, ch); - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); - } - else - { - if (pos == npos) - { - pos = length(); - } - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - value_type tmp = m_str[pos + 1]; - m_str[pos + 1] = 0; - str = _strrchr(m_str, ch); - m_str[pos + 1] = tmp; - } - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -template -inline typename CryStringT::size_type CryStringT::rfind(const CryStringT& subs, size_type pos) const -{ - size_type res = npos; - for (int i = (int)size(); i >= (int)pos; --i) - { - size_type findRes = find(subs, i); - if (findRes != npos) - { - res = findRes; - break; - } - } - return res; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(const CryStringT& _Str, size_type _Off) const -{ - return find_first_of(_Str.m_str, _Off); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(value_type _Ch, size_type nOff) const -{ - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - value_type charSet[2] = { _Ch, 0 }; - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(const_str charSet, size_type nOff) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -template <> -inline CryStringT::size_type CryStringT::find_first_of(const_str charSet, size_type nOff) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = wcspbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -//size_type find_first_not_of(const _Self& __s, size_type __pos = 0) const -//{ return find_first_not_of(__s._M_start, __pos, __s.size()); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const -//{ _STLP_FIX_LITERAL_BUG(__s) return find_first_not_of(__s, __pos, _Traits::length(__s)); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const; - -//size_type find_first_not_of(_CharT __c, size_type __pos = 0) const; - - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const value_type* _Ptr, size_type _Off) const -{ return find_first_not_of(_Ptr, _Off, _strlen(_Ptr)); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const CryStringT& _Str, size_type _Off) const -{ return find_first_not_of(_Str.m_str, _Off); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(value_type _Ch, size_type _Off) const -{ - if (_Off > length()) - { - return npos; - } - else - { - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - if (*str != _Ch) - { - return size_type(str - begin()); // Character found! - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - if (_Off > length()) - { - return npos; - } - else - { - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - const value_type* c; - for (c = charsFirst; c != charsLast; ++c) - { - if (*c == *str) - { - break; - } - } - if (c == charsLast) - { - return size_type(str - begin());// Current character not in char set. - } - } - return npos; - } -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(value_type _Ch, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // We found a character in the string which matches the input character. - if (*str == _Ch) - { - return size_type(str - begin()); // Character found! - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // We found nothing. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const value_type* _Ptr, size_type _Off) const -{ - // This function is actually a convenience alias... - // BTW: what will happeb if wchar_t is used here? - return find_last_of(_Ptr, _Off, _strlen(_Ptr)); -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - // From the character at the offset position, going to to the direction of the first character. - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; true; --str) - { - const value_type* c; - // For every character in the character set. - for (c = charsFirst; c != charsLast; ++c) - { - // If the current character matches any of the charcaters in the input string... - if (*c == *str) - { - // This is the value we must return. - return size_type(str - begin()); - } - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - // We couldn't find any character of the input string in the current string. - return npos; -} -///////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const _Self& strCharSet, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // We check every character of the input string. - for (const value_type* strInputCharacter = strCharSet.begin(); strInputCharacter != strCharSet.end(); ++strInputCharacter) - { - // If any character matches. - if (*str == *strInputCharacter) - { - // We return the position where we found it. - return size_type(str - begin()); // Character found! - } - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(value_type _Ch, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // If the current character being analyzed is different of the input character. - if (*str != _Ch) - { - // We found the last item which is not the input character before the given offset. - return size_type(str - begin()); // Character found! - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const value_type* _Ptr, size_type _Off) const -{ - // This function is actually a convenience alias... - // BTW: what will happeb if wchar_t is used here? - return find_last_not_of(_Ptr, _Off, _strlen(_Ptr)); -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; true; --str) - { - bool boFoundAny(false); - const value_type* c; - // For every character in the character set. - for (c = charsFirst; c != charsLast; ++c) - { - // If the current character matches any of the charcaters in the input string... - if (*c == *str) - { - // So we signal it was found and stop this search. - boFoundAny = true; - break; - } - } - - // Using a different solution of the other similar methods - // to make it easier to read. - // If the character being analyzed is not in the set... - if (!boFoundAny) - { - //.. we return the position where we found it. - return size_type(str - begin()); - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - // We couldn't find any character of the input string not in the character set. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const _Self& _Str, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - bool boFoundAny(false); - for (const value_type* strInputCharacter = _Str.begin(); strInputCharacter != _Str.end(); ++strInputCharacter) - { - // The character matched one of the character set... - if (*strInputCharacter == *str) - { - // So we signal it was found and stop this search. - boFoundAny = true; - break; - } - } - - // Using a different solution of the other similar methods - // to make it easier to read. - // If the character being analyzed is not in the set... - if (!boFoundAny) - { - //.. we return the position where we found it. - return size_type(str - begin()); - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT CryStringT::substr(size_type pos, size_type count) const -{ - if (pos >= length()) - { - return CryStringT(); - } - if (count == npos) - { - count = length() - pos; - } - if (pos + count > length()) - { - count = length() - pos; - } - return CryStringT(m_str + pos, count); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::erase(size_type nIndex, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - if (nCount < 0 || nCount > length() - nIndex) - { - nCount = length() - nIndex; - } - if (nCount > 0 && nIndex < length()) - { - _MakeUnique(); - size_type nNumToCopy = length() - (nIndex + nCount) + 1; - _move(m_str + nIndex, m_str + nIndex + nCount, nNumToCopy); - _header()->nLength = length() - nCount; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, value_type ch) -{ - return insert(nIndex, 1, ch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, size_type nCount, value_type ch) -{ - _MakeUnique(); - - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nNewLength = length(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nCount; - - if (capacity() < nNewLength) - { - StrHeader* pOldData = _header(); - const_str pstr = m_str; - _AllocData(nNewLength); - _copy(m_str, pstr, pOldData->nLength + 1); - _FreeData(pOldData); - } - - _move(m_str + nIndex + nCount, m_str + nIndex, (nNewLength - nIndex - nCount) + 1); - _set(m_str + nIndex, ch, nCount); - _header()->nLength = nNewLength; - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, const_str pstr, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nInsertLength = nCount; - size_type nNewLength = length(); - if (nInsertLength > 0) - { - _MakeUnique(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nInsertLength; - - if (capacity() < nNewLength) - { - StrHeader* pOldData = _header(); - const_str pOldStr = m_str; - _AllocData(nNewLength); - _copy(m_str, pOldStr, (pOldData->nLength + 1)); - _FreeData(pOldData); - } - - _move(m_str + nIndex + nInsertLength, m_str + nIndex, (nNewLength - nIndex - nInsertLength + 1)); - _copy(m_str + nIndex, pstr, nInsertLength); - _header()->nLength = nNewLength; - m_str[length()] = 0; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, const_str pstr) -{ - return insert(nIndex, pstr, _strlen(pstr)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, const_str strNew) -{ - return replace(pos, count, strNew, _strlen(strNew)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, const_str strNew, size_type count2) -{ - erase(pos, count); - insert(pos, strNew, count2); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, size_type nNumChars, value_type chNew) -{ - erase(pos, count); - insert(pos, nNumChars, chNew); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(value_type chOld, value_type chNew) -{ - if (chOld != chNew) - { - _MakeUnique(); - value_type* strend = m_str + length(); - for (value_type* str = m_str; str != strend; ++str) - { - if (*str == chOld) - { - *str = chNew; - } - } - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(const_str strOld, const_str strNew) -{ - size_type nSourceLen = _strlen(strOld); - if (nSourceLen == 0) - { - return *this; - } - size_type nReplacementLen = _strlen(strNew); - - size_type nCount = 0; - value_type* strStart = m_str; - value_type* strEnd = m_str + length(); - value_type* strTarget; - while (strStart < strEnd) - { - while ((strTarget = _strstr(strStart, strOld)) != NULL) - { - nCount++; - strStart = strTarget + nSourceLen; - } - strStart += _strlen(strStart) + 1; - } - - if (nCount > 0) - { - _MakeUnique(); - - size_type nOldLength = length(); - size_type nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount; - if (capacity() < nNewLength || _header()->nRefCount > 1) - { - StrHeader* pOldData = _header(); - const_str pstr = m_str; - _AllocData(nNewLength); - _copy(m_str, pstr, pOldData->nLength); - _FreeData(pOldData); - } - strStart = m_str; - strEnd = m_str + length(); - - while (strStart < strEnd) - { - while ((strTarget = _strstr(strStart, strOld)) != NULL) - { - size_type nBalance = nOldLength - ((size_type)(strTarget - m_str) + nSourceLen); - _move(strTarget + nReplacementLen, strTarget + nSourceLen, nBalance); - _copy(strTarget, strNew, nReplacementLen); - strStart = strTarget + nReplacementLen; - strStart[nBalance] = 0; - nOldLength += (nReplacementLen - nSourceLen); - } - strStart += _strlen(strStart) + 1; - } - _header()->nLength = nNewLength; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::swap(CryStringT& _Str) -{ - value_type* temp = _Str.m_str; - _Str.m_str = m_str; - m_str = temp; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Format(const_str format, ...) -{ - AZ_Assert(_IsValidString(format), "format c-string must not be nullptr"); - -#if defined(WIN32) || defined(WIN64) - va_list argList; - va_start(argList, format); - int n = _vscpf(format, argList); - if (n < 0) - { - n = 0; - } - resize(n); //this will actually allocate n+1 elements to accommodate the null terminator - _vsnpf(m_str, n, format, argList); - va_end(argList); - return *this; -#else - value_type temp[4096]; // Limited to 4096 characters! - va_list argList; - va_start(argList, format); - _vsnpf(temp, 4096, format, argList); - temp[4095] = '\0'; - va_end(argList); - *this = temp; - return *this; -#endif -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::MakeLower() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - const value_type c = *s; - *s = (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; // ASCII only, standard "C" locale - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::MakeUpper() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - const value_type c = *s; - *s = (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; // ASCII only, standard "C" locale - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim() -{ - return TrimRight().TrimLeft(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim(value_type ch) -{ - _MakeUnique(); - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset).TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim(const value_type* sCharSet) -{ - _MakeUnique(); - return TrimRight(sCharSet).TrimLeft(sCharSet); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet) || length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (_strchr(sCharSet, *str) != 0)) - { - str--; - } - - if (str != last) - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight() -{ - if (length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (isspace((unsigned char)*str) != 0)) - { - str--; - } - - if (str != last) // something changed? - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet)) - { - return *this; - } - - const value_type* str = m_str; - while ((*str != 0) && (_strchr(sCharSet, *str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - _move(m_str, m_str + nOff, nNewLength + 1); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft() -{ - const value_type* str = m_str; - while ((*str != 0) && (isspace((unsigned char)*str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - _move(m_str, m_str + nOff, nNewLength + 1); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -template -inline CryStringT CryStringT::Right(size_type count) const -{ - if (count == npos) - { - return CryStringT(); - } - else if (count > length()) - { - return *this; - } - - return CryStringT(m_str + length() - count, count); -} - -template -inline CryStringT CryStringT::Left(size_type count) const -{ - if (count == npos) - { - return CryStringT(); - } - else if (count > length()) - { - count = length(); - } - - return CryStringT(m_str, count); -} - -// strspn equivalent -template -inline CryStringT CryStringT::SpanIncluding(const_str charSet) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - return Left((size_type)strspn(m_str, charSet)); -} - -// strcspn equivalent -template -inline CryStringT CryStringT::SpanExcluding(const_str charSet) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - return Left((size_type)strcspn(m_str, charSet)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT CryStringT::Tokenize(const_str charSet, int& nStart) const -{ - if (nStart < 0) - { - return CryStringT(); - } - - if (!charSet) - { - return *this; - } - - const_str sPlace = m_str + nStart; - const_str sEnd = m_str + length(); - if (sPlace < sEnd) - { - int nIncluding = (int)strspn(sPlace, charSet); - - if ((sPlace + nIncluding) < sEnd) - { - sPlace += nIncluding; - int nExcluding = (int)strcspn(sPlace, charSet); - int nFrom = nStart + nIncluding; - nStart = nFrom + nExcluding + 1; - - return substr(nFrom, nExcluding); - } - } - // Return empty string. - nStart = -1; - return CryStringT(); -} - -////////////////////////////////////////////////////////////////////////// -// This code prevents std::string compiling in Win32 with STLPort -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) && !defined(WIN64) && defined(_STLP_BEGIN_NAMESPACE) && !defined(DONT_BAN_STD_STRING) -#define CRYINCLUDE_STLP_STRING_FWD_H -#define CRYINCLUDE_STLP_INTERNAL_STRING_H -namespace std -{ - //const char* __get_c_string( const CryStringT &str ) { return str.c_str(); }; - class string - { - // std::string must not be used if CryString included. - // Use string instead. - }; -} -////////////////////////////////////////////////////////////////////////// -#endif // WIN64 - -typedef CryStringT string; -typedef CryStringT wstring; - -#else // !defined(NOT_USE_CRY_STRING) - -#include // STL string -typedef std::string string; -typedef std::wstring wstring; - -#endif // !defined(NOT_USE_CRY_STRING) - -namespace AZStd -{ - template <> - struct hash<::string> - { - typedef ::string argument_type; - typedef size_t result_type; - inline result_type operator()(const argument_type& value) const - { - return hash_string(value.c_str(), value.length()); - } - - static size_t hash_string(const char* str, size_t length) - { - size_t hash = 14695981039346656037ULL; - const size_t fnvPrime = 1099511628211ULL; - const char* cptr = str; - for (; length; --length) - { - hash ^= static_cast(*cptr++); - hash *= fnvPrime; - } - return hash; - } - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_CRYSTRING_H diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h index b80666ce73..f85ddf763c 100644 --- a/Code/Legacy/CryCommon/CryThread_windows.h +++ b/Code/Legacy/CryCommon/CryThread_windows.h @@ -260,7 +260,7 @@ private: volatile bool m_bIsStarted; volatile bool m_bIsRunning; volatile bool m_bCreatedThread; - string m_name; + AZStd::string m_name; protected: virtual void Terminate() diff --git a/Code/Legacy/CryCommon/CryTypeInfo.cpp b/Code/Legacy/CryCommon/CryTypeInfo.cpp index bd2bfb8bb2..ffadc732b0 100644 --- a/Code/Legacy/CryCommon/CryTypeInfo.cpp +++ b/Code/Legacy/CryCommon/CryTypeInfo.cpp @@ -114,7 +114,7 @@ TYPE_INFO_INT(uint64) TYPE_INFO_BASIC(float) TYPE_INFO_BASIC(double) -TYPE_INFO_BASIC(string) +TYPE_INFO_BASIC(AZStd::string) const CTypeInfo&PtrTypeInfo() @@ -129,9 +129,9 @@ const CTypeInfo&PtrTypeInfo() // String conversion functions needed by TypeInfo. // bool -string ToString(bool const& val) +AZStd::string ToString(bool const& val) { - static string sTrue = "true", sFalse = "false"; + static AZStd::string sTrue = "true", sFalse = "false"; return val ? sTrue : sFalse; } @@ -151,14 +151,14 @@ bool FromString(bool& val, cstr s) } // int64 -string ToString(int64 const& val) +AZStd::string ToString(int64 const& val) { char buffer[64]; _i64toa_s(val, buffer, sizeof(buffer), 10); return buffer; } // uint64 -string ToString(uint64 const& val) +AZStd::string ToString(uint64 const& val) { char buffer[64]; sprintf_s(buffer, "%" PRIu64, val); @@ -168,7 +168,7 @@ string ToString(uint64 const& val) // long -string ToString(long const& val) +AZStd::string ToString(long const& val) { char buffer[64]; _ltoa_s(val, buffer, sizeof(buffer), 10); @@ -176,7 +176,7 @@ string ToString(long const& val) } // ulong -string ToString(unsigned long const& val) +AZStd::string ToString(unsigned long const& val) { char buffer[64]; _ultoa_s(val, buffer, sizeof(buffer), 10); @@ -233,33 +233,33 @@ bool FromString(uint64& val, const char* s) { return Clamped bool FromString(long& val, const char* s) { return ClampedIntFromString(val, s); } bool FromString(unsigned long& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(int const& val) { return ToString(long(val)); } +AZStd::string ToString(int const& val) { return ToString(long(val)); } bool FromString(int& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(unsigned int const& val) { return ToString((unsigned long)(val)); } +AZStd::string ToString(unsigned int const& val) { return ToString((unsigned long)(val)); } bool FromString(unsigned int& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(short const& val) { return ToString(long(val)); } +AZStd::string ToString(short const& val) { return ToString(long(val)); } bool FromString(short& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(unsigned short const& val) { return ToString((unsigned long)(val)); } +AZStd::string ToString(unsigned short const& val) { return ToString((unsigned long)(val)); } bool FromString(unsigned short& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(char const& val) { return ToString(long(val)); } +AZStd::string ToString(char const& val) { return ToString(long(val)); } bool FromString(char& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(wchar_t const& val) { return ToString(long(val)); } +AZStd::string ToString(wchar_t const& val) { return ToString(long(val)); } bool FromString(wchar_t& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(signed char const& val) { return ToString(long(val)); } +AZStd::string ToString(signed char const& val) { return ToString(long(val)); } bool FromString(signed char& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(unsigned char const& val) { return ToString((unsigned long)(val)); } +AZStd::string ToString(unsigned char const& val) { return ToString((unsigned long)(val)); } bool FromString(unsigned char& val, const char* s) { return ClampedIntFromString(val, s); } -string ToString(const AZ::Uuid& val) +AZStd::string ToString(const AZ::Uuid& val) { - return val.ToString(); + return val.ToString(); } bool FromString(AZ::Uuid& val, const char* s) @@ -295,7 +295,7 @@ float NumToFromString(float val, int digits, bool floating, char buffer[], int b } // double -string ToString(double const& val) +AZStd::string ToString(double const& val) { char buffer[64]; sprintf_s(buffer, "%.16g", val); @@ -307,7 +307,7 @@ bool FromString(double& val, const char* s) } // float -string ToString(float const& val) +AZStd::string ToString(float const& val) { char buffer[64]; for (int digits = 7; digits < 10; digits++) @@ -329,11 +329,11 @@ bool FromString(float& val, const char* s) // string override. template <> -void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const +void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const { // CRAIG: just a temp hack to try and get things working #if !defined(LINUX) && !defined(APPLE) - pSizer->AddString(*(string*)data); + pSizer->AddString(*(AZStd::string*)data); #endif } @@ -343,7 +343,7 @@ struct STypeInfoTest { STypeInfoTest() { - TestType(string("well")); + TestType(AZStd::string("well")); TestType(true); @@ -435,7 +435,7 @@ bool CTypeInfo::CVarInfo::GetAttr(cstr name) const return FindAttr(Attrs, name) != 0; } -bool CTypeInfo::CVarInfo::GetAttr(cstr name, string& val) const +bool CTypeInfo::CVarInfo::GetAttr(cstr name, AZStd::string& val) const { cstr valstr = FindAttr(Attrs, name); if (!valstr) @@ -459,7 +459,7 @@ bool CTypeInfo::CVarInfo::GetAttr(cstr name, string& val) const end--; } } - val = string(valstr, end - valstr); + val = AZStd::string(valstr, end - valstr); return true; } @@ -735,7 +735,7 @@ bool CStructInfo::ToValue(const void* data, void* value, const CTypeInfo& typeVa Nameless , 1, ,2 1,2 ; */ -static void StripCommas(string& str) +static void StripCommas(AZStd::string& str) { size_t nLast = str.size(); while (nLast > 0 && str[nLast - 1] == ',') @@ -745,9 +745,9 @@ static void StripCommas(string& str) str.resize(nLast); } -string CStructInfo::ToString(const void* data, FToString flags, const void* def_data) const +AZStd::string CStructInfo::ToString(const void* data, FToString flags, const void* def_data) const { - string str; // Return str. + AZStd::string str; // Return str. for (int i = 0; i < Vars.size(); i++) { @@ -763,7 +763,7 @@ string CStructInfo::ToString(const void* data, FToString flags, const void* def_ str += ","; } - string substr = var.ToString(data, FToString(flags).Sub(0), def_data); + AZStd::string substr = var.ToString(data, FToString(flags).Sub(0), def_data); if (flags.SkipDefault && substr.empty()) { @@ -772,7 +772,7 @@ string CStructInfo::ToString(const void* data, FToString flags, const void* def_ if (flags.NamedFields) { - if (*str) + if (*str.c_str()) { str += ","; } @@ -782,7 +782,7 @@ string CStructInfo::ToString(const void* data, FToString flags, const void* def_ str += "="; } } - if (substr.find(',') != string::npos || substr.find('=') != string::npos) + if (substr.find(',') != AZStd::string::npos || substr.find('=') != AZStd::string::npos) { // Encase nested composite types in parens. str += "("; @@ -811,7 +811,7 @@ string CStructInfo::ToString(const void* data, FToString flags, const void* def_ // Retrieve and return one subelement from src, advancing the pointer. // Copy to tempstr if necessary. -typedef CryStackStringT CTempStr; +typedef AZStd::fixed_string<256> CTempStr; void ParseElement(cstr& src, cstr& varname, cstr& val, CTempStr& tempstr) { @@ -882,21 +882,24 @@ void ParseElement(cstr& src, cstr& varname, cstr& val, CTempStr& tempstr) if (*end) { // Must copy sub string to temp. - val = (cstr)tempstr + (val - varname); - eq = (cstr)tempstr + (eq - varname); - varname = tempstr.assign(varname, end); + val = tempstr.c_str() + (val - varname); + eq = tempstr.c_str() + (eq - varname); + tempstr.assign(varname, end); + varname = tempstr.c_str(); non_const(*eq) = 0; } else { // Copy just varname to temp, return val in place. - varname = tempstr.assign(varname, eq); + tempstr.assign(varname, eq); + varname = tempstr.c_str(); } } else if (*end) { // Must copy sub string to temp. - val = tempstr.assign(val, end); + tempstr.assign(val, end); + val = tempstr.c_str(); } // Else can return val without copying. @@ -963,7 +966,7 @@ void CStructInfo::SwapEndian(void* data, size_t nCount, bool bWriting) const { non_const(*this).MakeEndianDesc(); - if (EndianDesc.length() == 1 && !HasBitfields && EndianDescSize(EndianDesc) == Size) + if (EndianDesc.length() == 1 && !HasBitfields && EndianDescSize(EndianDesc.c_str()) == Size) { // Optimised array swap. size_t nElems = (EndianDesc[0u] & 0x3F) * nCount; @@ -989,7 +992,7 @@ void CStructInfo::SwapEndian(void* data, size_t nCount, bool bWriting) const // First swap bits. // Iterate the endian descriptor. void* step = data; - for (cstr desc = EndianDesc; *desc; desc++) + for (cstr desc = EndianDesc.c_str(); *desc; desc++) { size_t nElems = *desc & 0x3F; switch (*desc & 0xC0) @@ -1064,7 +1067,7 @@ void CStructInfo::MakeEndianDesc() // Struct-computed endian desc. CStructInfo const& infoSub = static_cast(var.Type); non_const(infoSub).MakeEndianDesc(); - subdesc = infoSub.EndianDesc; + subdesc = infoSub.EndianDesc.c_str(); if (!*subdesc) { // No swapping. diff --git a/Code/Legacy/CryCommon/CryTypeInfo.h b/Code/Legacy/CryCommon/CryTypeInfo.h index 43b9d3e5b9..0bd734492a 100644 --- a/Code/Legacy/CryCommon/CryTypeInfo.h +++ b/Code/Legacy/CryCommon/CryTypeInfo.h @@ -17,13 +17,12 @@ #include #include "CryArray.h" #include "Options.h" -#include "CryString.h" #include "TypeInfo_decl.h" class ICrySizer; class CCryName; -string ToString(CCryName const& val); +AZStd::string ToString(CCryName const& val); bool FromString(CCryName& val, const char* s); //--------------------------------------------------------------------------- @@ -85,7 +84,7 @@ struct CTypeInfo // // Convert value to string. - virtual string ToString([[maybe_unused]] const void* data, [[maybe_unused]] FToString flags = 0, [[maybe_unused]] const void* def_data = 0) const + virtual AZStd::string ToString([[maybe_unused]] const void* data, [[maybe_unused]] FToString flags = 0, [[maybe_unused]] const void* def_data = 0) const { return ""; } // Write value from string, return success. @@ -180,7 +179,7 @@ struct CTypeInfo assert(!bBitfield); return Type.FromString((char*)base + Offset, str, flags); } - string ToString(const void* base, FToString flags = 0, const void* def_base = 0) const + AZStd::string ToString(const void* base, FToString flags = 0, const void* def_base = 0) const { assert(!bBitfield); return Type.ToString((const char*)base + Offset, flags, def_base ? (const char*)def_base + Offset : 0); @@ -189,7 +188,7 @@ struct CTypeInfo // Attribute access. Not fast. bool GetAttr(cstr name) const; bool GetAttr(cstr name, float& val) const; - bool GetAttr(cstr name, string& val) const; + bool GetAttr(cstr name, AZStd::string& val) const; // Comment, excluding attributes. cstr GetComment() const; diff --git a/Code/Legacy/CryCommon/IEntityRenderState.h b/Code/Legacy/CryCommon/IEntityRenderState.h index 9ee974b7fc..e9f041ba17 100644 --- a/Code/Legacy/CryCommon/IEntityRenderState.h +++ b/Code/Legacy/CryCommon/IEntityRenderState.h @@ -205,7 +205,7 @@ struct IRenderNode // Debug info about object. virtual const char* GetName() const = 0; virtual const char* GetEntityClassName() const = 0; - virtual string GetDebugString([[maybe_unused]] char type = 0) const { return ""; } + virtual AZStd::string GetDebugString([[maybe_unused]] char type = 0) const { return ""; } virtual float GetImportance() const { return 1.f; } // Description: diff --git a/Code/Legacy/CryCommon/IFont.h b/Code/Legacy/CryCommon/IFont.h index c95182abd7..41e9f5653a 100644 --- a/Code/Legacy/CryCommon/IFont.h +++ b/Code/Legacy/CryCommon/IFont.h @@ -16,7 +16,6 @@ #include #include -#include #include #include @@ -101,7 +100,7 @@ struct ICryFont // All font names separated by , // Example: // "console,default,hud" - virtual string GetLoadedFontNames() const = 0; + virtual AZStd::string GetLoadedFontNames() const = 0; //! \brief Called when the g_language (current language) setting changes. //! @@ -264,7 +263,7 @@ struct IFFont // Description: // Wraps text based on specified maximum line width (UTF-8) - virtual void WrapText(string& result, float maxWidth, const char* pStr, const STextDrawContext& ctx) = 0; + virtual void WrapText(AZStd::string& result, float maxWidth, const char* pStr, const STextDrawContext& ctx) = 0; // Description: // Puts the memory used by this font into the given sizer. @@ -338,7 +337,7 @@ struct FontFamily FontFamily& operator=(const FontFamily&) = delete; FontFamily& operator=(const FontFamily&&) = delete; - string familyName; + AZStd::string familyName; IFFont* normal; IFFont* bold; IFFont* italic; diff --git a/Code/Legacy/CryCommon/IRenderer.h b/Code/Legacy/CryCommon/IRenderer.h index d3557129bf..254f1933de 100644 --- a/Code/Legacy/CryCommon/IRenderer.h +++ b/Code/Legacy/CryCommon/IRenderer.h @@ -17,7 +17,6 @@ #include "Cry_Matrix33.h" #include "Cry_Color.h" #include "smartptr.h" -#include "StringUtils.h" #include // <> required for Interfuscator #include "smartptr.h" #include @@ -1449,7 +1448,7 @@ struct IRenderer virtual const char* EF_GetShaderMissLogPath() = 0; ///////////////////////////////////////////////////////////////////////////////// - virtual string* EF_GetShaderNames(int& nNumShaders) = 0; + virtual AZStd::string* EF_GetShaderNames(int& nNumShaders) = 0; // Summary: // Reloads file virtual bool EF_ReloadFile (const char* szFileName) = 0; diff --git a/Code/Legacy/CryCommon/ISerialize.h b/Code/Legacy/CryCommon/ISerialize.h index 0476237903..84e665850f 100644 --- a/Code/Legacy/CryCommon/ISerialize.h +++ b/Code/Legacy/CryCommon/ISerialize.h @@ -179,28 +179,16 @@ struct SSerializeString void resize(int sz) { m_str.resize(sz); } void reserve(int sz) { m_str.reserve(sz); } - void set_string(const string& s) + void set_string(const AZStd::string& s) { m_str.assign(s.begin(), s.size()); } -#if !defined(RESOURCE_COMPILER) - void set_string(const CryStringLocal& s) - { - m_str.assign(s.begin(), s.size()); - } -#endif - template - void set_string(const CryFixedStringT& s) - { - m_str.assign(s.begin(), s.size()); - } - - operator const string () const { + operator const AZStd::string() const { return m_str; } private: - string m_str; + AZStd::string m_str; }; // the ISerialize is intended to be implemented by objects that need @@ -308,7 +296,7 @@ public: m_pSerialize->Value(szName, value); } - void Value(const char* szName, string& value, int policy) + void Value(const char* szName, AZStd::string& value, int policy) { if (IsWriting()) { @@ -327,11 +315,11 @@ public: value = serializeString.c_str(); } } - ILINE void Value(const char* szName, string& value) + ILINE void Value(const char* szName, AZStd::string& value) { Value(szName, value, 0); } - void Value(const char* szName, const string& value, int policy) + void Value(const char* szName, const AZStd::string& value, int policy) { if (IsWriting()) { @@ -343,76 +331,7 @@ public: assert(0 && "This function can only be used for Writing"); } } - ILINE void Value(const char* szName, const string& value) - { - Value(szName, value, 0); - } - template - void Value(const char* szName, CryStringLocalT& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - if (GetSerializationTarget() != eST_Script) - { - value = ""; - } - - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->ReadStringValue(szName, serializeString, policy); - value = serializeString.c_str(); - } - } - template - ILINE void Value(const char* szName, CryStringLocalT& value) - { - Value(szName, value, 0); - } - template - void Value(const char* szName, const CryStringLocalT& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - assert(0 && "This function can only be used for Writing"); - } - } - template - ILINE void Value(const char* szName, const CryStringLocalT& value) - { - Value(szName, value, 0); - } - template - void Value(const char* szName, CryFixedStringT& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - if (GetSerializationTarget() != eST_Script) - { - value = ""; - } - - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->ReadStringValue(szName, serializeString, policy); - assert(serializeString.length() <= S); - value = serializeString.c_str(); - } - } - template - ILINE void Value(const char* szName, CryFixedStringT& value) + ILINE void Value(const char* szName, const AZStd::string& value) { Value(szName, value, 0); } @@ -493,7 +412,7 @@ public: m_pSerialize->ValueWithDefault(name, x, defaultValue); } - void ValueWithDefault(const char* szName, string& value, const string& defaultValue) + void ValueWithDefault(const char* szName, AZStd::string& value, const AZStd::string& defaultValue) { static SSerializeString defaultSerializeString; @@ -919,34 +838,13 @@ public: return CSerializeWrapper(m_pSerialize); } - SSerializeString& SetSharedSerializeString(const string& str) + SSerializeString& SetSharedSerializeString(const AZStd::string& str) { static SSerializeString serializeString; serializeString.set_string(str); return serializeString; } -#if !defined(RESOURCE_COMPILER) - SSerializeString& SetSharedSerializeString(const CryStringLocal& str) - { - - - static SSerializeString serializeString; - serializeString.set_string(str); - return serializeString; - } -#endif - - template - SSerializeString& SetSharedSerializeString(const CryFixedStringT& str) - { - - - static SSerializeString serializeString; - serializeString.set_string(str); - return serializeString; - } - private: TISerialize* m_pSerialize; }; diff --git a/Code/Legacy/CryCommon/IShader.h b/Code/Legacy/CryCommon/IShader.h index 3a49e4d1ac..978da1a77f 100644 --- a/Code/Legacy/CryCommon/IShader.h +++ b/Code/Legacy/CryCommon/IShader.h @@ -25,7 +25,6 @@ #include "Cry_Matrix33.h" #include "Cry_Color.h" #include "smartptr.h" -#include "StringUtils.h" #include // <> required for Interfuscator #include "smartptr.h" #include "VertexFormats.h" @@ -1394,12 +1393,12 @@ struct IRenderTarget struct STexSamplerFX { #if SHADER_REFLECT_TEXTURE_SLOTS - string m_szUIName; - string m_szUIDescription; + AZStd::string m_szUIName; + AZStd::string m_szUIDescription; #endif - string m_szName; - string m_szTexture; + AZStd::string m_szName; + AZStd::string m_szTexture; union { @@ -1708,7 +1707,7 @@ struct SEfResTextureExt //------------------------------------------------------------------------------ struct SEfResTexture { - string m_Name; + AZStd::string m_Name; bool m_bUTile; bool m_bVTile; signed char m_Filter; @@ -1890,7 +1889,7 @@ struct SEfResTexture struct SBaseShaderResources { AZStd::vector m_ShaderParams; - string m_TexturePath; + AZStd::string m_TexturePath; const char* m_szMaterialName; float m_AlphaRef; @@ -2146,8 +2145,8 @@ struct SShaderTextureSlot m_TexType = eTT_MaxTexType; } - string m_Name; - string m_Description; + AZStd::string m_Name; + AZStd::string m_Description; byte m_TexType; // 2D, 3D, Cube etc.. void GetMemoryUsage(ICrySizer* pSizer) const @@ -2726,7 +2725,7 @@ protected: virtual ~ILightAnimWrapper() {} protected: - string m_name; + AZStd::string m_name; IAnimNode* m_pNode; }; @@ -3256,12 +3255,12 @@ enum EGrNodeIOSemantic struct SShaderGraphFunction { - string m_Data; - string m_Name; - std::vector inParams; - std::vector outParams; - std::vector szInTypes; - std::vector szOutTypes; + AZStd::string m_Data; + AZStd::string m_Name; + std::vector inParams; + std::vector outParams; + std::vector szInTypes; + std::vector szOutTypes; }; struct SShaderGraphNode @@ -3269,8 +3268,8 @@ struct SShaderGraphNode EGrNodeType m_eType; EGrNodeFormat m_eFormat; EGrNodeIOSemantic m_eSemantic; - string m_CustomSemantics; - string m_Name; + AZStd::string m_CustomSemantics; + AZStd::string m_Name; bool m_bEditable; bool m_bWasAdded; SShaderGraphFunction* m_pFunction; @@ -3296,7 +3295,7 @@ struct SShaderGraphBlock { EGrBlockType m_eType; EGrBlockSamplerType m_eSamplerType; - string m_ClassName; + AZStd::string m_ClassName; FXShaderGraphNodes m_Nodes; ~SShaderGraphBlock(); diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index d934995b4d..973196ac4c 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -946,7 +946,7 @@ struct ISystem // If m_GraphicsSettingsMap is defined (in Graphics Settings Dialog box), fills in mapping based on sys_spec_Full // Arguments: // sPath - e.g. "Game/Config/CVarGroups" - virtual void AddCVarGroupDirectory(const string& sPath) = 0; + virtual void AddCVarGroupDirectory(const AZStd::string& sPath) = 0; // Summary: // Saves system configuration. diff --git a/Code/Legacy/CryCommon/IXml.h b/Code/Legacy/CryCommon/IXml.h index b722da78e3..e4cb752234 100644 --- a/Code/Legacy/CryCommon/IXml.h +++ b/Code/Legacy/CryCommon/IXml.h @@ -94,12 +94,12 @@ void testXml(bool bReuseStrings) // Summary: // Special string wrapper for xml nodes. class XmlString - : public string + : public AZStd::string { public: XmlString() {}; XmlString(const char* str) - : string(str) {}; + : AZStd::string(str) {}; operator const char*() const { return c_str(); diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 2dea83925d..e47d16d1bc 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -329,9 +329,6 @@ inline uint32 GetTickCount() #define _wtof(str) wcstod(str, 0) -// Need to include this before using it's used in finddata, but after the strnicmp definition -#include "CryString.h" - typedef struct __finddata64_t { //!< atributes set by find request diff --git a/Code/Legacy/CryCommon/LyShine/UiBase.h b/Code/Legacy/CryCommon/LyShine/UiBase.h index 274618821e..af6314be2c 100644 --- a/Code/Legacy/CryCommon/LyShine/UiBase.h +++ b/Code/Legacy/CryCommon/LyShine/UiBase.h @@ -65,6 +65,5 @@ namespace AZ AZ_TYPE_INFO_SPECIALIZE(ColorF, "{63782551-A309-463B-A301-3A360800DF1E}"); AZ_TYPE_INFO_SPECIALIZE(ColorB, "{6F0CC2C0-0CC6-4DBF-9297-B043F270E6A4}"); AZ_TYPE_INFO_SPECIALIZE(Vec4, "{CAC9510C-8C00-41D4-BC4D-2C6A8136EB30}"); - AZ_TYPE_INFO_SPECIALIZE(CryStringT, "{835199FB-292B-4DB3-BC7C-366E356300FA}"); } // namespace AZ diff --git a/Code/Legacy/CryCommon/LyShine/UiSerializeHelpers.h b/Code/Legacy/CryCommon/LyShine/UiSerializeHelpers.h index 05289c6c50..3ad3de2d3d 100644 --- a/Code/Legacy/CryCommon/LyShine/UiSerializeHelpers.h +++ b/Code/Legacy/CryCommon/LyShine/UiSerializeHelpers.h @@ -22,154 +22,6 @@ namespace LyShine { - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to an AZStd::String - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromCryStringToAzString( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a string or not valid - AZ_Error("Serialization", false, "Cannot get string data for element %s.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int newElementIndex = classElement.AddElement(context, subElementName); - if (newElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", subElementName); - return false; - } - - AZStd::string newData(oldData.c_str()); - classElement.GetSubElement(newElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to a char - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromCryStringToChar( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName, - char defaultValue) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a CryString - AZ_Error("Serialization", false, "Element %s is not a CryString.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int newElementIndex = classElement.AddElement(context, subElementName); - if (newElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", subElementName); - return false; - } - - char newData = (oldData.empty()) ? defaultValue : oldData[0]; - classElement.GetSubElement(newElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to a simple asset reference - // Inline to avoid DLL linkage issues - template - inline bool ConvertSubElementFromCryStringToAssetRef( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a CryString - AZ_Error("Serialization", false, "Element %s is not a CryString.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int simpleAssetRefIndex = classElement.AddElement >(context, subElementName); - if (simpleAssetRefIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for simpleAssetRefIndex %s", subElementName); - return false; - } - - // add a sub element for the SimpleAssetReferenceBase within the SimpleAssetReference - AZ::SerializeContext::DataElementNode& simpleAssetRefNode = classElement.GetSubElement(simpleAssetRefIndex); - int simpleAssetRefBaseIndex = simpleAssetRefNode.AddElement(context, "BaseClass1"); - if (simpleAssetRefBaseIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element BaseClass1"); - return false; - } - - // add a sub element for the AssetPath within the SimpleAssetReference - AZ::SerializeContext::DataElementNode& simpleAssetRefBaseNode = simpleAssetRefNode.GetSubElement(simpleAssetRefBaseIndex); - int assetPathElementIndex = simpleAssetRefBaseNode.AddElement(context, "AssetPath"); - if (assetPathElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element AssetPath"); - return false; - } - - AZStd::string newData(oldData.c_str()); - simpleAssetRefBaseNode.GetSubElement(assetPathElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - //////////////////////////////////////////////////////////////////////////////////////////////// // Helper function to VersionConverter to convert an AZStd::string field to a simple asset reference // Inline to avoid DLL linkage issues diff --git a/Code/Legacy/CryCommon/StlUtils.h b/Code/Legacy/CryCommon/StlUtils.h index 2438ee9f7b..d7e5697593 100644 --- a/Code/Legacy/CryCommon/StlUtils.h +++ b/Code/Legacy/CryCommon/StlUtils.h @@ -494,7 +494,7 @@ namespace stl //! Specialization of string to const char cast. template <> - inline const char* constchar_cast(const string& type) + inline const char* constchar_cast(const AZStd::string& type) { return type.c_str(); } diff --git a/Code/Legacy/CryCommon/StringUtils.h b/Code/Legacy/CryCommon/StringUtils.h deleted file mode 100644 index ffd1001f95..0000000000 --- a/Code/Legacy/CryCommon/StringUtils.h +++ /dev/null @@ -1,1358 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef _CRY_ENGINE_STRING_UTILS_HDR_ -#define _CRY_ENGINE_STRING_UTILS_HDR_ - -#pragma once - -#include "CryString.h" -#include -#include // std::replace, std::min -#include "UnicodeFunctions.h" -#include "UnicodeIterator.h" -#include - -#if !defined(RESOURCE_COMPILER) -# include "CryCrc32.h" -#endif - -#if defined(LINUX) || defined(APPLE) -# include -#endif - -namespace CryStringUtils -{ - // Convert a single ASCII character to lower case, this is compatible with the standard "C" locale (ie, only A-Z). - inline char toLowerAscii(char c) - { - return (c >= 'A' && c <= 'Z') ? (c - 'A' + 'a') : c; - } - - // Convert a single ASCII character to upper case, this is compatible with the standard "C" locale (ie, only A-Z). - inline char toUpperAscii(char c) - { - return (c >= 'a' && c <= 'z') ? (c - 'a' + 'A') : c; - } -} - -// cry_strXXX() and CryStringUtils_Internal::strXXX(): -// -// The functions copy characters from src to dst one by one until any of -// the following conditions is met: -// 1) the end of the destination buffer (minus one character) is reached. -// 2) the end of the source buffer is reached. -// 3) zero character is found in the source buffer. -// -// When any of 1), 2), 3) happens, the functions write the terminating zero -// character to the destination buffer and return. -// -// The functions guarantee writing the terminating zero character to the -// destination buffer (if the buffer can fit at least one character). -// -// The functions return false when a null pointer is passed or when -// clamping happened (i.e. when the end of the destination buffer is -// reached but the source has some characters left). - -namespace CryStringUtils_Internal -{ - template - inline bool strcpy_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes) - { - COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); - - if (!dst || dst_size_in_bytes < sizeof(TChar)) - { - return false; - } - - if (!src || src_size_in_bytes < sizeof(TChar)) - { - dst[0] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes / sizeof(TChar); - const size_t n = (std::min)(dst_size_in_bytes / sizeof(TChar) - 1, src_n); - - for (size_t i = 0; i < n; ++i) - { - dst[i] = src[i]; - if (!src[i]) - { - return true; - } - } - - dst[n] = 0; - return n >= src_n || src[n] == 0; - } - - template - inline bool strcat_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes) - { - COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); - - if (!dst || dst_size_in_bytes < sizeof(TChar)) - { - return false; - } - - const size_t dst_n = dst_size_in_bytes / sizeof(TChar) - 1; - - size_t dst_len = 0; - while (dst_len < dst_n && dst[dst_len]) - { - ++dst_len; - } - - if (!src || src_size_in_bytes < sizeof(TChar)) - { - dst[dst_len] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes / sizeof(TChar); - const size_t n = (std::min)(dst_n - dst_len, src_n); - TChar* dst_ptr = &dst[dst_len]; - - for (size_t i = 0; i < n; ++i) - { - *dst_ptr++ = src[i]; - if (!src[i]) - { - return true; - } - } - - *dst_ptr = 0; - return n >= src_n || src[n] == 0; - } - - // Compares characters as case-sensitive, locale agnostic. - template - struct SCharComparatorCaseSensitive - { - static bool IsEqual(CharType a, CharType b) - { - return a == b; - } - }; - - // Compares characters as case-insensitive, uses the standard "C" locale. - template - struct SCharComparatorCaseInsensitive - { - static bool IsEqual(CharType a, CharType b) - { - if (a < 0x80 && b < 0x80) - { - a = (CharType)CryStringUtils::toLowerAscii(char(a)); - b = (CharType)CryStringUtils::toLowerAscii(char(b)); - } - return a == b; - } - }; - - // Template for wildcard matching, UCS code-point aware. - // Can be used for ASCII and Unicode (UTF-8/UTF-16/UTF-32), but not for ANSI. - // ? will match exactly one code-point. - // * will match zero or more code-points. - template class CharComparator, class CharType> - inline bool MatchesWildcards_Tpl(const CharType* pStr, const CharType* pWild) - { - const CharType* savedStr = 0; - const CharType* savedWild = 0; - - while ((*pStr) && (*pWild != '*')) - { - if (!CharComparator::IsEqual(*pWild, *pStr) && (*pWild != '?')) - { - return false; - } - - // We need special handling of '?' for Unicode - if (*pWild == '?' && *pStr > 127) - { - Unicode::CIterator utf(pStr, pStr + 4); - if (utf.IsAtValidCodepoint()) - { - pStr = (++utf).GetPosition(); - --pStr; - } - } - - ++pWild; - ++pStr; - } - - while (*pStr) - { - if (*pWild == '*') - { - if (!*++pWild) - { - return true; - } - savedWild = pWild; - savedStr = pStr + 1; - } - else if (CharComparator::IsEqual(*pWild, *pStr) || (*pWild == '?')) - { - // We need special handling of '?' for Unicode - if (*pWild == '?' && *pStr > 127) - { - Unicode::CIterator utf(pStr, pStr + 4); - if (utf.IsAtValidCodepoint()) - { - pStr = (++utf).GetPosition(); - --pStr; - } - } - - ++pWild; - ++pStr; - } - else - { - pWild = savedWild; - pStr = savedStr++; - } - } - - while (*pWild == '*') - { - ++pWild; - } - - return *pWild == 0; - } -} // namespace CryStringUtils_Internal - - -inline bool cry_strcpy(char* const dst, size_t const dst_size_in_bytes, const char* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_strcpy(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template -inline bool cry_strcpy(char(&dst)[SIZE_IN_CHARS], const char* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, SIZE_IN_CHARS, src, (size_t)-1); -} - -template -inline bool cry_strcpy(char(&dst)[SIZE_IN_CHARS], const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, SIZE_IN_CHARS, src, src_size_in_bytes); -} - - -inline bool cry_wstrcpy(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_wstrcpy(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template -inline bool cry_wstrcpy(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, (size_t)-1); -} - -template -inline bool cry_wstrcpy(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, src_size_in_bytes); -} - - -inline bool cry_strcat(char* const dst, size_t const dst_size_in_bytes, const char* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_strcat(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template -inline bool cry_strcat(char(&dst)[SIZE_IN_CHARS], const char* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, SIZE_IN_CHARS, src, (size_t)-1); -} - -template -inline bool cry_strcat(char(&dst)[SIZE_IN_CHARS], const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, SIZE_IN_CHARS, src, src_size_in_bytes); -} - - -inline bool cry_wstrcat(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_wstrcat(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template -inline bool cry_wstrcat(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, (size_t)-1); -} - -template -inline bool cry_wstrcat(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, src_size_in_bytes); -} - - -namespace CryStringUtils -{ - enum - { - CRY_DEFAULT_HASH_SEED = 40503, // This is a large 16 bit prime number (perfect for seeding) - CRY_EMPTY_STR_HASH = 3350499166U, // HashString("") - }; - - // removes the extension from the file path - // \param szFilePath the source path - inline char* StripFileExtension(char* szFilePath) - { - for (char* p = szFilePath + (int)strlen(szFilePath) - 1; p >= szFilePath; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return nullptr; - case '.': - // there's an extension in this file name - *p = '\0'; - return p + 1; - } - } - // it seems the file name is a pure name, without path or extension - return nullptr; - } - - - // returns the parent directory of the given file or directory. - // the returned path is WITHOUT the trailing slash - // if the input path has a trailing slash, it's ignored - // nGeneration - is the number of parents to scan up - // Note: A drive specifier (if any) will always be kept (Windows-specific). - template - StringCls GetParentDirectory(const StringCls& strFilePath, int nGeneration = 1) - { - for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent - p >= strFilePath.c_str(); - --p) - { - switch (*p) - { - case ':': - return StringCls(strFilePath.c_str(), p); - break; - case '/': - case '\\': - // we've reached a path separator - return everything before it. - if (!--nGeneration) - { - return StringCls(strFilePath.c_str(), p); - } - break; - } - } - ; - // the file name is a pure name, without path or extension - return StringCls(); - } - - /*! - // converts all chars to lower case - */ - inline string ToLower(const string& str) - { - string temp = str; - -#ifndef NOT_USE_CRY_STRING - temp.MakeLower(); -#else - std::transform(temp.begin(), temp.end(), temp.begin(), toLowerAscii); // STL MakeLower -#endif - - return temp; - } - - /// Converts the single character to lower case. - /*! - \param c source character to convert to lower case if possible - \return the lower case character equivalent if possible - */ - inline char ToLower(char c) - { - return ((c <= 'Z') && (c >= 'A')) ? c + ('a' - 'A') : c; - } - - /// Converts the specified character into lowercase. - /*! - \param c the character to convert to lowercase - \return the lowercase character - */ - // Converts all ASCII characters to upper case. - // Note: Any non-ASCII characters are left unchanged. - // This function is ASCII-only and locale agnostic. - inline string toUpper (const string& str) - { - string temp = str; - -#ifndef NOT_USE_CRY_STRING - temp.MakeUpper(); -#else - std::transform(temp.begin(), temp.end(), temp.begin(), toUpperAscii); // STL MakeLower -#endif - - return temp; - } - - // searches and returns the pointer to the extension of the given file - /*! - \param szFileName source filename to search - // This function is Unicode agnostic and locale agnostic. - */ - inline const char* FindExtension(const char* szFileName) - { - const char* szEnd = szFileName + (int)strlen(szFileName); - for (const char* p = szEnd - 1; p >= szFileName; --p) - { - if (*p == '.') - { - return p + 1; - } - } - - return szEnd; - } - - // searches and returns the pointer to the file name in the given file path - /*! - \param szFilePath source path to search - */ - inline const char* FindFileNameInPath(const char* szFilePath) - { - for (const char* p = szFilePath + (int)strlen(szFilePath) - 1; p >= szFilePath; --p) - { - if (*p == '\\' || *p == '/') - { - return p + 1; - } - } - return szFilePath; - } - - // works like strstr, but is case-insensitive - /*! - \param szString the source string - \param szSubstring the sub-string to look for - */ - inline const char* stristr(const char* szString, const char* szSubstring) - { - int nSuperstringLength = (int)strlen(szString); - int nSubstringLength = (int)strlen(szSubstring); - - for (int nSubstringPos = 0; nSubstringPos <= nSuperstringLength - nSubstringLength; ++nSubstringPos) - { - if (_strnicmp(szString + nSubstringPos, szSubstring, nSubstringLength) == 0) - { - return szString + nSubstringPos; - } - } - return nullptr; - } - - -#ifndef NOT_USE_CRY_STRING - - /* - \param strPath the path to "unify" - */ - inline void UnifyFilePath(stack_string& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - - template - inline void UnifyFilePath(CryStackStringT& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - - /// Replaces backslashes with forward slashes and transforms string to lowercase. - /*! - \param strPath the path to "unify" - */ - inline void UnifyFilePath(string& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - -#endif - - // converts the number to a string - /* - \param nNumber an unsigned number - \return the unsigned number as a string - */ - inline string ToString(unsigned nNumber) - { - char szNumber[16]; - sprintf_s(szNumber, "%u", nNumber); - return szNumber; - } - - /// Converts the number to a string. - /*! - \param nNumber an signed integer - \return the signed integer as a string - */ - inline string ToString(signed int nNumber) - { - char szNumber[16]; - sprintf_s(szNumber, "%d", nNumber); - return szNumber; - } - - /// Converts the floating point number to a string. - /*! - \param nNumber a floating point number - \return the floating point number as a string - */ - inline string ToString(float nNumber) - { - char szNumber[128]; - sprintf_s(szNumber, "%f", nNumber); - return szNumber; - } - - /// Converts the boolean value to a string ("0" or "1"). - /*! - \param nNumber an unsigned number - \return the bool as a string (either "1" or "0") - */ - inline string ToString(bool nNumber) - { - char szNumber[4]; - sprintf_s(szNumber, "%i", (int)nNumber); - return szNumber; - } - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_MATRIX44_H - /// Converts a Matrix44 to a string. - /*! - \param m A matrix of type Matrix44 - \return the matrix in the format {0,0,0,0}{0,0,0,0}{0,0,0,0}{0,0,0,0} - */ - inline string ToString(const Matrix44& m) - { - char szBuf[0x200]; - sprintf_s(szBuf, "{%g,%g,%g,%g}{%g,%g,%g,%g}{%g,%g,%g,%g}{%g,%g,%g,%g}", - m(0, 0), m(0, 1), m(0, 2), m(0, 3), - m(1, 0), m(1, 1), m(1, 2), m(1, 3), - m(2, 0), m(2, 1), m(2, 2), m(2, 3), - m(3, 0), m(3, 1), m(3, 2), m(3, 3)); - return szBuf; - } -#endif - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_QUAT_H - /// Converts a CryQuat to a string. - /*! - \param m A quaternion of type CryQuat - \return the quaternion in the format {0,{0,0,0,0}} - */ - inline string ToString (const CryQuat& q) - { - char szBuf[0x100]; - sprintf_s(szBuf, "{%g,{%g,%g,%g}}", q.w, q.v.x, q.v.y, q.v.z); - return szBuf; - } -#endif - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_VECTOR3_H - /// Converts a Vec3 to a string. - /*! - \param m A vector of type Vec3 - \return the vector in the format {0,0,0} - */ - inline string ToString (const Vec3& v) - { - char szBuf[0x80]; - sprintf_s(szBuf, "{%g,%g,%g}", v.x, v.y, v.z); - return szBuf; - } -#endif - - /// This function only exists to allow ToString to compile if it is ever used with an unsupported type. - /*! - \param unknownType - \return a string that reads "unknown" - */ - template - inline string ToString(T& unknownType) - { - char szValue[8]; - sprintf_s(szValue, "%s", "unknown"); - return szValue; - } - - // does the same as strstr, but the szString is allowed to be no more than the specified size - /*! - \param szString the source string - \param szSubstring the sub-string to look for - \param nSuperstringLength the maximum size of szString - */ - inline const char* strnstr(const char* szString, const char* szSubstring, int nSuperstringLength) - { - int nSubstringLength = (int)strlen(szSubstring); - if (!nSubstringLength) - { - return szString; - } - - for (int nSubstringPos = 0; szString[nSubstringPos] && nSubstringPos < nSuperstringLength - nSubstringLength; ++nSubstringPos) - { - if (strncmp(szString + nSubstringPos, szSubstring, nSubstringLength) == 0) - { - return szString + nSubstringPos; - } - } - return nullptr; - } - - - // Finds the string in the array of strings. - // Returns its 0-based index or -1 if not found. - // Comparison is case-sensitive. - // The string array end is demarked by the NULL value. - // This function is Unicode agnostic (but no Unicode collation is performed for equality test) and locale agnostic. - inline int findString(const char* szString, const char* arrStringList[]) - { - for (const char** p = arrStringList; *p; ++p) - { - if (0 == strcmp(*p, szString)) - { - return (int)(p - arrStringList); - } - } - return -1; // string was not found - } - - /// Finds the string in the array of strings. - /*! - \param szString the string to look for - \param arrStringList array of strings - \remark comparison is case-sensitive - \remark The string array end is delimited by the nullptr value - \return its 0-based index or -1 if not found - */ - inline int FindString(const char* szString, const char* arrStringList[]) - { - for (const char** p = arrStringList; *p; ++p) - { - if (0 == strcmp(*p, szString)) - { - return (int)(p - arrStringList); - } - } - return -1; // string was not found - } - - /// Used for printing out sets of objects of string type. - /*! - \remark just forms the comma-delimited string where each string in the set is presented as a formatted substring - \param setStrings set of strings to print - \return a formatted string - */ - inline string ToString(const std::set& setStrings) - { - string strResult; - if (!setStrings.empty()) - { - strResult += "{"; - for (std::set::const_iterator it = setStrings.begin(); it != setStrings.end(); ++it) - { - if (it != setStrings.begin()) - { - strResult += ", "; - } - strResult += "\""; - strResult += *it; - strResult += "\""; - } - strResult += "}"; - } - return strResult; - } - - // Cuts the string and adds leading ... if it's longer than specified maximum length. - // This function is ASCII-only and locale agnostic. - inline string cutString(const string& strPath, unsigned nMaxLength) - { - if (strPath.length() > nMaxLength && nMaxLength > 3) - { - return string("...") + string(strPath.c_str() + strPath.length() - (nMaxLength - 3)); - } - else - { - return strPath; - } - } - - /// Cuts the string and adds leading ... if it's longer than specified maximum length. - /*! - \param str the string to cut - \param nMaxLength the allowed length of the string before its cut. - \return a shortened string starting in ellipses or the source string if it's smaller than nMaxLength - */ - inline string CutString(const string& str, unsigned nMaxLength) - { - if (str.length() > nMaxLength && nMaxLength > 3) - { - return string("...") + string(str.c_str() + str.length() - (nMaxLength - 3)); - } - else - { - return str; - } - } - - /// Converts the given set of NUMBERS into the string. - /*! - \param setMtlms A numeric set to convert into a string - \param szFormat - \param szPostfix - */ - template - string ToString(const std::set& setMtls, const char* szFormat, const char* szPostfix = "") - { - string strResult; - char szBuffer[64]; - if (!setMtls.empty()) - { - strResult += strResult.empty() ? "(" : " ("; - for (typename std::set::const_iterator it = setMtls.begin(); it != setMtls.end(); ) - { - if (it != setMtls.begin()) - { - strResult += ", "; - } - sprintf_s(szBuffer, szFormat, *it); - strResult += szBuffer; - T nStart = *it; - - ++it; - - if (it != setMtls.end() && *it == nStart + 1) - { - T nPrev = *it; - // we've got a region - while (++it != setMtls.end() && *it == nPrev + 1) - { - nPrev = *it; - } - if (nPrev == nStart + 1) - { - // special case - range of length 1 - strResult += ","; - } - else - { - strResult += ".."; - } - sprintf_s(szBuffer, szFormat, nPrev); - strResult += szBuffer; - } - } - strResult += ")"; - } - return szPostfix[0] ? strResult + szPostfix : strResult; - } - - - // Attempts to find a matching wildcard in a string. - /*! - \param szString source string - \param szWildcard the wildcard, supports * and ? - // returns true if the string matches the wildcard - // Note: ANSI input is not supported, ASCII is fine since it's a subset of UTF-8. - */ - inline bool MatchWildcard(const char* szString, const char* szWildcard) - { - return CryStringUtils_Internal::MatchesWildcards_Tpl(szString, szWildcard); - } - - // Returns true if the string matches the wildcard. - // Supports wildcard ? (matches one code-point) and * (matches zero or more code-points). - // This function is Unicode aware and uses the "C" locale for case comparison. - // Note: ANSI input is not supported, ASCII is fine since it's a subset of UTF-8. - inline bool MatchWildcardIgnoreCase(const char* szString, const char* szWildcard) - { - return CryStringUtils_Internal::MatchesWildcards_Tpl(szString, szWildcard); - } - -#if !defined(RESOURCE_COMPILER) - - // calculates a hash value for a given string - inline uint32 CalculateHash(const char* str) - { - return CCrc32::Compute(str); - } - - // calculates a hash value for the lower case version of a given string - inline uint32 CalculateHashLowerCase(const char* str) - { - return CCrc32::ComputeLowercase(str); - } - - // This function is Unicode agnostic and locale agnostic. - inline uint32 HashStringSeed(const char* string, const uint32 seed) - { - // A string hash taken from the FRD/Crysis2 (game) code with low probability of clashes - // Recommend you use the CRY_DEFAULT_HASH_SEED (see HashString) - const char* p; - uint32 hash = seed; - for (p = string; *p != '\0'; p++) - { - hash += *p; - hash += (hash << 10); - hash ^= (hash >> 6); - } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); - return hash; - } - - // This function is ASCII-only and uses the standard "C" locale for case conversion. - inline uint32 HashStringLowerSeed(const char* string, const uint32 seed) - { - // computes the hash of 'string' converted to lower case - // also see the comment in HashStringSeed - const char* p; - uint32 hash = seed; - for (p = string; *p != '\0'; p++) - { - hash += toLowerAscii(*p); - hash += (hash << 10); - hash ^= (hash >> 6); - } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); - return hash; - } - - // This function is Unicode agnostic and locale agnostic. - inline uint32 HashString(const char* string) - { - return HashStringSeed(string, CRY_DEFAULT_HASH_SEED); - } - - // This function is ASCII-only and uses the standard "C" locale for case conversion. - inline uint32 HashStringLower(const char* string) - { - return HashStringLowerSeed(string, CRY_DEFAULT_HASH_SEED); - } -#endif - - // converts all chars to lower case - avoids memory allocation - /*! - \param str Reference to string to convert into lowercase. - */ - inline void ToLowerInplace(string& str) - { -#ifndef NOT_USE_CRY_STRING - str.MakeLower(); -#else - std::transform(str.begin(), str.end(), str.begin(), toLowerAscii); // STL MakeLower -#endif - } - - /// Converts all chars to lower case - avoids memory allocation - /*! - \param str Reference to string to convert into lowercase. - */ - inline void ToLowerInplace(char* str) - { - if (str == nullptr) - { - return; - } - - for (char* s = str; *s != '\0'; s++) - { - *s = toLowerAscii(*s); - } - } - - -#ifndef NOT_USE_CRY_STRING - - // Converts a wide string (can be UTF-16 or UTF-32 depending on platform) to UTF-8. - // This function is Unicode aware and locale agnostic. - /// Converts a wide string to a UTF8 string. - /*! - \param str The wide string to convert. - \return dstr The wide string converted into the specified UTF8 type. - */ - template - inline void WStrToUTF8(const wchar_t* str, T& dstr) - { - string utf8; - Unicode::Convert(utf8, str); - - // Note: This function expects T to have assign(ptr, len) function - dstr.assign(utf8.c_str(), utf8.length()); - } - - // Converts a wide string (can be UTF-16 or UTF-32 depending on platform) to UTF-8. - // This function is Unicode aware and locale agnostic. - /// Converts a wide string to UTF8. - /*! - \param str The wchar_t string to convert. - \return The UTF8 string. - */ - inline string WStrToUTF8(const wchar_t* str) - { - return Unicode::Convert(str); - } - - /// Converts a UTF8 string to a wide string. - /*! - \param str The UTF8 string to convert. - \return dstr The UTF8 string converted into the specified type. - */ - template - inline void UTF8ToWStr(const char* str, T& dstr) - { - wstring wide; - Unicode::Convert(wide, str); - - // Note: This function expects T to have assign(ptr, len) function - dstr.assign(wide.c_str(), wide.length()); - } - - // Converts an UTF-8 string to wide string (can be UTF-16 or UTF-32 depending on platform). - // This function is Unicode aware and locale agnostic. - /*! - \param str The UTF8 string to convert. - \return str as converted to wstring. - */ - inline wstring UTF8ToWStr(const char* str) - { - return Unicode::Convert(str); - } - - /// Converts a string to a wide character string - /*! - \param str Source string. - \param dstr Destination wstring. - */ - inline void StrToWstr(const char* str, wstring& dstr) - { - CryStackStringT tmp; - tmp.resize(strlen(str)); - tmp.clear(); - - while (const wchar_t c = (wchar_t)(*str++)) - { - tmp.append(1, c); - } - - dstr.assign(tmp.data(), tmp.length()); - } - -#endif // NOT_USE_CRY_STRING - - /// The type used to parse a yes/no string -#if defined(_DISALLOW_ENUM_CLASS) - enum YesNoType -#else - enum class YesNoType -#endif - { - Yes, - No, - Invalid - }; - - // parse the yes/no string - /*! - \param szString any of the following strings: yes, enable, true, 1, no, disable, false, 0 - \return YesNoType::Yes if szString is yes/enable/true/1, YesNoType::No if szString is no, disable, false, 0 and YesNoType::Invalid if the string is not one of the expected values. - */ - inline YesNoType ToYesNoType(const char* szString) - { - if (!_stricmp(szString, "yes") - || !_stricmp(szString, "enable") - || !_stricmp(szString, "true") - || !_stricmp(szString, "1")) -#if defined(_DISALLOW_ENUM_CLASS) - { - return Yes; - } -#else - { - return YesNoType::Yes; - } -#endif - if (!_stricmp(szString, "no") - || !_stricmp(szString, "disable") - || !_stricmp(szString, "false") - || !_stricmp(szString, "0")) -#if defined(_DISALLOW_ENUM_CLASS) - { - return No; - } -#else - { - return YesNoType::No; - } -#endif - -#if defined(_DISALLOW_ENUM_CLASS) - return Invalid; -#else - return YesNoType::Invalid; -#endif - } - - /// Verifies if the filename provided only contains the accepted characters. - /*! - \param fileName the filename to verify - \return true if the filename only contains alphanumeric values and/or dot, dash and underscores. - */ - inline bool IsValidFileName(const char* fileName) - { - size_t i = 0; - for (;; ) - { - const char c = fileName[i++]; - if (c == 0) - { - return true; - } - if (!((c >= '0' && c <= '9') - || (c >= 'A' && c <= 'Z') - || (c >= 'a' && c <= 'z') - || c == '.' || c == '-' || c == '_')) - { - return false; - } - } - } - - - /************************************************************************** - *void _makepath() - build path name from components - * - *Purpose: - * create a path name from its individual components - * - *Entry: - * char *path - pointer to buffer for constructed path - * char *drive - pointer to drive component, may or may not contain trailing ':' - * char *dir - pointer to subdirectory component, may or may not include leading and/or trailing '/' or '\' characters - * char *fname - pointer to file base name component - * char *ext - pointer to extension component, may or may not contain a leading '.'. - * - *Exit: - * path - pointer to constructed path name - * - *******************************************************************************/ - ILINE void portable_makepath(char path[_MAX_PATH], const char* drive, const char* dir, const char* fname, const char* ext) - { - const char* p; - - /* we assume that the arguments are in the following form (although we - * do not diagnose invalid arguments or illegal filenames (such as - * names longer than 8.3 or with illegal characters in them) - * - * drive: - * A ; or - * A: - * dir: - * \top\next\last\ ; or - * /top/next/last/ ; or - * either of the above forms with either/both the leading - * and trailing / or \ removed. Mixed use of '/' and '\' is - * also tolerated - * fname: - * any valid file name - * ext: - * any valid extension (none if empty or null ) - */ - - /* copy drive */ - - if (drive && *drive) - { - *path++ = *drive; - *path++ = (':'); - } - - /* copy dir */ - - if ((p = dir) && *p) - { - do - { - *path++ = *p++; - } while (*p); - if (*(p - 1) != '/' && *(p - 1) != ('\\')) - { - *path++ = ('\\'); - } - } - - /* copy fname */ - - if (p = fname) - { - while (*p) - { - *path++ = *p++; - } - } - - /* copy ext, including 0-terminator - check to see if a '.' needs - * to be inserted. - */ - - if (p = ext) - { - if (*p && *p != ('.')) - { - *path++ = ('.'); - } - while (*path++ = *p++) - { - ; - } - } - else - { - /* better add the 0-terminator */ - *path = ('\0'); - } - } - - /// Create a path name from its individual components. - /*! - \param char *path pointer to buffer for constructed path - \param char *drive pointer to drive component, may or may not contain trailing ':' - \param char *dir pointer to subdirectory component, may or may not include leading and/or trailing '/' or '\' characters - \param char *fname pointer to file base name component - \param char *ext pointer to extension component, may or may not contain a leading '.'. - \return path pointer to constructed path name - */ - inline void MakePath(char path[_MAX_PATH], const char* drive, const char* dir, const char* fname, const char* ext) - { - const char* p; - - // we assume that the arguments are in the following form (although we - // do not diagnose invalid arguments or illegal filenames (such as - // names longer than 8.3 or with illegal characters in them) - // - // drive: - // A ; or - // A: - // dir: - // \top\next\last\ ; or - // /top/next/last/ ; or - // either of the above forms with either/both the leading - // and trailing / or \ removed. Mixed use of '/' and '\' is - // also tolerated - // fname: - // any valid file name - // ext: - // any valid extension (none if empty or null ) - // - - // copy drive - if (drive && *drive) - { - *path++ = *drive; - *path++ = (':'); - } - - // copy dir - if ((p = dir) && *p) - { - do - { - *path++ = *p++; - } while (*p); - if (*(p - 1) != '/' && *(p - 1) != ('\\')) - { - *path++ = ('\\'); - } - } - - // copy fname - if (p = fname) - { - while (*p) - { - *path++ = *p++; - } - } - - // copy ext, including 0-terminator - check to see if a '.' needs - // to be inserted. - if (p = ext) - { - if (*p && *p != ('.')) - { - *path++ = ('.'); - } - while (*path++ = *p++) - { - ; - } - } - else - { - // better add the 0-terminator - *path = ('\0'); - } - } - - // Copies characters from a string. - /*! - \param destination Pointer to the destination array where the content is to be copied. - \param source C string to be copied. - \param num Maximum number of characters to be copied from source. - \remark Parameter order is the same as strncpy; Copies only up to num characters from source to destination. - \return true if entirety of source was copied into destination. - */ - inline bool strncpy(char* destination, const char* source, size_t num) - { - bool reply = false; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (num) - { - size_t i; - for (i = 0; source[i] && (i + 1) < num; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == '\0'); - } - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT_MESSAGE(reply, string().Format("String '%s' is too big to fit into a buffer of length %u", source, (unsigned int)num)); -#endif - return reply; - } - - // Copies wide characters from a wide string. - /*! - \param destination Pointer to the destination wchar_t array where the content is to be copied. - \param source C wide string to be copied. - \param num Maximum number of characters to be copied from source. - \remark Parameter order is the same as strncpy; Copies only up to num characters from source to destination. - \return true if entirety of source was copied into destination. - */ - inline bool wstrncpy(wchar_t* destination, const wchar_t* source, size_t bufferLength) - { - bool reply = false; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (bufferLength) - { - size_t i; - for (i = 0; source[i] && (i + 1) < bufferLength; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == '\0'); - } - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT_MESSAGE(reply, string().Format("String '%ls' is too big to fit into a buffer of length %u", source, (unsigned int)bufferLength)); -#endif - return reply; - } - - // Copies a C string into a destination buffer up to a specified delimiter or null terminator. - /*! - \param destination Pointer to a buffer where the resulting C-string is stored. - \param source C string to be copied. - \param num Maximum number of characters to be copied from source. - \param delimiter Delimiter character up to which the string will be copied. - \return Number of bytes written into destination (including null terminator) or 0 if delimiter is not found within the first num bytes of source. - */ - inline size_t CopyStringUntilFindChar(char* destination, const char* source, size_t num, char delimiter) - { - size_t reply = 0; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (num) - { - size_t i; - for (i = 0; source[i] && source[i] != delimiter && (i + 1) < num; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == delimiter) ? (i + 1) : 0; - } - - return reply; - } -} // namespace CryStringUtils - -#endif // CRYINCLUDE_CRYCOMMON_STRINGUTILS_H diff --git a/Code/Legacy/CryCommon/TypeInfo_decl.h b/Code/Legacy/CryCommon/TypeInfo_decl.h index f763ec6ebb..28a0b370a9 100644 --- a/Code/Legacy/CryCommon/TypeInfo_decl.h +++ b/Code/Legacy/CryCommon/TypeInfo_decl.h @@ -15,6 +15,7 @@ #pragma once #include +#include ////////////////////////////////////////////////////////////////////////// // Meta-type support. @@ -55,7 +56,7 @@ inline const CTypeInfo& TypeInfo(const T* t) // Type info declaration, with additional prototypes for string conversions. #define BASIC_TYPE_INFO(Type) \ - string ToString(Type const & val); \ + AZStd::string ToString(Type const & val); \ bool FromString(Type & val, const char* s); \ DECLARE_TYPE_INFO(Type) @@ -105,7 +106,7 @@ BASIC_TYPE_INFO(double) BASIC_TYPE_INFO(AZ::Uuid) -DECLARE_TYPE_INFO(string) +DECLARE_TYPE_INFO(AZStd::string) // All pointers share same TypeInfo. const CTypeInfo&PtrTypeInfo(); diff --git a/Code/Legacy/CryCommon/UnicodeBinding.h b/Code/Legacy/CryCommon/UnicodeBinding.h index 6bfa846035..aaefcf0f55 100644 --- a/Code/Legacy/CryCommon/UnicodeBinding.h +++ b/Code/Legacy/CryCommon/UnicodeBinding.h @@ -12,7 +12,6 @@ // // (At least) the following string types can be bound with these helper functions: // Types Input Output Null-Terminator -// CryStringT, (::string, ::wstring): yes yes implied by type (also Stack and Fixed variants) // std::basic_string, std::string, std::wstring: yes yes implied by type // QString: yes yes implied by type // std::vector, std::list, std::deque: yes yes not present @@ -56,18 +55,14 @@ // Forward declare the supported types. // Before actually instantiating a binding however, you need to have the full definition included. // Also, this allows us to work with QChar/QString as declared names without a dependency on Qt. -template -class CryStackStringT; -template -class CryFixedStringT; -template -class CryFixedWStringT; -template -class CryStringLocalT; -template -class CryStringT; +namespace AZStd +{ + template + class basic_fixed_string; +} class QChar; class QString; + namespace Unicode { namespace Detail @@ -253,36 +248,15 @@ namespace Unicode static const bool isValid = SValidChar::value; static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; template - struct SBindObject, InferEncoding> + struct SBindObject, InferEncoding> { typedef typename add_const::type CharType; static const bool isValid = SValidChar::value; static const EBind value = isValid ? eBind_Data : eBind_Impossible; }; template - struct SBindObject, InferEncoding> - { - typedef char CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> + struct SBindObject, InferEncoding> { typedef wchar_t CharType; static const bool isValid = SValidChar::value; @@ -348,22 +322,8 @@ namespace Unicode static const bool isValid = SValidChar::value; static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; template - struct SBindOutput, InferEncoding> + struct SBindOutput, InferEncoding> { typedef T CharType; static const bool isValid = SValidChar::value; diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 3208da9d68..a60dbdf00b 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -486,7 +486,7 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext drv[0] = 0; } - typedef CryStackStringT path_stack_string; + typedef AZStd::fixed_string path_stack_string; const path_stack_string inPath(inpath); string::size_type s = inPath.rfind('/', inPath.size());//position of last / diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index 0392f11c89..63c5b49513 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -78,7 +78,6 @@ set(FILES CryCrc32.h CryCustomTypes.h CryFile.h - CryFixedString.h CryHeaders.h CryHeaders_info.cpp CryListenerSet.h @@ -87,7 +86,6 @@ set(FILES CryPath.h CryPodArray.h CrySizer.h - CryString.h CrySystemBus.h CryThread.h CryThreadImpl.h @@ -111,7 +109,6 @@ set(FILES SimpleSerialize.h smartptr.h StlUtils.h - StringUtils.h Synchronization.h Tarray.h Timer.h diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index b3846b88dd..60edf10de9 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -689,9 +689,6 @@ void SetFlags(T& dest, U flags, bool b) #include AZ_RESTRICTED_FILE(platform_h) #endif -// Platform wrappers must be included before CryString.h -# include "CryString.h" - // Include support for meta-type data. #include "TypeInfo_decl.h" @@ -701,12 +698,6 @@ void SetFlags(T& dest, U flags, bool b) bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes); threadID CryGetCurrentThreadId(); -#if !defined(NOT_USE_CRY_STRING) -// Fixed-Sized (stack based string) -// put after the platform wrappers because of missing wcsicmp/wcsnicmp functions - #include "CryFixedString.h" -#endif - // need this in a common header file and any other file would be too misleading enum ETriState { diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index a677ba30b6..6ec8df0365 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -8,7 +8,6 @@ #include -#include #include #include #include @@ -248,10 +247,7 @@ int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const ch return 0; } #endif - wstring wideText, wideCaption; - Unicode::Convert(wideText, lpText); - Unicode::Convert(wideCaption, lpCaption); - return MessageBoxW(NULL, wideText.c_str(), wideCaption.c_str(), uType); + return MessageBox(NULL, lpText, lpCaption, uType); #else return 0; #endif diff --git a/Code/Legacy/CrySystem/CmdLine.cpp b/Code/Legacy/CrySystem/CmdLine.cpp index cb805b6990..50b8b2c092 100644 --- a/Code/Legacy/CrySystem/CmdLine.cpp +++ b/Code/Legacy/CrySystem/CmdLine.cpp @@ -11,7 +11,7 @@ #include "CmdLine.h" -void CCmdLine::PushCommand(const string& sCommand, const string& sParameter) +void CCmdLine::PushCommand(const AZStd::string& sCommand, const AZStd::string& sParameter) { if (sCommand.empty()) { @@ -47,7 +47,7 @@ CCmdLine::CCmdLine(const char* commandLine) char* src = (char*)commandLine; - string command, parameter; + AZStd::string command, parameter; for (;; ) { @@ -56,12 +56,12 @@ CCmdLine::CCmdLine(const char* commandLine) break; } - string arg = Next(src); + AZStd::string arg = Next(src); if (m_args.empty()) { // this is the filename, convert backslash to forward slash - arg.replace('\\', '/'); + AZ::StringFunc::Replace(arg, '\\', '/'); m_args.push_back(CCmdLineArg("filename", arg.c_str(), eCLAT_Executable)); } else @@ -90,7 +90,7 @@ CCmdLine::CCmdLine(const char* commandLine) } else { - parameter += string(" ") + arg; + parameter += AZStd::string(" ") + arg; } } } @@ -151,7 +151,7 @@ const ICmdLineArg* CCmdLine::FindArg(const ECmdLineArgType ArgType, const char* } -string CCmdLine::Next(char*& src) +AZStd::string CCmdLine::Next(char*& src) { char ch = 0; char* org = src; @@ -170,7 +170,7 @@ string CCmdLine::Next(char*& src) ; } - return string(org, src - 1); + return AZStd::string(org, src - 1); case '[': org = src; @@ -178,7 +178,7 @@ string CCmdLine::Next(char*& src) { ; } - return string(org, src - 1); + return AZStd::string(org, src - 1); case ' ': ch = *src++; @@ -190,12 +190,12 @@ string CCmdLine::Next(char*& src) ; } - return string(org, src); + return AZStd::string(org, src); } ch = *src++; } - return string(); + return AZStd::string(); } diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp index 576c3ee9fb..1914e82515 100644 --- a/Code/Legacy/CrySystem/DebugCallStack.cpp +++ b/Code/Legacy/CrySystem/DebugCallStack.cpp @@ -430,18 +430,18 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) { const char* const szMessage = m_bIsFatalError ? s_szFatalErrorCode : m_szBugMessage; excName = szMessage; - cry_strcpy(excCode, szMessage); - cry_strcpy(excAddr, ""); - cry_strcpy(desc, ""); - cry_strcpy(m_excModule, ""); - cry_strcpy(excDesc, szMessage); + azstrcpy(excCode, szMessage); + azstrcpy(excAddr, ""); + azstrcpy(desc, ""); + azstrcpy(m_excModule, ""); + azstrcpy(excDesc, szMessage); } else { sprintf_s(excAddr, "0x%04X:0x%p", pex->ContextRecord->SegCs, pex->ExceptionRecord->ExceptionAddress); sprintf_s(excCode, "0x%08X", pex->ExceptionRecord->ExceptionCode); excName = TranslateExceptionCode(pex->ExceptionRecord->ExceptionCode); - cry_strcpy(desc, ""); + azstrcpy(desc, ""); sprintf_s(excDesc, "%s\r\n%s", excName, desc); @@ -471,9 +471,9 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) WriteLineToLog("Exception Description: %s", desc); - cry_strcpy(m_excDesc, excDesc); - cry_strcpy(m_excAddr, excAddr); - cry_strcpy(m_excCode, excCode); + azstrcpy(m_excDesc, excDesc); + azstrcpy(m_excAddr, excAddr); + azstrcpy(m_excCode, excCode); char errs[32768]; @@ -499,7 +499,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) dumpCallStack(funcs); // Fill call stack. char str[s_iCallStackSize]; - cry_strcpy(str, ""); + azstrcpy(str, ""); for (unsigned int i = 0; i < funcs.size(); i++) { char temp[s_iCallStackSize]; @@ -509,7 +509,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) cry_strcat(errs, temp); cry_strcat(errs, "\n"); } - cry_strcpy(m_excCallstack, str); + azstrcpy(m_excCallstack, str); } cry_strcat(errorString, errs); diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index e8cc4d484c..83db5e4a29 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -567,7 +567,7 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) INDENT_LOG_DURING_SCOPE(); char levelName[256]; - cry_strcpy(levelName, _levelName); + azstrcpy(levelName, _levelName); // Not remove a scope!!! { diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp index ce39f08480..fe0fd9cb22 100644 --- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp +++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp @@ -528,7 +528,7 @@ static void CopyLowercase(char* dst, size_t dstSize, const char* src, size_t src } ////////////////////////////////////////////////////////////////////////// -static void ReplaceEndOfLine(CryFixedStringT& s) +static void ReplaceEndOfLine(AZStd::fixed_string& s) { const string oldSubstr("\\n"); const string newSubstr(" \n"); @@ -536,7 +536,7 @@ static void ReplaceEndOfLine(CryFixedStringT::npos) + if (pos == AZStd::fixed_string::npos) { return; } @@ -955,7 +955,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName, bool bFirstRow = true; - CryFixedStringT sTmp; + AZStd::fixed_string sTmp; // lower case event name char szLowerCaseEvent[128]; @@ -1609,7 +1609,7 @@ bool CLocalizedStringsManager::DoLoadAGSXmlDocument(const char* sFileName, uint8 { continue; } - AzFramework::StringFunc::Replace(textValue, "\\n", " \n"); // carried over from helper func ReplaceEndOfLine(CryFixedStringT<>& s) + AzFramework::StringFunc::Replace(textValue, "\\n", " \n"); if (keyString[0] == '@') { AzFramework::StringFunc::LChop(keyString, 1); @@ -2536,7 +2536,7 @@ void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberStrin int n = abs(number); string separator; - CryFixedStringT<64> tmp; + AZStd::fixed_string<64> tmp; LocalizeString_ch("@ui_thousand_separator", separator); while (n > 0) { @@ -2565,7 +2565,7 @@ void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals { if (number == 0.0f) { - CryFixedStringT<64> tmp; + AZStd::fixed_string<64> tmp; tmp.Format("%.*f", decimals, number); outNumberString.assign(tmp.c_str()); return; @@ -2585,7 +2585,7 @@ void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals int decimalsAsInt = aznumeric_cast(int_round(decimalsOnly * pow(10.0f, decimals))); - CryFixedStringT<64> tmp; + AZStd::fixed_string<64> tmp; tmp.Format("%s%s%0*d", intPart.c_str(), commaSeparator.c_str(), decimals, decimalsAsInt); outNumberString.assign(tmp.c_str()); @@ -2657,7 +2657,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool if (len > 0) { // len includes terminating null! - CryFixedWStringT<256> tmpString; + AZStd::fixed_wstring<256> tmpString; tmpString.resize(len); ::GetTimeFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len); Unicode::Convert(outTimeString, tmpString); @@ -2678,7 +2678,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool UnixTimeToSystemTime(t, &systemTime); // len includes terminating null! - CryFixedWStringT<256> tmpString; + AZStd::fixed_wstring<256> tmpString; if (bIncludeWeekday) { diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp index d2d8495063..2c7c307d50 100644 --- a/Code/Legacy/CrySystem/Log.cpp +++ b/Code/Legacy/CrySystem/Log.cpp @@ -509,7 +509,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo stack_string s = szBuffer; s += "\t "; s += sAssetScope; - cry_strcpy(szBuffer, s.c_str()); + azstrcpy(szBuffer, s.c_str()); } } @@ -863,7 +863,7 @@ bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SL { // When logging from other thread then main, push all log strings to queue. SLogMsg msg; - cry_strcpy(msg.msg, szString); + azstrcpy(msg.msg, szString); msg.bAdd = bAdd; msg.destination = destination; msg.logType = logType; @@ -1286,7 +1286,7 @@ void CLog::CreateBackupFile() const string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt); fileSystem->CreatePath(LOG_BACKUP_PATH); - cry_strcpy(m_sBackupFilename, bakdest.c_str()); + azstrcpy(m_sBackupFilename, bakdest.c_str()); // Remove any existing backup file with the same name first since the copy will fail otherwise. fileSystem->Remove(m_sBackupFilename); fileSystem->Copy(m_szFilename, bakdest); diff --git a/Code/Legacy/CrySystem/Log.h b/Code/Legacy/CrySystem/Log.h index 5b1956b12f..3c0fa98037 100644 --- a/Code/Legacy/CrySystem/Log.h +++ b/Code/Legacy/CrySystem/Log.h @@ -37,7 +37,7 @@ class CLog { public: typedef std::list Callbacks; - typedef CryStackStringT LogStringType; + typedef AZStd::fixed_string LogStringType; // constructor CLog(ISystem* pSystem); diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp index 7fa7f7d2b0..bf4de8489d 100644 --- a/Code/Legacy/CrySystem/System.cpp +++ b/Code/Legacy/CrySystem/System.cpp @@ -1190,7 +1190,7 @@ void CSystem::WarningV(EValidatorModule module, EValidatorSeverity severity, int if (file && *file) { - CryFixedStringT fmt = szBuffer; + AZStd::fixed_string fmt = szBuffer; fmt += " [File="; fmt += file; fmt += "]"; diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp index 2cc41adc08..943a540ae6 100644 --- a/Code/Legacy/CrySystem/SystemWin32.cpp +++ b/Code/Legacy/CrySystem/SystemWin32.cpp @@ -127,7 +127,7 @@ const char* CSystem::GetUserName() DWORD dwSize = iNameBufferSize; wchar_t nameW[iNameBufferSize]; ::GetUserNameW(nameW, &dwSize); - cry_strcpy(szNameBuffer, CryStringUtils::WStrToUTF8(nameW)); + azstrcpy(szNameBuffer, CryStringUtils::WStrToUTF8(nameW)); return szNameBuffer; #else #if defined(LINUX) @@ -283,7 +283,7 @@ static const char* GetLastSystemErrorMessage() 0, NULL)) { - cry_strcpy(szBuffer, (char*)lpMsgBuf); + azstrcpy(szBuffer, (char*)lpMsgBuf); LocalFree(lpMsgBuf); } else @@ -505,7 +505,9 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize) if (bSucceeded) { // Convert from UNICODE to UTF-8 - cry_strcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath)); + AZStd::string str; + AZStd::to_string(str, AZStd::wstring(wMyDocumentsPath)); + azstrcpy(szMyDocumentsPath, maxPathSize, str.c_str()); CoTaskMemFree(wMyDocumentsPath); } } @@ -519,7 +521,9 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize) bSucceeded = SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, wMyDocumentsPath)); if (bSucceeded) { - cry_strcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath)); + AZStd::string str; + AZStd::to_string(str, AZStd::wstring(wMyDocumentsPath)); + azstrcpy(szMyDocumentsPath, maxPathSize, str.c_str()); } } diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp index 09b3182c04..a69d86e8b7 100644 --- a/Code/Legacy/CrySystem/XConsole.cpp +++ b/Code/Legacy/CrySystem/XConsole.cpp @@ -1554,7 +1554,7 @@ const char* CXConsole::GetFlagsString(const uint32 dwFlags) // hiding this makes it a bit more difficult for cheaters // if(dwFlags&VF_CHEAT) cry_strcat( sFlags,"CHEAT, "); - cry_strcpy(sFlags, ""); + azstrcpy(sFlags, ""); if (dwFlags & VF_READONLY) { diff --git a/Code/Legacy/CrySystem/XConsole.h b/Code/Legacy/CrySystem/XConsole.h index eca52771dd..f09c8e5ad7 100644 --- a/Code/Legacy/CrySystem/XConsole.h +++ b/Code/Legacy/CrySystem/XConsole.h @@ -42,11 +42,11 @@ enum ScrollDir ////////////////////////////////////////////////////////////////////////// struct CConsoleCommand { - string m_sName; // Console command name - string m_sCommand; // lua code that is executed when this command is invoked - string m_sHelp; // optional help string - can be shown in the console with " ?" - int m_nFlags; // bitmask consist of flag starting with VF_ e.g. VF_CHEAT - ConsoleCommandFunc m_func; // Pointer to console command. + AZStd::string m_sName; // Console command name + AZStd::string m_sCommand; // lua code that is executed when this command is invoked + AZStd::string m_sHelp; // optional help string - can be shown in the console with " ?" + int m_nFlags; // bitmask consist of flag starting with VF_ e.g. VF_CHEAT + ConsoleCommandFunc m_func; // Pointer to console command. ////////////////////////////////////////////////////////////////////////// CConsoleCommand() @@ -67,7 +67,7 @@ struct CConsoleCommand struct CConsoleCommandArgs : public IConsoleCmdArgs { - CConsoleCommandArgs(string& line, std::vector& args) + CConsoleCommandArgs(AZStd::string& line, std::vector& args) : m_line(line) , m_args(args) {}; virtual int GetArgCount() const { return m_args.size(); }; @@ -87,8 +87,8 @@ struct CConsoleCommandArgs } private: - std::vector& m_args; - string& m_line; + std::vector& m_args; + AZStd::string& m_line; }; @@ -132,7 +132,7 @@ class CXConsole , public AzFramework::CommandRegistrationBus::Handler { public: - typedef std::deque ConsoleBuffer; + typedef std::deque ConsoleBuffer; typedef ConsoleBuffer::iterator ConsoleBufferItor; typedef ConsoleBuffer::reverse_iterator ConsoleBufferRItor; @@ -262,7 +262,7 @@ protected: // ------------------------------------------------------------------ void AddInputUTF8(const AZStd::string& textUTF8); void RemoveInputChar(bool bBackSpace); void ExecuteInputBuffer(); - void ExecuteCommand(CConsoleCommand& cmd, string& params, bool bIgnoreDevMode = false); + void ExecuteCommand(CConsoleCommand& cmd, AZStd::string& params, bool bIgnoreDevMode = false); void ScrollConsole(); @@ -294,7 +294,7 @@ protected: // ------------------------------------------------------------------ // Arguments: // bFromConsole - true=from console, false=from outside - void SplitCommands(const char* line, std::list& split); + void SplitCommands(const char* line, std::list& split); void ExecuteStringInternal(const char* command, const bool bFromConsole, const bool bSilentMode = false); void ExecuteDeferredCommands(); @@ -320,27 +320,27 @@ private: // ---------------------------------------------------------- void PostLine(const char* lineOfText, size_t len); - typedef std::map ConsoleCommandsMap; + typedef std::map ConsoleCommandsMap; typedef ConsoleCommandsMap::iterator ConsoleCommandsMapItor; - typedef std::map ConsoleBindsMap; + typedef std::map ConsoleBindsMap; typedef ConsoleBindsMap::iterator ConsoleBindsMapItor; - typedef std::map > ArgumentAutoCompleteMap; + typedef std::map > ArgumentAutoCompleteMap; struct SConfigVar { - string m_value; + AZStd::string m_value; bool m_partOfGroup; }; - typedef std::map ConfigVars; + typedef std::map ConfigVars; struct SDeferredCommand { - string command; + AZStd::string command; bool silentMode; - SDeferredCommand(const string& _command, bool _silentMode) + SDeferredCommand(const AZStd::string& _command, bool _silentMode) : command(_command) , silentMode(_silentMode) {} @@ -359,10 +359,10 @@ private: // ---------------------------------------------------------- int m_nProgress; int m_nProgressRange; - string m_sInputBuffer; - string m_sReturnString; + AZStd::string m_sInputBuffer; + AZStd::string m_sReturnString; - string m_sPrevTab; + AZStd::string m_sPrevTab; int m_nTabCount; ConsoleCommandsMap m_mapCommands; // diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp index da4bf66eee..55fab84286 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp @@ -49,7 +49,7 @@ bool CSerializeXMLReaderImpl::Value(const char* name, int8& value) return bResult; } -bool CSerializeXMLReaderImpl::Value(const char* name, string& value) +bool CSerializeXMLReaderImpl::Value(const char* name, AZStd::string& value) { DefaultValue(value); // Set input value to default. if (m_nErrors) @@ -177,7 +177,7 @@ void CSerializeXMLReaderImpl::EndGroup() ////////////////////////////////////////////////////////////////////////// const char* CSerializeXMLReaderImpl::GetStackInfo() const { - static string str; + static AZStd::string str; str.assign(""); for (int i = 0; i < (int)m_nodeStack.size(); i++) { diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h index c0e2059886..177db0ffaa 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h @@ -47,7 +47,7 @@ public: g_pXmlStrCmp = pPrevCmpFunc; return bReturn; } - ILINE bool GetAttr([[maybe_unused]] XmlNodeRef& node, [[maybe_unused]] const char* name, [[maybe_unused]] const string& value) + ILINE bool GetAttr([[maybe_unused]] XmlNodeRef& node, [[maybe_unused]] const char* name, [[maybe_unused]] const AZStd::string& value) { return false; } @@ -75,7 +75,7 @@ public: } bool Value(const char* name, int8& value); - bool Value(const char* name, string& value); + bool Value(const char* name, AZStd::string& value); bool Value(const char* name, CTimeValue& value); bool Value(const char* name, XmlNodeRef& value); @@ -172,8 +172,8 @@ private: void DefaultValue(Quat& v) const { v.w = 1.0f; v.v.x = 0; v.v.y = 0; v.v.z = 0; } void DefaultValue(CTimeValue& v) const { v.SetValue(0); } //void DefaultValue( char *str ) const { if (str) str[0] = 0; } - void DefaultValue(string& str) const { str = ""; } - void DefaultValue([[maybe_unused]] const string& str) const {} + void DefaultValue(AZStd::string& str) const { str = ""; } + void DefaultValue([[maybe_unused]] const AZStd::string& str) const {} void DefaultValue([[maybe_unused]] SNetObjectID& id) const {} void DefaultValue([[maybe_unused]] SSerializeString& str) const {} void DefaultValue(XmlNodeRef& ref) const { ref = NULL; } diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp index bd31fb3ba4..e59f6b8969 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp @@ -32,7 +32,7 @@ const char* XMLBinary::XMLBinaryReader::GetErrorDescription() const void XMLBinary::XMLBinaryReader::SetErrorDescription(const char* text) { - cry_strcpy(m_errorDescription, text); + azstrcpy(m_errorDescription, text); } diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp index 60e0d2e4f1..81994b26e0 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp @@ -84,7 +84,7 @@ static void write(XMLBinary::IDataWriter* const pFile, size_t& nPosition, const } ////////////////////////////////////////////////////////////////////////// -bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, bool bNeedSwapEndian, XMLBinary::IFilter* pFilter, string& error) +bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, bool bNeedSwapEndian, XMLBinary::IFilter* pFilter, AZStd::string& error) { error = ""; @@ -99,7 +99,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, static const uint nMaxNodeCount = (NodeIndex) ~0; if (m_nodes.size() > nMaxNodeCount) { - error.Format("XMLBinary: Too many nodes: %d (max is %i)", m_nodes.size(), nMaxNodeCount); + error = AZStd::string::format("XMLBinary: Too many nodes: %d (max is %i)", m_nodes.size(), nMaxNodeCount); return false; } @@ -192,7 +192,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, return true; } -bool XMLBinary::CXMLBinaryWriter::CompileTables(XmlNodeRef node, XMLBinary::IFilter* pFilter, string& error) +bool XMLBinary::CXMLBinaryWriter::CompileTables(XmlNodeRef node, XMLBinary::IFilter* pFilter, AZStd::string& error) { bool ok = CompileTablesForNode(node, -1, pFilter, error); ok = ok && CompileChildTable(node, pFilter, error); @@ -200,7 +200,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTables(XmlNodeRef node, XMLBinary::IFil } ////////////////////////////////////////////////////////////////////////// -bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nParentIndex, XMLBinary::IFilter* pFilter, string& error) +bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nParentIndex, XMLBinary::IFilter* pFilter, AZStd::string& error) { // Add the tag to the string table. int nTagStringOffset = AddString(node->getTag()); @@ -231,7 +231,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nPar static const int nMaxAttributeCount = (uint16) ~0; if (nAttributeCount > nMaxAttributeCount) { - error.Format("XMLBinary: Too many attributes in a node: %d (max is %i)", nAttributeCount, nMaxAttributeCount); + error = AZStd::string::format("XMLBinary: Too many attributes in a node: %d (max is %i)", nAttributeCount, nMaxAttributeCount); return false; } @@ -261,7 +261,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nPar { if (++nChildCount > nMaxChildCount) { - error.Format("XMLBinary: Too many children in node '%s': %d (max is %i)", childNode->getTag(), nChildCount, nMaxChildCount); + error = AZStd::string::format("XMLBinary: Too many children in node '%s': %d (max is %i)", childNode->getTag(), nChildCount, nMaxChildCount); return false; } if (!CompileTablesForNode(childNode, nIndex, pFilter, error)) @@ -277,7 +277,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nPar } ////////////////////////////////////////////////////////////////////////// -bool XMLBinary::CXMLBinaryWriter::CompileChildTable(XmlNodeRef node, XMLBinary::IFilter* pFilter, string& error) +bool XMLBinary::CXMLBinaryWriter::CompileChildTable(XmlNodeRef node, XMLBinary::IFilter* pFilter, AZStd::string& error) { const int nIndex = m_nodesMap.find(node)->second; // Assume node always exist in map. const int nFirstChildIndex = (int)m_childs.size(); @@ -298,7 +298,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileChildTable(XmlNodeRef node, XMLBinary:: } if (nChildCount != nd.nChildCount) { - error.Format("XMLBinary: Internal error in CompileChildTable()"); + error = AZStd::string::format("XMLBinary: Internal error in CompileChildTable()"); return false; } diff --git a/Code/Legacy/CrySystem/XML/XMLPatcher.cpp b/Code/Legacy/CrySystem/XML/XMLPatcher.cpp index f78fa93a60..ff4cfc91d2 100644 --- a/Code/Legacy/CrySystem/XML/XMLPatcher.cpp +++ b/Code/Legacy/CrySystem/XML/XMLPatcher.cpp @@ -345,7 +345,7 @@ void CXMLPatcher::DumpXMLNodes( AZ::IO::HandleType inFileHandle, int inIndent, const XmlNodeRef& inNode, - CryFixedStringT<512>* ioTempString) + AZStd::fixed_string<512>* ioTempString) { auto pPak = gEnv->pCryPak; @@ -393,7 +393,7 @@ void CXMLPatcher::DumpFiles( DumpXMLFile(string().Format("PATCH_%s", pOrigFileName), inBefore); - CryFixedStringT<128> newFileName(pOrigFileName); + AZStd::fixed_string<128> newFileName(pOrigFileName); newFileName.replace(".xml", "_patched.xml"); DumpXMLFile(string().Format("PATCH_%s", newFileName.c_str()), inAfter); @@ -414,7 +414,7 @@ void CXMLPatcher::DumpXMLFile( if (fileHandle != AZ::IO::InvalidHandle) { - CryFixedStringT<512> tempStr; + AZStd::fixed_string<512> tempStr; DumpXMLNodes(fileHandle, 0, inNode, &tempStr); diff --git a/Code/Legacy/CrySystem/XML/XMLPatcher.h b/Code/Legacy/CrySystem/XML/XMLPatcher.h index 039b369723..ccc5f481eb 100644 --- a/Code/Legacy/CrySystem/XML/XMLPatcher.h +++ b/Code/Legacy/CrySystem/XML/XMLPatcher.h @@ -59,7 +59,7 @@ protected: AZ::IO::HandleType inFileHandle, int inIndent, const XmlNodeRef& inNode, - CryFixedStringT<512>* ioTempString); + AZStd::fixed_string<512>* ioTempString); void DumpFiles( const char* pInXMLFileName, const XmlNodeRef& inBefore, diff --git a/Code/Legacy/CrySystem/XML/xml.cpp b/Code/Legacy/CrySystem/XML/xml.cpp index 5761d8a963..c6e660155f 100644 --- a/Code/Legacy/CrySystem/XML/xml.cpp +++ b/Code/Legacy/CrySystem/XML/xml.cpp @@ -1691,8 +1691,8 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, char str[1024]; - CryStackStringT adjustedFilename; - CryStackStringT pakPath; + AZStd::fixed_string<256> adjustedFilename; + AZStd::fixed_string<256> pakPath; if (fileSize <= 0) { CCryFile xmlFile; @@ -1761,7 +1761,7 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, // not binary XML - refuse to load if in scripts dir and not in bin xml to help reduce hacking // wish we could compile the text xml parser out, but too much work to get everything moved over static const char SCRIPTS_DIR[] = "Scripts/"; - CryFixedStringT<32> strScripts("S"); + AZStd::fixed_string<32> strScripts("S"); strScripts += "c"; strScripts += "r"; strScripts += "i"; @@ -1770,7 +1770,7 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, strScripts += "s"; strScripts += "/"; // exclude files and PAKs from Mods folder - CryFixedStringT<8> modsStr("M"); + AZStd::fixed_string<8> modsStr("M"); modsStr += "o"; modsStr += "d"; modsStr += "s"; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 795c823fd6..7974d0f2c1 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -18,7 +18,6 @@ #include #include #include -#include #include #include #include "AtomFont.h" diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp index 9aaaf2ffeb..f72ba6e1ff 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp @@ -18,7 +18,7 @@ namespace AtomFontInternal if (SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0, SHGFP_TYPE_DEFAULT, sysFontPath))) { const char* fontPath = m_strFontPath.c_str(); - const char* fontName = CryStringUtils::FindFileNameInPath(fontPath); + const char* fontName = AZ::IO::PathView(fontPath).Filename(); string newFontPath(sysFontPath); newFontPath += "/"; diff --git a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp index b7a7443daa..933633b5e3 100644 --- a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp +++ b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp @@ -437,8 +437,6 @@ namespace Blast static void CmdToggleBlastDebugVisualization(IConsoleCmdArgs* args) { - using namespace CryStringUtils; - const int argumentCount = args->GetArgCount(); if (argumentCount == 2) diff --git a/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp b/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp index 640fc2100e..78742028f9 100644 --- a/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp +++ b/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp @@ -85,7 +85,7 @@ namespace LmbrCentral { static const char* s_assetCatalogFilename = "assetcatalog.xml"; - using LmbrCentralAllocatorScope = AZ::AllocatorScope; + using LmbrCentralAllocatorScope = AZ::AllocatorScope; // This component boots the required allocators for LmbrCentral everywhere but AssetBuilders class LmbrCentralAllocatorComponent @@ -347,12 +347,6 @@ namespace LmbrCentral m_allocatorShutdowns.push_back([]() { AZ::AllocatorInstance::Destroy(); }); } - if (!AZ::AllocatorInstance::IsReady()) - { - AZ::AllocatorInstance::Create(); - m_allocatorShutdowns.push_back([]() { AZ::AllocatorInstance::Destroy(); }); - } - // Register asset handlers. Requires "AssetDatabaseService" AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!"); diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp index d930b4b581..9cca6cdf8d 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp @@ -1512,7 +1512,7 @@ int CUiAnimViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, con if (const char* pCh = strstr(nodeName, ".[")) { char matPath[MAX_PATH]; - cry_strcpy(matPath, nodeName, (size_t)(pCh - nodeName)); + azstrcpy(matPath, nodeName, (size_t)(pCh - nodeName)); matName = matPath; pCh += 2; if ((*pCh) != 0) diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp index ac55cd38e9..98cbd22f71 100644 --- a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp +++ b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp @@ -47,7 +47,8 @@ bool PropertyHandlerChar::ReadValuesIntoGUI(size_t index, AzToolsFramework::Prop // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to // work for cases tested but may not in general. wchar_t wcharString[2] = { static_cast(instance), 0 }; - AZStd::string val(CryStringUtils::WStrToUTF8(wcharString)); + AZStd::string val; + AZStd::to_string(val, AZStd::wstring(wcharString)); GUI->setValue(val); } GUI->blockSignals(false); diff --git a/Gems/LyShine/Code/Source/LyShineSystemComponent.h b/Gems/LyShine/Code/Source/LyShineSystemComponent.h index 9b5f32aa57..f922c59afe 100644 --- a/Gems/LyShine/Code/Source/LyShineSystemComponent.h +++ b/Gems/LyShine/Code/Source/LyShineSystemComponent.h @@ -22,9 +22,9 @@ namespace LyShine { - // LyShine depends on the LegacyAllocator and CryStringAllocator. This will be managed + // LyShine depends on the LegacyAllocator. This will be managed // by the LyShineSystemComponent - using LyShineAllocatorScope = AZ::AllocatorScope; + using LyShineAllocatorScope = AZ::AllocatorScope; class LyShineSystemComponent : public AZ::Component diff --git a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp index 318a165914..cbd0b2d6cb 100644 --- a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp +++ b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp @@ -20,7 +20,8 @@ bool UiClipboard::SetText(const AZStd::string& text) { if (text.length() > 0) { - auto wstr = CryStringUtils::UTF8ToWStr(text.c_str()); + AZStd::wstring wstr; + AZStd::to_wstring(wstr, text); const SIZE_T buffSize = (wstr.size() + 1) * sizeof(WCHAR); if (HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, buffSize)) { @@ -46,7 +47,7 @@ AZStd::string UiClipboard::GetText() if (HANDLE hText = GetClipboardData(CF_UNICODETEXT)) { const WCHAR* text = static_cast(GlobalLock(hText)); - outText = CryStringUtils::WStrToUTF8(text); + AZStd::to_string(outText, AZStd::wstring(text)); GlobalUnlock(hText); } CloseClipboard(); diff --git a/Gems/LyShine/Code/Source/StringUtfUtils.h b/Gems/LyShine/Code/Source/StringUtfUtils.h index 74a27afe9f..e10e691a6f 100644 --- a/Gems/LyShine/Code/Source/StringUtfUtils.h +++ b/Gems/LyShine/Code/Source/StringUtfUtils.h @@ -36,7 +36,8 @@ namespace LyShine // In the long run it would be better to eliminate // this function and use Unicode::CIterator<>::Position instead. wchar_t wcharString[2] = { static_cast(multiByteChar), 0 }; - AZStd::string utf8String(CryStringUtils::WStrToUTF8(wcharString)); + AZStd::string utf8String; + AZStd::to_string(utf8String, AZStd::wstring(wcharString)); int utf8Length = utf8String.length(); return utf8Length; } diff --git a/Gems/LyShine/Code/Source/UiButtonComponent.cpp b/Gems/LyShine/Code/Source/UiButtonComponent.cpp index bf0a67d08a..c6ba64848e 100644 --- a/Gems/LyShine/Code/Source/UiButtonComponent.cpp +++ b/Gems/LyShine/Code/Source/UiButtonComponent.cpp @@ -220,48 +220,9 @@ bool UiButtonComponent::VersionConverter(AZ::SerializeContext& context, // conversion from version 1 to 2: // - Need to convert CryString elements to AZStd::string // - Need to convert Color to Color and Alpha - if (classElement.GetVersion() < 2) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "SelectedSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "PressedSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "DisabledSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "SelectedColor", "SelectedAlpha")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "PressedColor", "PressedAlpha")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "DisabledColor", "DisabledAlpha")) - { - return false; - } - } - // conversion from version 2 to 3: // - Need to convert CryString ActionName elements to AZStd::string - if (classElement.GetVersion() < 3) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "ActionName")) - { - return false; - } - } + AZ_Assert(classElement.GetVersion() < 3, "Unsupported UiButtonComponent version: %d", classElement.GetVersion()); // conversion from version 3 to 4: // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference diff --git a/Gems/LyShine/Code/Source/UiImageComponent.cpp b/Gems/LyShine/Code/Source/UiImageComponent.cpp index 901c13d594..8f4145c07b 100644 --- a/Gems/LyShine/Code/Source/UiImageComponent.cpp +++ b/Gems/LyShine/Code/Source/UiImageComponent.cpp @@ -2663,18 +2663,7 @@ bool UiImageComponent::VersionConverter(AZ::SerializeContext& context, // conversion from version 1: // - Need to convert CryString elements to AZStd::string // - Need to convert Color to Color and Alpha - if (classElement.GetVersion() <= 1) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "SpritePath")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "Color", "Alpha")) - { - return false; - } - } + AZ_Assert(classElement.GetVersion() <= 1, "Unsupported UiImageComponent version: %d", classElement.GetVersion()); // conversion from version 1 or 2 to current: // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference diff --git a/Gems/LyShine/Code/Source/UiSerialize.cpp b/Gems/LyShine/Code/Source/UiSerialize.cpp index f44d011863..e0892596ff 100644 --- a/Gems/LyShine/Code/Source/UiSerialize.cpp +++ b/Gems/LyShine/Code/Source/UiSerialize.cpp @@ -31,67 +31,6 @@ namespace UiSerialize { - //////////////////////////////////////////////////////////////////////////////////////////////////// - class CryStringTCharSerializer - : public AZ::SerializeContext::IDataSerializer - { - /// Return the size of binary buffer necessary to store the value in binary format - size_t GetRequiredBinaryBufferSize(const void* classPtr) const - { - const CryStringT* string = reinterpret_cast*>(classPtr); - return string->length() + 1; - } - - /// Store the class data into a stream. - size_t Save(const void* classPtr, AZ::IO::GenericStream& stream, [[maybe_unused]] bool isDataBigEndian /*= false*/) override - { - const CryStringT* string = reinterpret_cast*>(classPtr); - const char* data = string->c_str(); - - return static_cast(stream.Write(string->length() + 1, reinterpret_cast(data))); - } - - size_t DataToText(AZ::IO::GenericStream& in, AZ::IO::GenericStream& out, [[maybe_unused]] bool isDataBigEndian /*= false*/) override - { - size_t len = in.GetLength(); - char* buffer = static_cast(azmalloc(len)); - in.Read(in.GetLength(), reinterpret_cast(buffer)); - - AZStd::string outText = buffer; - azfree(buffer); - - return static_cast(out.Write(outText.size(), outText.data())); - } - - size_t TextToData(const char* text, unsigned int textVersion, AZ::IO::GenericStream& stream, [[maybe_unused]] bool isDataBigEndian /*= false*/) override - { - (void)textVersion; - - size_t len = strlen(text) + 1; - stream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN); - return static_cast(stream.Write(len, reinterpret_cast(text))); - } - - bool Load(void* classPtr, AZ::IO::GenericStream& stream, unsigned int /*version*/, [[maybe_unused]] bool isDataBigEndian /*= false*/) override - { - CryStringT* string = reinterpret_cast*>(classPtr); - - size_t len = stream.GetLength(); - char* buffer = static_cast(azmalloc(len)); - - stream.Read(len, reinterpret_cast(buffer)); - - *string = buffer; - azfree(buffer); - return true; - } - - bool CompareValueData(const void* lhs, const void* rhs) override - { - return AZ::SerializeContext::EqualityCompareHelper >::CompareValues(lhs, rhs); - } - }; - ////////////////////////////////////////////////////////////////////////// void UiOffsetsScriptConstructor(UiTransform2dInterface::Offsets* thisPtr, AZ::ScriptDataContext& dc) { @@ -553,9 +492,6 @@ namespace UiSerialize if (serializeContext) { - serializeContext->Class >()-> - Serializer(&AZ::Serialize::StaticInstance::s_instance); - serializeContext->Class() ->Version(1) ->Field("SerializeString", &AnimationData::m_serializeData); diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp index 025c22a895..76a789c5cf 100644 --- a/Gems/LyShine/Code/Source/UiTextComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp @@ -4995,28 +4995,8 @@ bool UiTextComponent::VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) { // conversion from version 1: Need to convert Color to Color and Alpha - if (classElement.GetVersion() == 1) - { - if (!LyShine::ConvertSubElementFromCryStringToAssetRef(context, classElement, "FontFileName")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "Color", "Alpha")) - { - return false; - } - } - // conversion from version 1 or 2: Need to convert Text from CryString to AzString - if (classElement.GetVersion() <= 2) - { - // Call internal function to work-around serialization of empty AZ std string - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "Text")) - { - return false; - } - } + AZ_Assert(classElement.GetVersion() <= 2, "Unsupported UiTextComponent version: %d", classElement.GetVersion()); // Versions prior to v4: Change default font if (classElement.GetVersion() <= 3) diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp index e37d8787e1..c746d14095 100644 --- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp @@ -1185,7 +1185,8 @@ void UiTextInputComponent::UpdateDisplayedTextFunction() // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to // work for cases tested but may not in general. wchar_t wcharString[2] = { static_cast(this->GetReplacementCharacter()), 0 }; - AZStd::string replacementCharString(CryStringUtils::WStrToUTF8(wcharString)); + AZStd::string replacementCharString; + AZStd::to_string(replacementCharString, AZStd::wstring(wcharString)); int numReplacementChars = LyShine::GetUtf8StringLength(originalText); @@ -1475,54 +1476,10 @@ bool UiTextInputComponent::VersionConverter(AZ::SerializeContext& context, // conversion from version 1: // - Need to convert CryString elements to AZStd::string // - Need to convert Color to Color and Alpha - if (classElement.GetVersion() <= 1) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "SelectedSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "PressedSprite")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "SelectedColor", "SelectedAlpha")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromColorToColorPlusAlpha(context, classElement, "PressedColor", "PressedAlpha")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToChar(context, classElement, "ReplacementCharacter", defaultReplacementChar)) - { - return false; - } - } - // conversion from version 1 or 2 to current: // - Need to convert CryString ActionName elements to AZStd::string - if (classElement.GetVersion() <= 2) - { - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "ChangeAction")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "EndEditAction")) - { - return false; - } - - if (!LyShine::ConvertSubElementFromCryStringToAzString(context, classElement, "EnterAction")) - { - return false; - } - } - + AZ_Assert(classElement.GetVersion() <= 2, "Unsupported UiTextInputComponent version: %d", classElement.GetVersion()); + // conversion from version 1, 2 or 3 to current: // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference if (classElement.GetVersion() <= 3) diff --git a/Gems/LyShine/Code/Tests/SerializationTest.cpp b/Gems/LyShine/Code/Tests/SerializationTest.cpp index e5ed3638d4..70ae590358 100644 --- a/Gems/LyShine/Code/Tests/SerializationTest.cpp +++ b/Gems/LyShine/Code/Tests/SerializationTest.cpp @@ -24,7 +24,6 @@ namespace UnitTest appDesc.m_stackRecordLevels = 20; AZ::ComponentApplication::StartupParameters appStartup; - // Module needs to be created this way to create CryString allocator for test appStartup.m_createStaticModulesCallback = [](AZStd::vector& modules) { diff --git a/Gems/LyShine/Code/Tests/SpriteTest.cpp b/Gems/LyShine/Code/Tests/SpriteTest.cpp index 0ac3465cd7..84b47955b4 100644 --- a/Gems/LyShine/Code/Tests/SpriteTest.cpp +++ b/Gems/LyShine/Code/Tests/SpriteTest.cpp @@ -27,7 +27,6 @@ namespace UnitTest appDesc.m_stackRecordLevels = 20; AZ::ComponentApplication::StartupParameters appStartup; - // Module needs to be created this way to create CryString allocator for test appStartup.m_createStaticModulesCallback = [](AZStd::vector& modules) { diff --git a/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp index 114e768975..60d578d1f8 100644 --- a/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp @@ -52,7 +52,7 @@ void CCaptureTrack::GetKeyInfo(int key, const char*& description, float& duratio char prefix[64] = "Frame"; if (!m_keys[key].prefix.empty()) { - cry_strcpy(prefix, m_keys[key].prefix.c_str()); + azstrcpy(prefix, m_keys[key].prefix.c_str()); } description = buffer; if (!m_keys[key].folder.empty()) diff --git a/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp index c9a50a0979..1dd72de567 100644 --- a/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp @@ -25,7 +25,7 @@ void CCommentTrack::GetKeyInfo(int key, const char*& description, float& duratio description = 0; duration = m_keys[key].m_duration; - cry_strcpy(desc, m_keys[key].m_strComment.c_str()); + azstrcpy(desc, m_keys[key].m_strComment.c_str()); description = desc; } diff --git a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp index 5e1a63b4bc..278833cfe2 100644 --- a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp @@ -69,7 +69,7 @@ void CEventTrack::GetKeyInfo(int key, const char*& description, float& duration) CheckValid(); description = 0; duration = 0; - cry_strcpy(desc, m_keys[key].event.c_str()); + azstrcpy(desc, m_keys[key].event.c_str()); if (!m_keys[key].eventValue.empty()) { cry_strcat(desc, ", "); diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp index 4ffb7f0413..9e3fe212df 100644 --- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp @@ -916,7 +916,7 @@ void CAnimSceneNode::ApplyCameraKey(ISelectKey& key, SAnimContext& ec) void CAnimSceneNode::ApplyEventKey(IEventKey& key, [[maybe_unused]] SAnimContext& ec) { char funcName[1024]; - cry_strcpy(funcName, "Event_"); + azstrcpy(funcName, "Event_"); cry_strcat(funcName, key.event.c_str()); gEnv->pMovieSystem->SendGlobalEvent(funcName); } diff --git a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp index f6a0920901..3eca733a1d 100644 --- a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp @@ -143,7 +143,7 @@ void CTrackEventTrack::GetKeyInfo(int key, const char*& description, float& dura CheckValid(); description = 0; duration = 0; - cry_strcpy(desc, m_keys[key].event.c_str()); + azstrcpy(desc, m_keys[key].event.c_str()); if (!m_keys[key].eventValue.empty()) { cry_strcat(desc, ", "); diff --git a/Gems/Maestro/Code/Source/MaestroSystemComponent.h b/Gems/Maestro/Code/Source/MaestroSystemComponent.h index e5776c6628..b27075dbc0 100644 --- a/Gems/Maestro/Code/Source/MaestroSystemComponent.h +++ b/Gems/Maestro/Code/Source/MaestroSystemComponent.h @@ -17,10 +17,10 @@ namespace Maestro { - // Ensure that Maestro always has the LegacyAllocator and CryStringAllocators available + // Ensure that Maestro always has the LegacyAllocator available // NOTE: This component is only activated in the AssetBuilder, as the required allocators are // booted by the launcher or editor. - using MaestroAllocatorScope = AZ::AllocatorScope; + using MaestroAllocatorScope = AZ::AllocatorScope; class MaestroAllocatorComponent : public AZ::Component diff --git a/Gems/Metastream/Code/Tests/MetastreamTest.cpp b/Gems/Metastream/Code/Tests/MetastreamTest.cpp index c304a1c55f..4f1d37391a 100644 --- a/Gems/Metastream/Code/Tests/MetastreamTest.cpp +++ b/Gems/Metastream/Code/Tests/MetastreamTest.cpp @@ -38,12 +38,10 @@ protected: AZ::AllocatorInstance::Create(); AZ::AllocatorInstance::Create(); AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); } void TeardownEnvironment() override { - AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); AZ::AllocatorInstance::Destroy(); diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 96da22480d..0ccc77bba4 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -577,8 +577,6 @@ namespace PhysXDebug static void physx_Debug([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) { - using namespace CryStringUtils; - const int argumentCount = arguments.size(); if (argumentCount == 1) From 63d2f34ad6641546c81674a79ee39eb20370b90d Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 28 Jul 2021 11:06:14 -0700 Subject: [PATCH 016/205] more fixes, AtomFont still requires more work Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/ILocalizationManager.h | 30 +++++++++---------- .../Legacy/CryCommon/LocalizationManagerBus.h | 24 +++++++-------- .../AtomLyIntegration/AtomFont/AtomFont.h | 4 +-- .../AtomLyIntegration/AtomFont/AtomNullFont.h | 4 +-- .../AtomLyIntegration/AtomFont/FFont.h | 12 ++++---- .../AtomLyIntegration/AtomFont/FontRenderer.h | 2 +- .../AtomLyIntegration/AtomFont/FontTexture.h | 4 +-- .../AtomLyIntegration/AtomFont/GlyphCache.h | 2 +- .../AtomFont/Code/Source/FFontXML_Internal.h | 14 ++++----- 9 files changed, 47 insertions(+), 49 deletions(-) diff --git a/Code/Legacy/CryCommon/ILocalizationManager.h b/Code/Legacy/CryCommon/ILocalizationManager.h index de100152b3..2cba093f21 100644 --- a/Code/Legacy/CryCommon/ILocalizationManager.h +++ b/Code/Legacy/CryCommon/ILocalizationManager.h @@ -34,14 +34,14 @@ struct SLocalizedInfoGame } const char* szCharacterName; - string sUtf8TranslatedText; + AZStd::string sUtf8TranslatedText; bool bUseSubtitle; }; struct SLocalizedAdvancesSoundEntry { - string sName; + AZStd::string sName; float fValue; void GetMemoryUsage(ICrySizer* pSizer) const { @@ -178,12 +178,12 @@ struct ILocalizationManager // bEnglish - if true, translates the string into the always present English language. // Returns: // true if localization was successful, false otherwise - virtual bool LocalizeString_ch([[maybe_unused]] const char* sString, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } + virtual bool LocalizeString_ch([[maybe_unused]] const char* sString, [[maybe_unused]] AZStd::string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } // Summary: - // Same as LocalizeString( const char* sString, string& outLocalizedString, bool bEnglish=false ) + // Same as LocalizeString( const char* sString, AZStd::string& outLocalizedString, bool bEnglish=false ) // but at the moment this is faster. - virtual bool LocalizeString_s([[maybe_unused]] const string& sString, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } + virtual bool LocalizeString_s([[maybe_unused]] const AZStd::string& sString, [[maybe_unused]] AZStd::string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } // Summary: virtual void LocalizeAndSubstituteInternal([[maybe_unused]] AZStd::string& locString, [[maybe_unused]] const AZStd::vector& keys, [[maybe_unused]] const AZStd::vector& values) override {} @@ -196,7 +196,7 @@ struct ILocalizationManager // bEnglish - if true, returns the always present English version of the label. // Returns: // True if localization was successful, false otherwise. - virtual bool LocalizeLabel([[maybe_unused]] const char* sLabel, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } + virtual bool LocalizeLabel([[maybe_unused]] const char* sLabel, [[maybe_unused]] AZStd::string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } virtual bool IsLocalizedInfoFound([[maybe_unused]] const char* sKey) { return false; } // Summary: @@ -251,7 +251,7 @@ struct ILocalizationManager // sLocalizedString - Corresponding english language string. // Returns: // True if successful, false otherwise (key not found). - virtual bool GetEnglishString([[maybe_unused]] const char* sKey, [[maybe_unused]] string& sLocalizedString) override { return false; } + virtual bool GetEnglishString([[maybe_unused]] const char* sKey, [[maybe_unused]] AZStd::string& sLocalizedString) override { return false; } // Summary: // Get Subtitle for Key or Label . @@ -261,21 +261,21 @@ struct ILocalizationManager // bForceSubtitle - If true, get subtitle (sLocalized or sEnglish) even if not specified in Data file. // Returns: // True if subtitle found (and outSubtitle filled in), false otherwise. - virtual bool GetSubtitle([[maybe_unused]] const char* sKeyOrLabel, [[maybe_unused]] string& outSubtitle, [[maybe_unused]] bool bForceSubtitle = false) override { return false; } + virtual bool GetSubtitle([[maybe_unused]] const char* sKeyOrLabel, [[maybe_unused]] AZStd::string& outSubtitle, [[maybe_unused]] bool bForceSubtitle = false) override { return false; } // Description: // These methods format outString depending on sString with ordered arguments // FormatStringMessage(outString, "This is %2 and this is %1", "second", "first"); // Arguments: // outString - This is first and this is second. - virtual void FormatStringMessage_List([[maybe_unused]] string& outString, [[maybe_unused]] const string& sString, [[maybe_unused]] const char** sParams, [[maybe_unused]] int nParams) override {} - virtual void FormatStringMessage([[maybe_unused]] string& outString, [[maybe_unused]] const string& sString, [[maybe_unused]] const char* param1, [[maybe_unused]] const char* param2 = 0, [[maybe_unused]] const char* param3 = 0, [[maybe_unused]] const char* param4 = 0) override {} + virtual void FormatStringMessage_List([[maybe_unused]] AZStd::string& outString, [[maybe_unused]] const AZStd::string& sString, [[maybe_unused]] const char** sParams, [[maybe_unused]] int nParams) override {} + virtual void FormatStringMessage([[maybe_unused]] AZStd::string& outString, [[maybe_unused]] const AZStd::string& sString, [[maybe_unused]] const char* param1, [[maybe_unused]] const char* param2 = 0, [[maybe_unused]] const char* param3 = 0, [[maybe_unused]] const char* param4 = 0) override {} - virtual void LocalizeTime([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShowSeconds, [[maybe_unused]] string& outTimeString) override {} - virtual void LocalizeDate([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShort, [[maybe_unused]] bool bIncludeWeekday, [[maybe_unused]] string& outDateString) override {} - virtual void LocalizeDuration([[maybe_unused]] int seconds, [[maybe_unused]] string& outDurationString) override {} - virtual void LocalizeNumber([[maybe_unused]] int number, [[maybe_unused]] string& outNumberString) override {} - virtual void LocalizeNumber_Decimal([[maybe_unused]] float number, [[maybe_unused]] int decimals, [[maybe_unused]] string& outNumberString) override {} + virtual void LocalizeTime([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShowSeconds, [[maybe_unused]] AZStd::string& outTimeString) override {} + virtual void LocalizeDate([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShort, [[maybe_unused]] bool bIncludeWeekday, [[maybe_unused]] AZStd::string& outDateString) override {} + virtual void LocalizeDuration([[maybe_unused]] int seconds, [[maybe_unused]] AZStd::string& outDurationString) override {} + virtual void LocalizeNumber([[maybe_unused]] int number, [[maybe_unused]] AZStd::string& outNumberString) override {} + virtual void LocalizeNumber_Decimal([[maybe_unused]] float number, [[maybe_unused]] int decimals, [[maybe_unused]] AZStd::string& outNumberString) override {} // Summary: // Returns true if the project has localization configured for use, false otherwise. diff --git a/Code/Legacy/CryCommon/LocalizationManagerBus.h b/Code/Legacy/CryCommon/LocalizationManagerBus.h index 8daca5562a..69ab32cebf 100644 --- a/Code/Legacy/CryCommon/LocalizationManagerBus.h +++ b/Code/Legacy/CryCommon/LocalizationManagerBus.h @@ -99,12 +99,12 @@ public: // bEnglish - if true, translates the string into the always present English language. // Returns: // true if localization was successful, false otherwise - virtual bool LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish = false) = 0; + virtual bool LocalizeString_ch(const char* sString, AZStd::string& outLocalizedString, bool bEnglish = false) = 0; // Summary: // Same as LocalizeString( const char* sString, string& outLocalizedString, bool bEnglish=false ) // but at the moment this is faster. - virtual bool LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish = false) = 0; + virtual bool LocalizeString_s(const AZStd::string& sString, AZStd::string& outLocalizedString, bool bEnglish = false) = 0; // Set up system for passing in placeholder data for localized strings // Summary: @@ -138,7 +138,7 @@ public: // bEnglish - if true, returns the always present English version of the label. // Returns: // True if localization was successful, false otherwise. - virtual bool LocalizeLabel(const char* sLabel, string& outLocalizedString, bool bEnglish = false) = 0; + virtual bool LocalizeLabel(const char* sLabel, AZStd::string& outLocalizedString, bool bEnglish = false) = 0; // Summary: // Return number of localization entries. @@ -151,7 +151,7 @@ public: // sLocalizedString - Corresponding english language string. // Returns: // True if successful, false otherwise (key not found). - virtual bool GetEnglishString(const char* sKey, string& sLocalizedString) = 0; + virtual bool GetEnglishString(const char* sKey, AZStd::string& sLocalizedString) = 0; // Summary: // Get Subtitle for Key or Label . @@ -161,21 +161,21 @@ public: // bForceSubtitle - If true, get subtitle (sLocalized or sEnglish) even if not specified in Data file. // Returns: // True if subtitle found (and outSubtitle filled in), false otherwise. - virtual bool GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle = false) = 0; + virtual bool GetSubtitle(const char* sKeyOrLabel, AZStd::string& outSubtitle, bool bForceSubtitle = false) = 0; // Description: // These methods format outString depending on sString with ordered arguments // FormatStringMessage(outString, "This is %2 and this is %1", "second", "first"); // Arguments: // outString - This is first and this is second. - virtual void FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams) = 0; - virtual void FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) = 0; + virtual void FormatStringMessage_List(AZStd::string& outString, const AZStd::string& sString, const char** sParams, int nParams) = 0; + virtual void FormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) = 0; - virtual void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString) = 0; - virtual void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString) = 0; - virtual void LocalizeDuration(int seconds, string& outDurationString) = 0; - virtual void LocalizeNumber(int number, string& outNumberString) = 0; - virtual void LocalizeNumber_Decimal(float number, int decimals, string& outNumberString) = 0; + virtual void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString) = 0; + virtual void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString) = 0; + virtual void LocalizeDuration(int seconds, AZStd::string& outDurationString) = 0; + virtual void LocalizeNumber(int number, AZStd::string& outNumberString) = 0; + virtual void LocalizeNumber_Decimal(float number, int decimals, AZStd::string& outNumberString) = 0; // Summary: // Returns true if the project has localization configured for use, false otherwise. diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h index 7dd2629bd0..7636b45060 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h @@ -82,7 +82,7 @@ namespace AZ FontFamilyPtr GetFontFamily(const char* fontFamilyName) override; void AddCharsToFontTextures(FontFamilyPtr fontFamily, const char* chars, int glyphSizeX = ICryFont::defaultGlyphSizeX, int glyphSizeY = ICryFont::defaultGlyphSizeY) override; void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {} - string GetLoadedFontNames() const; + AZStd::string GetLoadedFontNames() const; void OnLanguageChanged() override; void ReloadAllFonts() override; ////////////////////////////////////////////////////////////////////////////////// @@ -124,7 +124,7 @@ namespace AZ //! \param fontFamilyName The name of the font family, or path to a font family file. //! \param outputDirectory Path to loaded font family (no filename), may need resolving with PathUtil::MakeGamePath. //! \param outputFullPath Full path to loaded font family, may need resolving with PathUtil::MakeGamePath. - XmlNodeRef LoadFontFamilyXml(const char* fontFamilyName, string& outputDirectory, string& outputFullPath); + XmlNodeRef LoadFontFamilyXml(const char* fontFamilyName, AZStd::string& outputDirectory, AZStd::string& outputFullPath); // Data::AssetBus::Handler overrides... void OnAssetReady(Data::Asset asset) override; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h index ebbdaf09d0..4820d1c176 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomNullFont.h @@ -42,7 +42,7 @@ namespace AZ size_t GetTextLength([[maybe_unused]] const char* str, [[maybe_unused]] const bool asciiMultiLine) const override { return 0; } - void WrapText(string& result, [[maybe_unused]] float maxWidth, const char* str, [[maybe_unused]] const TextDrawContext& ctx) override { result = str; } + void WrapText(AZStd::string& result, [[maybe_unused]] float maxWidth, const char* str, [[maybe_unused]] const TextDrawContext& ctx) override { result = str; } void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {} @@ -76,7 +76,7 @@ namespace AZ virtual FontFamilyPtr GetFontFamily([[maybe_unused]] const char* fontFamilyName) override { CRY_ASSERT(false); return nullptr; } virtual void AddCharsToFontTextures([[maybe_unused]] FontFamilyPtr fontFamily, [[maybe_unused]] const char* chars, [[maybe_unused]] int glyphSizeX, [[maybe_unused]] int glyphSizeY) override {}; virtual void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {} - virtual string GetLoadedFontNames() const override { return ""; } + virtual AZStd::string GetLoadedFontNames() const override { return ""; } virtual void OnLanguageChanged() override { } virtual void ReloadAllFonts() override { } diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 7974d0f2c1..6f56d912a0 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -122,7 +122,7 @@ namespace AZ struct FontEffect { - string m_name; + AZStd::string m_name; std::vector m_passes; FontEffect(const char* name) @@ -178,7 +178,7 @@ namespace AZ void DrawString(float x, float y, float z, const char* str, const bool asciiMultiLine, const TextDrawContext& ctx) override; Vec2 GetTextSize(const char* str, const bool asciiMultiLine, const TextDrawContext& ctx) override; size_t GetTextLength(const char* str, const bool asciiMultiLine) const override; - void WrapText(string& result, float maxWidth, const char* str, const TextDrawContext& ctx) override; + void WrapText(AZStd::string& result, float maxWidth, const char* str, const TextDrawContext& ctx) override; void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const override {}; void GetGradientTextureCoord(float& minU, float& minV, float& maxU, float& maxV) const override; unsigned int GetEffectId(const char* effectName) const override; @@ -215,7 +215,7 @@ namespace AZ FFont(AtomFont* atomFont, const char* fontName); FontTexture* GetFontTexture() const { return m_fontTexture; } - const string& GetName() const { return m_name; } + const AZStd::string& GetName() const { return m_name; } FontEffect* AddEffect(const char* effectName); FontEffect* GetDefaultEffect(); @@ -291,8 +291,8 @@ namespace AZ static constexpr uint32_t NumBuffers = 2; static constexpr float WindowScaleWidth = 800.0f; static constexpr float WindowScaleHeight = 600.0f; - string m_name; - string m_curPath; + AZStd::string m_name; + AZStd::string m_curPath; AZ::Name m_dynamicDrawContextName = AZ::Name(AZ::AtomFontDynamicDrawContextName); @@ -341,7 +341,7 @@ namespace AZ FFont* font = const_cast(static_cast(ptr)); if (font && font->m_atomFont) { - font->m_atomFont->UnregisterFont(font->m_name); + font->m_atomFont->UnregisterFont(font->m_name.c_str()); font->m_atomFont = nullptr; } diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontRenderer.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontRenderer.h index 9f95c12180..3cfb900055 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontRenderer.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontRenderer.h @@ -60,7 +60,7 @@ namespace AZ FontRenderer(); ~FontRenderer(); - int LoadFromFile(const string& fileName); + int LoadFromFile(const AZStd::string& fileName); int LoadFromMemory(unsigned char* buffer, int bufferSize); int Release(); diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h index 91fecfa3ef..b9bdce6810 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h @@ -74,7 +74,7 @@ namespace AZ FontTexture(); ~FontTexture(); - int CreateFromFile(const string& fileName, int width, int height, AZ::FontSmoothMethod smoothMethod, AZ::FontSmoothAmount smoothAmount, int widthCharCount = 16, int heightCharCount = 16); + int CreateFromFile(const AZStd::string& fileName, int width, int height, AZ::FontSmoothMethod smoothMethod, AZ::FontSmoothAmount smoothAmount, int widthCharCount = 16, int heightCharCount = 16); //! Default texture slot width/height is 16x8 slots, allowing for 128 glyphs to be stored in the font texture. This was //! previously 16x16, allowing 256 glyphs to be stored. For reference, there are 95 printable ASCII characters, so by @@ -129,7 +129,7 @@ namespace AZ // useful for special feature rendering interleaved with fonts (e.g. box behind the text) void CreateGradientSlot(); - int WriteToFile(const string& fileName); + int WriteToFile(const AZStd::string& fileName); void GetMemoryUsage([[maybe_unused]] ICrySizer* sizer) const {} diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h index cd37cb6b79..8c6cf721b3 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h @@ -79,7 +79,7 @@ namespace AZ int Create(int iCacheSize, int glyphBitmapWidth, int glyphBitmapHeight, FontSmoothMethod smoothMethod, FontSmoothAmount smoothAmount, float sizeRatio); int Release(); - int LoadFontFromFile(const string& fileName); + int LoadFontFromFile(const AZStd::string& fileName); int LoadFontFromMemory(unsigned char* fileBuffer, int dataSize); int ReleaseFont(); diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFontXML_Internal.h b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFontXML_Internal.h index 2cae7b45ee..ac6d140dfc 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFontXML_Internal.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFontXML_Internal.h @@ -36,7 +36,7 @@ namespace AtomFontInternal ELEMENT_PASS_BLEND = 14 }; - inline int GetBlendModeFromString(const string& str, bool dst) + inline int GetBlendModeFromString(const AZStd::string& str, bool dst) { int blend = GS_BLSRC_ONE; @@ -100,7 +100,7 @@ namespace AtomFontInternal ); } - inline AZ::FontSmoothMethod TranslateSmoothMethod(const string& value) + inline AZ::FontSmoothMethod TranslateSmoothMethod(const AZStd::string& value) { AZ::FontSmoothMethod smoothMethod = AZ::FontSmoothMethod::None; if (value == "blur") @@ -179,9 +179,8 @@ namespace AtomFontInternal void FoundElementImpl(); // notify methods - void FoundElement(const string& name) + void FoundElement(const AZStd::string& name) { - //MessageBox(NULL, string("[" + name + "]").c_str(), "FoundElement", MB_OK); // process the previous element switch (m_nElement) { @@ -246,9 +245,8 @@ namespace AtomFontInternal } } - void FoundAttribute(const string& name, const string& value) + void FoundAttribute(const AZStd::string& name, const AZStd::string& value) { - //MessageBox(NULL, string(name + "\n" + value).c_str(), "FoundAttribute", MB_OK); switch (m_nElement) { case ELEMENT_FONT: @@ -388,8 +386,8 @@ namespace AtomFontInternal AZ::FFont::FontEffect* m_effect; AZ::FFont::FontRenderingPass* m_pass; - string m_strFontPath; - string m_strFontEffectPath; + AZStd::string m_strFontPath; + AZStd::string m_strFontEffectPath; vector2l m_FontTexSize; AZ::AtomFont::GlyphSize m_slotSizes; float m_SizeRatio = IFFontConstants::defaultSizeRatio; From 72f808876c9bdaa4127edb2aae4b73e746858baa Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Wed, 28 Jul 2021 16:35:51 -0700 Subject: [PATCH 017/205] Improvements to pass statistics and SRG debugability Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- .../Atom/RHI.Reflect/ConstantsLayout.h | 5 +- .../Atom/RHI.Reflect/NameIdReflectionMap.h | 9 +++ .../RHI/Code/Include/Atom/RHI/ConstantsData.h | 8 +++ .../Atom/RHI/ShaderResourceGroupData.h | 3 + .../Atom/RHI/ShaderResourceGroupDebug.h | 21 ++++++ .../Source/RHI.Reflect/ConstantsLayout.cpp | 35 ++++++---- .../RHI/Code/Source/RHI/ConstantsData.cpp | 66 +++++++++++++++++++ .../Source/RHI/ShaderResourceGroupData.cpp | 5 ++ .../Source/RHI/ShaderResourceGroupDebug.cpp | 59 +++++++++++++++++ .../Atom/RHI/Code/atom_rhi_public_files.cmake | 2 + .../Include/Atom/RPI.Public/Pass/PassSystem.h | 15 ++++- .../RPI.Public/Pass/PassSystemInterface.h | 41 ++++++++---- .../Include/Atom/RPI.Public/Pass/RasterPass.h | 3 + .../Source/RPI.Public/Pass/PassSystem.cpp | 24 +++++++ .../Source/RPI.Public/Pass/RasterPass.cpp | 7 ++ .../Source/RPI.Public/Pass/RenderPass.cpp | 2 + ...AtomViewportDisplayInfoSystemComponent.cpp | 25 +++---- 17 files changed, 289 insertions(+), 41 deletions(-) create mode 100644 Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h create mode 100644 Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ConstantsLayout.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ConstantsLayout.h index 09415f1bc2..003a7dcd23 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ConstantsLayout.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ConstantsLayout.h @@ -81,6 +81,10 @@ namespace AZ //! If validation is disabled, true is always returned. bool ValidateAccess(ShaderInputConstantIndex inputIndex) const; + //! Prints to the console the shader input names specified by input list of indices + //! Will ignore any indices outside of the inputs array bounds + void DebugPrintNames(AZStd::array_view constantList) const; + protected: ConstantsLayout() = default; @@ -94,7 +98,6 @@ namespace AZ AZStd::vector m_inputs; IdReflectionMapForConstants m_idReflection; - AZStd::vector m_intervals; uint32_t m_sizeInBytes = 0; HashValue64 m_hash = InvalidHash; }; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/NameIdReflectionMap.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/NameIdReflectionMap.h index 7756e7d290..b6042ab34c 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/NameIdReflectionMap.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/NameIdReflectionMap.h @@ -68,6 +68,9 @@ namespace AZ /// Return the number of entries size_t Size() const; + // Returns true if size is zero + bool IsEmpty() const; + class NameIdReflectionMapSerializationEvents : public SerializeContext::IEventHandler { @@ -168,6 +171,12 @@ namespace AZ return m_reflectionMap.size(); } + template + bool NameIdReflectionMap::IsEmpty() const + { + return Size() == 0; + } + template void NameIdReflectionMap::Sort() { diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ConstantsData.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ConstantsData.h index 5fd10212d4..27bd418b8a 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ConstantsData.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ConstantsData.h @@ -84,6 +84,14 @@ namespace AZ //! Returns the constants layout. const ConstantsLayout* GetLayout() const; + //! Returns whether other constant data and this have the same value at the specified shader input index + bool ConstantIsEqual(const ConstantsData& other, ShaderInputConstantIndex inputIndex) const; + + //! Performs a diff between this and input constant data and returns a list of all the shader input indices + //! for which the constants are not the same between the two. If one of the two has more constants than the + //! other, these additional constants will be added to the end of the returned list. + AZStd::vector GetIndicesOfDifferingConstants(const ConstantsData& other) const; + private: enum class ValidateConstantAccessExpect : uint32_t { diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h index a145ba7ece..17ed3a64f1 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupData.h @@ -172,6 +172,9 @@ namespace AZ //! Different platforms might follow different packing rules for the internally-managed SRG constant buffer. AZStd::array_view GetConstantData() const; + //! Returns the underlying ConstantsData struct + const ConstantsData& GetConstantsData() const; + //! Returns the shader resource layout for this group. const ShaderResourceGroupLayout* GetLayout() const; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h new file mode 100644 index 0000000000..b81f9e0c0b --- /dev/null +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +namespace AZ +{ + namespace RHI + { + class ConstantsData; + struct DrawItem; + class ShaderResourceGroup; + + void PrintConstantDataDiff(const ShaderResourceGroup& shaderResourceGroup, ConstantsData& referenceData, bool updateReferenceData = false); + void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, u32 srgBindingSlot, bool updateReferenceData = false); + + } +} diff --git a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp index 3f9d9d9d63..fa85fbd884 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp @@ -17,10 +17,9 @@ namespace AZ if (SerializeContext* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) + ->Version(1) // Version 1: Adding debug helper functions to Shader Resource Groups ->Field("m_inputs", &ConstantsLayout::m_inputs) ->Field("m_idReflection", &ConstantsLayout::m_idReflection) - ->Field("m_intervals", &ConstantsLayout::m_intervals) ->Field("m_sizeInBytes", &ConstantsLayout::m_sizeInBytes) ->Field("m_hash", &ConstantsLayout::m_hash); } @@ -42,7 +41,6 @@ namespace AZ { m_inputs.clear(); m_idReflection.Clear(); - m_intervals.clear(); m_sizeInBytes = 0; m_hash = InvalidHash; } @@ -66,11 +64,8 @@ namespace AZ return false; } - // The constant data size is the maximum offset + size from the start of the struct. - constantDataSize = AZStd::max(constantDataSize, constantDescriptor.m_constantByteOffset + constantDescriptor.m_constantByteCount); - - // Add the [min, max) interval for the inline constant. - m_intervals.emplace_back(constantDescriptor.m_constantByteOffset, constantDescriptor.m_constantByteOffset + constantDescriptor.m_constantByteCount); + uint32_t end = constantDescriptor.m_constantByteOffset + constantDescriptor.m_constantByteCount; + constantDataSize = AZStd::max(constantDataSize, end); ++constantInputIndex; m_hash = TypeHash64(constantDescriptor.GetHash(), m_hash); @@ -99,7 +94,10 @@ namespace AZ Interval ConstantsLayout::GetInterval(ShaderInputConstantIndex inputIndex) const { - return m_intervals[inputIndex.GetIndex()]; + const ShaderInputConstantDescriptor& desc = GetShaderInput(inputIndex); + uint32_t start = desc.m_constantByteOffset; + uint32_t end = start + desc.m_constantByteCount; + return Interval(start, end); } const ShaderInputConstantDescriptor& ConstantsLayout::GetShaderInput(ShaderInputConstantIndex inputIndex) const @@ -138,8 +136,8 @@ namespace AZ { if (!m_sizeInBytes) { - AZ_Assert(m_intervals.empty(), "Constants size is not valid."); - return m_intervals.empty(); + AZ_Assert(m_idReflection.IsEmpty(), "Constants size is not valid."); + return m_idReflection.IsEmpty(); } } @@ -148,5 +146,20 @@ namespace AZ return true; } + + void ConstantsLayout::DebugPrintNames(AZStd::array_view constantList) const + { + AZStd::string output; + for (const ShaderInputConstantIndex& constandIdx : constantList) + { + if (constandIdx.GetIndex() < m_inputs.size()) + { + output += m_inputs[constandIdx.GetIndex()].m_name.GetCStr(); + output += " - "; + } + } + AZ_Printf("RHI", output.c_str()); + } + } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp b/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp index e00896d44e..29d451b4d5 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp @@ -404,5 +404,71 @@ namespace AZ AZ_Assert(m_layout, "Constants layout is null"); return m_layout.get(); } + + bool ConstantsData::ConstantIsEqual(const ConstantsData& other, ShaderInputConstantIndex inputIndex) const + { + AZStd::array_view myConstans = GetConstantRaw(inputIndex); + AZStd::array_view otherConstans = other.GetConstantRaw(inputIndex); + + // If they point to the same data, they are equal + if (myConstans == otherConstans) + { + return true; + } + + // If they point to data of different size, they are not equal + if (myConstans.size() != otherConstans.size()) + { + return false; + } + + // If they point to differing data of same size, compare the data + // Note: due to small size of data this loop will be faster than a mem compare + for(uint32_t i = 0; i < myConstans.size(); ++i) + { + if (myConstans[i] != otherConstans[i]) + { + return false; + } + } + + // Arrays point to different locations in memory but all bytes match, return true + return true; + } + + AZStd::vector ConstantsData::GetIndicesOfDifferingConstants(const ConstantsData& other) const + { + AZStd::vector differingIndices; + + if (m_layout == nullptr || other.m_layout == nullptr) + { + return differingIndices; + } + + AZStd::array_view myShaderInputs = m_layout->GetShaderInputList(); + AZStd::array_view otherShaderInputs = other.m_layout->GetShaderInputList(); + + size_t minSize = AZStd::min(myShaderInputs.size(), otherShaderInputs.size()); + size_t maxSize = AZStd::max(myShaderInputs.size(), otherShaderInputs.size()); + + for (size_t idx = 0; idx < minSize; ++idx) + { + const ShaderInputConstantIndex inputIndex(idx); + if (!ConstantIsEqual(other, inputIndex)) + { + differingIndices.push_back(inputIndex); + } + } + + // If sizes are different, add difference at the end + for (size_t idx = minSize; idx < maxSize; ++idx) + { + const ShaderInputConstantIndex inputIndex(idx); + differingIndices.push_back(inputIndex); + } + + return differingIndices; + } + } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupData.cpp b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupData.cpp index f2b57bf1e5..65499fb57d 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupData.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupData.cpp @@ -334,5 +334,10 @@ namespace AZ return m_constantsData.GetConstantData(); } + const ConstantsData& ShaderResourceGroupData::GetConstantsData() const + { + return m_constantsData; + } + } // namespace RHI } // namespace AZ diff --git a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp new file mode 100644 index 0000000000..4bd8d0aab8 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include + +namespace AZ +{ + namespace RHI + { + + void PrintConstantDataDiff(const ShaderResourceGroup& shaderResourceGroup, ConstantsData& referenceData, bool updateReferenceData) + { + const RHI::ConstantsData& currentData = shaderResourceGroup.GetData().GetConstantsData(); + + AZStd::vector differingIndices = currentData.GetIndicesOfDifferingConstants(referenceData); + + if (differingIndices.size() > 0) + { + AZ_Printf("RHI", "Detected different SRG values for the following fields:\n"); + if (currentData.GetLayout()) + { + currentData.GetLayout()->DebugPrintNames(differingIndices); + } + } + + if (updateReferenceData) + { + referenceData = currentData; + } + } + + void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, u32 srgBindingSlot, bool updateReferenceData) + { + s32 srgIndex = -1; + for (u32 i = 0; i < drawItem.m_shaderResourceGroupCount; ++i) + { + if (drawItem.m_shaderResourceGroups[i]->GetBindingSlot() == srgBindingSlot) + { + srgIndex = i; + break; + } + } + + if (srgIndex != -1) + { + const ShaderResourceGroup& srg = *drawItem.m_shaderResourceGroups[srgIndex]; + PrintConstantDataDiff(srg, referenceData, updateReferenceData); + } + } + + } +} diff --git a/Gems/Atom/RHI/Code/atom_rhi_public_files.cmake b/Gems/Atom/RHI/Code/atom_rhi_public_files.cmake index b489cbbbb4..2bf2acd892 100644 --- a/Gems/Atom/RHI/Code/atom_rhi_public_files.cmake +++ b/Gems/Atom/RHI/Code/atom_rhi_public_files.cmake @@ -156,10 +156,12 @@ set(FILES Source/RHI/ScopeAttachment.cpp Include/Atom/RHI/ShaderResourceGroup.h Include/Atom/RHI/ShaderResourceGroupData.h + Include/Atom/RHI/ShaderResourceGroupDebug.h Include/Atom/RHI/ShaderResourceGroupInvalidateRegistry.h Include/Atom/RHI/ShaderResourceGroupPool.h Source/RHI/ShaderResourceGroup.cpp Source/RHI/ShaderResourceGroupData.cpp + Source/RHI/ShaderResourceGroupDebug.cpp Source/RHI/ShaderResourceGroupInvalidateRegistry.cpp Source/RHI/ShaderResourceGroupPool.cpp Include/Atom/RHI/MemoryStatisticsBuilder.h diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h index de57e2e3f6..5998798ae8 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystem.h @@ -74,6 +74,12 @@ namespace AZ const AZ::Name& GetTargetedPassDebuggingName() const override; void ConnectEvent(OnReadyLoadTemplatesEvent::Handler& handler) override; PassSystemState GetState() const override; + SwapChainPass* FindSwapChainPass(AzFramework::NativeWindowHandle windowHandle) const override; + + // PassSystemInterface statistics related functions + void IncrementFrameDrawItemCount(u32 numDrawItems) override; + void IncrementFrameRenderPassCount() override; + PassSystemFrameStatistics GetFrameStatistics() override; // PassSystemInterface factory related functions... void AddPassCreator(Name className, PassCreator createFunction) override; @@ -92,7 +98,6 @@ namespace AZ void RegisterPass(Pass* pass) override; void UnregisterPass(Pass* pass) override; AZStd::vector FindPasses(const PassFilter& passFilter) const override; - SwapChainPass* FindSwapChainPass(AzFramework::NativeWindowHandle windowHandle) const override; private: // Returns the root of the pass tree hierarchy @@ -115,6 +120,9 @@ namespace AZ void QueueForRemoval(Pass* pass) override; void QueueForInitialization(Pass* pass) override; + // Resets the frame statistic counters + void ResetFrameStatistics(); + // Lists for queuing passes for various function calls // Name of the list reflects the pass function it will call AZStd::vector< Ptr > m_buildPassList; @@ -140,13 +148,16 @@ namespace AZ AZ::Name m_targetedPassDebugName; // Counts the number of passes - int32_t m_passCounter = 0; + u32 m_passCounter = 0; // Events OnReadyLoadTemplatesEvent m_loadTemplatesEvent; // Used to track what phase of execution the pass system is in PassSystemState m_state = PassSystemState::Unitialized; + + // Counters used to gather statistics about the frame + PassSystemFrameStatistics m_frameStatistics; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h index cc66a7c228..246e43a2f7 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/PassSystemInterface.h @@ -66,6 +66,14 @@ namespace AZ FrameEnd, }; + //! Frame counters used for collecting statistics + struct PassSystemFrameStatistics + { + u32 m_numRenderPassesExecuted = 0; + u32 m_totalDrawItemsRendered = 0; + u32 m_maxDrawItemsRenderedInAPass = 0; + }; + class PassSystemInterface { friend class Pass; @@ -115,6 +123,27 @@ namespace AZ virtual void SetTargetedPassDebuggingName(const AZ::Name& targetPassName) = 0; virtual const AZ::Name& GetTargetedPassDebuggingName() const = 0; + //! Find the SwapChainPass associated with window Handle + virtual SwapChainPass* FindSwapChainPass(AzFramework::NativeWindowHandle windowHandle) const = 0; + + using OnReadyLoadTemplatesEvent = AZ::Event<>; + //! Connect a handler to listen to the event that the pass system is ready to load pass templates + //! The event is triggered when pass system is initialized and asset system is ready. + //! The handler can add new pass templates or load pass template mappings from assets + virtual void ConnectEvent(OnReadyLoadTemplatesEvent::Handler& handler) = 0; + + virtual PassSystemState GetState() const = 0; + + // Passes call this function to notify the pass system that they are drawing X draw items this frame + // Used for Pass System statistics + virtual void IncrementFrameDrawItemCount(u32 numDrawItems) = 0; + + // Increments the counter for the number of render passes executed this frame (does not include passes that are disabled) + virtual void IncrementFrameRenderPassCount() = 0; + + // Get frame statistics from the Pass System + virtual PassSystemFrameStatistics GetFrameStatistics() = 0; + // --- Pass Factory related functionality --- //! Directly creates a pass given a PassDescriptor @@ -171,17 +200,6 @@ namespace AZ //! Find matching passes from registered passes with specified filter virtual AZStd::vector FindPasses(const PassFilter& passFilter) const = 0; - //! Find the SwapChainPass associated with window Handle - virtual SwapChainPass* FindSwapChainPass(AzFramework::NativeWindowHandle windowHandle) const = 0; - - using OnReadyLoadTemplatesEvent = AZ::Event<>; - //! Connect a handler to listen to the event that the pass system is ready to load pass templates - //! The event is triggered when pass system is initialized and asset system is ready. - //! The handler can add new pass templates or load pass template mappings from assets - virtual void ConnectEvent(OnReadyLoadTemplatesEvent::Handler& handler) = 0; - - virtual PassSystemState GetState() const = 0; - private: // These functions are only meant to be used by the Pass class @@ -199,7 +217,6 @@ namespace AZ //! Unregisters the pass with the pass library. Called in the Pass destructor. virtual void UnregisterPass(Pass* pass) = 0; - }; namespace PassSystemEvents diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h index 735b3930c8..b0d941083b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h @@ -42,6 +42,8 @@ namespace AZ //! Expose shader resource group. ShaderResourceGroup* GetShaderResourceGroup(); + u32 GetDrawItemCount(); + protected: explicit RasterPass(const PassDescriptor& descriptor); @@ -68,6 +70,7 @@ namespace AZ RHI::Viewport m_viewportState; bool m_overrideScissorSate = false; bool m_overrideViewportState = false; + u32 m_drawItemCount = 0; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index 91cc645947..3092b9ecd0 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -308,6 +308,7 @@ namespace AZ AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: FrameUpdate"); + ResetFrameStatistics(); ProcessQueuedChanges(); m_state = PassSystemState::Rendering; @@ -392,6 +393,29 @@ namespace AZ handler.Connect(m_loadTemplatesEvent); } + void PassSystem::ResetFrameStatistics() + { + m_frameStatistics.m_numRenderPassesExecuted = 0; + m_frameStatistics.m_totalDrawItemsRendered = 0; + m_frameStatistics.m_maxDrawItemsRenderedInAPass = 0; + } + + PassSystemFrameStatistics PassSystem::GetFrameStatistics() + { + return m_frameStatistics; + } + + void PassSystem::IncrementFrameDrawItemCount(u32 numDrawItems) + { + m_frameStatistics.m_totalDrawItemsRendered += numDrawItems; + m_frameStatistics.m_maxDrawItemsRenderedInAPass = AZStd::max(m_frameStatistics.m_maxDrawItemsRenderedInAPass, numDrawItems); + } + + void PassSystem::IncrementFrameRenderPassCount() + { + ++m_frameStatistics.m_numRenderPassesExecuted; + } + // --- Pass Factory Functions --- void PassSystem::AddPassCreator(Name className, PassCreator createFunction) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp index ee38c1e5ef..ae74e355f2 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp @@ -112,6 +112,11 @@ namespace AZ return m_shaderResourceGroup.get(); } + u32 RasterPass::GetDrawItemCount() + { + return m_drawItemCount; + } + // --- Pass behaviour overrides --- void RasterPass::Validate(PassValidationResults& validationResults) @@ -145,6 +150,8 @@ namespace AZ // Draw List m_drawListView = view->GetDrawList(m_drawListTag); + m_drawItemCount = m_drawListView.size(); + PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); } RenderPass::FrameBeginInternal(params); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp index 96649573b2..92e6d8b2b6 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RenderPass.cpp @@ -200,6 +200,8 @@ namespace AZ m_attachmentCopy.lock()->FrameBegin(params); } CollectSrgs(); + + PassSystemInterface::Get()->IncrementFrameRenderPassCount(); } diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index af9fd7fdd8..ef341f8dc8 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -229,25 +229,20 @@ namespace AZ::Render AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); auto rootPass = viewportContext->GetCurrentPipeline()->GetRootPass(); const RPI::PipelineStatisticsResult stats = rootPass->GetLatestPipelineStatisticsResult(); - AZStd::function)> containingPassCount = [&containingPassCount](const AZ::RPI::Ptr pass) - { - int count = 1; - if (auto passAsParent = pass->AsParent()) - { - for (const auto& child : passAsParent->GetChildren()) - { - count += containingPassCount(child); - } - } - return count; - }; - const int numPasses = containingPassCount(rootPass); + + RPI::PassSystemFrameStatistics passSystemFrameStatistics = AZ::RPI::PassSystemInterface::Get()->GetFrameStatistics(); + DrawLine(AZStd::string::format( - "Total Passes: %d Vertex Count: %lld Primitive Count: %lld", - numPasses, + "RenderPasses: %d Vertex Count: %lld Primitive Count: %lld", + passSystemFrameStatistics.m_numRenderPassesExecuted, aznumeric_cast(stats.m_vertexCount), aznumeric_cast(stats.m_primitiveCount) )); + DrawLine(AZStd::string::format( + "Total Draw Item Count: %d Max Draw Items in a Pass: %d", + passSystemFrameStatistics.m_totalDrawItemsRendered, + passSystemFrameStatistics.m_maxDrawItemsRenderedInAPass + )); } void AtomViewportDisplayInfoSystemComponent::UpdateFramerate() From 56eda61828f9fb9beaf328ad2107de00ffd482f6 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:49:44 -0700 Subject: [PATCH 018/205] remove of UNICODE/_UNICODE Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../WinAPI/AzCore/Debug/Trace_WinAPI.cpp | 4 - .../WinAPI/AzCore/IO/SystemFile_WinAPI.cpp | 115 +----------------- .../Module/DynamicModuleHandle_WinAPI.cpp | 5 - .../AzCore/std/parallel/config_WinAPI.h | 12 +- .../Windows/AzCore/PlatformIncl_Windows.h | 1 + Code/Legacy/CryCommon/AppleSpecific.h | 5 - Code/Legacy/CryCommon/LinuxSpecific.h | 5 - Code/Legacy/CryCommon/platform.h | 2 +- 8 files changed, 5 insertions(+), 144 deletions(-) diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp index d4a0f52941..143bd8f9d0 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp @@ -61,16 +61,12 @@ namespace AZ void OutputToDebugger(const char* window, const char* message) { AZ_UNUSED(window); -#ifdef _UNICODE wchar_t messageW[g_maxMessageLength]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, messageW, message, g_maxMessageLength - 1) == 0) { OutputDebugStringW(messageW); } -#else // !_UNICODE - OutputDebugString(message); -#endif // !_UNICODE } } } diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp index 090e29a535..15d779017d 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/SystemFile_WinAPI.cpp @@ -28,7 +28,6 @@ namespace //========================================================================= DWORD GetAttributes(const char* fileName) { -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) @@ -39,9 +38,6 @@ namespace { return INVALID_FILE_ATTRIBUTES; } -#else //!_UNICODE - return GetFileAttributes(fileName); -#endif // !_UNICODE } //========================================================================= @@ -51,7 +47,6 @@ namespace //========================================================================= BOOL SetAttributes(const char* fileName, DWORD fileAttributes) { -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) @@ -62,9 +57,6 @@ namespace { return FALSE; } -#else //!_UNICODE - return SetFileAttributes(fileName, fileAttributes); -#endif // !_UNICODE } //========================================================================= @@ -76,7 +68,6 @@ namespace // * GetLastError() on Windows-like platforms // * errno on Unix platforms //========================================================================= -#if defined(_UNICODE) bool CreateDirRecursive(wchar_t* dirPath) { if (CreateDirectoryW(dirPath, nullptr)) @@ -112,53 +103,6 @@ namespace } return false; } -#else - bool CreateDirRecursive(char* dirPath) - { - if (CreateDirectory(dirPath, nullptr)) - { - return true; // Created without error - } - DWORD error = GetLastError(); - if (error == ERROR_PATH_NOT_FOUND) - { - // try to create our parent hierarchy - for (size_t i = strlen(dirPath); i > 0; --i) - { - if (dirPath[i] == '/' || dirPath[i] == '\\') - { - char delimiter = dirPath[i]; - dirPath[i] = 0; // null-terminate at the previous slash - bool ret = CreateDirRecursive(dirPath); - dirPath[i] = delimiter; // restore slash - if (ret) - { - // now that our parent is created, try to create again - if (CreateDirectory(dirPath, nullptr)) - { - return true; - } - DWORD creationError = GetLastError(); - if (creationError == ERROR_ALREADY_EXISTS) - { - DWORD attributes = GetFileAttributes(dirPath); - return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; - } - return false; - } - return false; - } - } - // if we reach here then there was no parent folder to create, so we failed for other reasons - } - else if (error == ERROR_ALREADY_EXISTS) - { - DWORD attributes = GetFileAttributes(dirPath); - return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; - } - return false; - } -#endif static const SystemFile::FileHandleType PlatformSpecificInvalidHandle = INVALID_HANDLE_VALUE; } @@ -208,7 +152,6 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags) CreatePath(m_fileName.c_str()); } -# ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; m_handle = INVALID_HANDLE_VALUE; @@ -216,9 +159,6 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags) { m_handle = CreateFileW(fileNameW, dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0); } -# else //!_UNICODE - m_handle = CreateFile(m_fileName.c_str(), dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0); -# endif // !_UNICODE if (m_handle == INVALID_HANDLE_VALUE) { @@ -417,7 +357,6 @@ namespace Platform HANDLE hFile; int lastError; -#ifdef _UNICODE wchar_t filterW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; hFile = INVALID_HANDLE_VALUE; @@ -425,39 +364,28 @@ namespace Platform { hFile = FindFirstFile(filterW, &fd); } -#else // !_UNICODE - hFile = FindFirstFile(filter, &fd); -#endif // !_UNICODE if (hFile != INVALID_HANDLE_VALUE) { const char* fileName; -#ifdef _UNICODE char fileNameA[AZ_MAX_PATH_LEN]; fileName = NULL; if (wcstombs_s(&numCharsConverted, fileNameA, fd.cFileName, AZ_ARRAY_SIZE(fileNameA) - 1) == 0) { fileName = fileNameA; } -#else // !_UNICODE - fileName = fd.cFileName; -#endif // !_UNICODE cb(fileName, (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0); // List all the other files in the directory. - while (FindNextFile(hFile, &fd) != 0) + while (FindNextFileW(hFile, &fd) != 0) { -#ifdef _UNICODE fileName = NULL; if (wcstombs_s(&numCharsConverted, fileNameA, fd.cFileName, AZ_ARRAY_SIZE(fileNameA) - 1) == 0) { fileName = fileNameA; } -#else // !_UNICODE - fileName = fd.cFileName; -#endif // !_UNICODE cb(fileName, (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0); } @@ -483,16 +411,12 @@ namespace Platform { HANDLE handle = nullptr; -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) { handle = CreateFileW(fileNameW, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); } -#else // !_UNICODE - handle = CreateFileA(fileName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); -#endif // !_UNICODE if (handle == INVALID_HANDLE_VALUE) { @@ -524,16 +448,12 @@ namespace Platform WIN32_FILE_ATTRIBUTE_DATA data = { 0 }; BOOL result = FALSE; -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) { result = GetFileAttributesExW(fileNameW, GetFileExInfoStandard, &data); } -#else // !_UNICODE - result = GetFileAttributesExA(fileName, GetFileExInfoStandard, &data); -#endif // !_UNICODE if (result) { @@ -553,7 +473,6 @@ namespace Platform bool Delete(const char* fileName) { -#ifdef _UNICODE wchar_t fileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, fileNameW, fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0) @@ -568,20 +487,12 @@ namespace Platform { return false; } -#else // !_UNICODE - if (DeleteFile(fileName) == 0) - { - EBUS_EVENT(FileIOEventBus, OnError, nullptr, fileName, (int)GetLastError()); - return false; - } -#endif // !_UNICODE return true; } bool Rename(const char* sourceFileName, const char* targetFileName, bool overwrite) { -#ifdef _UNICODE wchar_t sourceFileNameW[AZ_MAX_PATH_LEN]; wchar_t targetFileNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; @@ -598,13 +509,6 @@ namespace Platform { return false; } -#else // !_UNICODE - if (MoveFileEx(sourceFileName, targetFileName, overwrite ? MOVEFILE_REPLACE_EXISTING : 0) == 0) - { - EBUS_EVENT(FileIOEventBus, OnError, nullptr, sourceFileName, (int)GetLastError()); - return false; - } -#endif // !_UNICODE return true; } @@ -639,7 +543,6 @@ namespace Platform { if (dirName) { -#if defined(_UNICODE) wchar_t dirPath[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, dirPath, dirName, AZ_ARRAY_SIZE(dirPath) - 1) == 0) @@ -651,18 +554,6 @@ namespace Platform } return success; } -#else - char dirPath[AZ_MAX_PATH_LEN]; - if (azstrcpy(dirPath, AZ_ARRAY_SIZE(dirPath), dirName) == 0) - { - bool success = CreateDirRecursive(dirPath); - if (!success) - { - EBUS_EVENT(FileIOEventBus, OnError, nullptr, dirName, (int)GetLastError()); - } - return success; - } -#endif } return false; } @@ -671,16 +562,12 @@ namespace Platform { if (dirName) { -#if defined(_UNICODE) wchar_t dirNameW[AZ_MAX_PATH_LEN]; size_t numCharsConverted; if (mbstowcs_s(&numCharsConverted, dirNameW, dirName, AZ_ARRAY_SIZE(dirNameW) - 1) == 0) { return RemoveDirectory(dirNameW) != 0; } -#else - return RemoveDirectory(dirName) != 0; -#endif } return false; diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp index cc04fb6bd5..659650d2e2 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Module/DynamicModuleHandle_WinAPI.cpp @@ -98,7 +98,6 @@ namespace AZ bool alreadyLoaded = false; -# ifdef _UNICODE wchar_t fileNameW[MAX_PATH]; size_t numCharsConverted; errno_t wcharResult = mbstowcs_s(&numCharsConverted, fileNameW, m_fileName.c_str(), AZ_ARRAY_SIZE(fileNameW) - 1); @@ -114,10 +113,6 @@ namespace AZ m_handle = NULL; return LoadStatus::LoadFailure; } -# else //!_UNICODE - alreadyLoaded = NULL != GetModuleHandleA(m_fileName.c_str()); - m_handle = LoadLibraryA(m_fileName.c_str()); -# endif // !_UNICODE if (m_handle) { diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h index fe7620c173..fb91e4d503 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h @@ -75,22 +75,14 @@ extern "C" AZ_DLL_IMPORT HANDLE _stdcall CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCWSTR lpName); AZ_DLL_IMPORT BOOL _stdcall ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount); #ifndef CreateSemaphore - #ifdef UNICODE - #define CreateSemaphore CreateSemaphoreW - #else - #define CreateSemaphore CreateSemaphoreA - #endif + #define CreateSemaphore CreateSemaphoreW #endif // Event AZ_DLL_IMPORT HANDLE _stdcall CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName); AZ_DLL_IMPORT HANDLE _stdcall CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCWSTR lpName); #ifndef CreateEvent - #ifdef UNICODE - #define CreateEvent CreateEventW - #else - #define CreateEvent CreateEventA - #endif + #define CreateEvent CreateEventW #endif AZ_DLL_IMPORT BOOL _stdcall SetEvent(HANDLE); } diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/PlatformIncl_Windows.h b/Code/Framework/AzCore/Platform/Windows/AzCore/PlatformIncl_Windows.h index 6adef282eb..f58e772155 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/PlatformIncl_Windows.h +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/PlatformIncl_Windows.h @@ -9,6 +9,7 @@ #pragma once #define WIN32_LEAN_AND_MEAN +#define UNICODE //#define NOGDICAPMASKS //- CC_*, LC_*, PC_*, CP_*, TC_*, RC_ //#define NOVIRTUALKEYCODES //- VK_* //#define NOWINMESSAGES //- WM_*, EM_*, LB_*, CB_* diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index 4d17c18bac..caf85a8f44 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -192,13 +192,8 @@ typedef WCHAR* LPUWSTR, * PUWSTR; typedef const WCHAR* LPCWSTR, * PCWSTR; typedef const WCHAR* LPCUWSTR, * PCUWSTR; -#ifdef UNICODE typedef LPCWSTR LPCTSTR; typedef LPWSTR LPTSTR; -#else -typedef LPCSTR LPCTSTR; -typedef LPSTR LPTSTR; -#endif typedef DWORD COLORREF; #define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h index 5fc1f7b801..72673cafe3 100644 --- a/Code/Legacy/CryCommon/LinuxSpecific.h +++ b/Code/Legacy/CryCommon/LinuxSpecific.h @@ -156,13 +156,8 @@ typedef WCHAR* LPUWSTR, * PUWSTR; typedef const WCHAR* LPCWSTR, * PCWSTR; typedef const WCHAR* LPCUWSTR, * PCUWSTR; -#ifdef UNICODE typedef LPCWSTR LPCTSTR; typedef LPWSTR LPTSTR; -#else -typedef LPCSTR LPCTSTR; -typedef LPSTR LPTSTR; -#endif typedef char TCHAR; typedef DWORD COLORREF; diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 60edf10de9..c040139b5a 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -176,7 +176,7 @@ // In Win32 Release we use static linkage #ifdef WIN32 - #if !defined(_RELEASE) || defined(RESOURCE_COMPILER) || defined(EDITOR) || defined(_FORCEDLL) + #if !defined(_RELEASE) || defined(EDITOR) || defined(_FORCEDLL) // All windows targets not in Release built as DLLs. #ifndef _USRDLL #define _USRDLL From f21fc79dc45842c67ce7640b8bf061963ccf78de Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:50:24 -0700 Subject: [PATCH 019/205] remove of unicode files from Cry Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/UnicodeBinding.h | 946 -------------- Code/Legacy/CryCommon/UnicodeEncoding.h | 767 ----------- Code/Legacy/CryCommon/UnicodeFunctions.h | 1265 ------------------- Code/Legacy/CryCommon/UnicodeIterator.h | 615 --------- Code/Legacy/CryCommon/crycommon_files.cmake | 4 - 5 files changed, 3597 deletions(-) delete mode 100644 Code/Legacy/CryCommon/UnicodeBinding.h delete mode 100644 Code/Legacy/CryCommon/UnicodeEncoding.h delete mode 100644 Code/Legacy/CryCommon/UnicodeFunctions.h delete mode 100644 Code/Legacy/CryCommon/UnicodeIterator.h diff --git a/Code/Legacy/CryCommon/UnicodeBinding.h b/Code/Legacy/CryCommon/UnicodeBinding.h deleted file mode 100644 index aaefcf0f55..0000000000 --- a/Code/Legacy/CryCommon/UnicodeBinding.h +++ /dev/null @@ -1,946 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Note: The utilities in this file should typically not be used directly, -// consider including UnicodeFunctions.h or UnicodeIterator.h instead. -// -// (At least) the following string types can be bound with these helper functions: -// Types Input Output Null-Terminator -// std::basic_string, std::string, std::wstring: yes yes implied by type -// QString: yes yes implied by type -// std::vector, std::list, std::deque: yes yes not present -// T[] (fixed-length buffer): yes yes guaranteed to be emitted on output, accepted on input -// T * and size_t (user-specified-size buffer): no yes guaranteed to be emitted on output -// const T * (null-terminated string): yes no expected -// const T[] (literal): yes no implied as the last item in the array -// pair of iterators over T: yes no should not be included in the range -// uint32 (single UCS code-point): yes no not present -// If some other string type is not listed, you can still use it for input easily by passing begin/end iterators. -// Note: For all types, T can be any 8-bit, 16-bit or 32-bit integral or character type. -// Further T types may be processed by explicitly passing InputEncoding and OutputEncoding. -// We never actively tested such scenario's, so no guarantees on floating and user-defined types as code-units. - - -#pragma once - -#ifndef assert -// Some tools use CRT's assert, most engine and game modules use CryAssert.h (via platform.h maybe). -// We don't want to force a choice upon all code that uses Unicode utilities, so we just assume assert is defined. -#error This header uses assert macro, please provide an applicable definition before including UnicodeXXX.h -#endif - -#include "UnicodeEncoding.h" -#include // For str(n)len and memcpy. -#include // For wcs(n)len. -#include // For size_t and ptrdiff_t. -#include // For std::iterator_traits. -#include // For std::basic_string. -#include // For std::vector. -#include // For std::list. -#include // For std::deque. -#include // ... standard type-traits (as of C++11). - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define UNICODEBINDING_H_SECTION_1 1 -#define UNICODEBINDING_H_SECTION_2 2 -#endif - -// Forward declare the supported types. -// Before actually instantiating a binding however, you need to have the full definition included. -// Also, this allows us to work with QChar/QString as declared names without a dependency on Qt. -namespace AZStd -{ - template - class basic_fixed_string; -} -class QChar; -class QString; - -namespace Unicode -{ - namespace Detail - { - // Import standard type traits. - // This requires C++11 compiler support. - using std::add_const; - using std::conditional; - using std::extent; - using std::integral_constant; - using std::is_arithmetic; - using std::is_array; - using std::is_base_of; - using std::is_const; - using std::is_convertible; - using std::is_integral; - using std::is_pointer; - using std::is_same; - using std::make_unsigned; - using std::remove_cv; - using std::remove_extent; - using std::remove_pointer; - - // SVoid: - // Result type will be void if T is well-formed. - // Note: This is mostly used to test the presence of member types at compile-time. - template - struct SVoid - { - typedef void type; - }; - - // SValidChar: - // Determine if T is a valid character type in the given compile-time context. - // The InferEncoding flag is set if the encoding has to be detected automatically. - // The Input flag is set if the type is used for input (and not set if the type is used for output). - template - struct SValidChar - { - typedef typename remove_cv::type BaseType; - static const bool isArithmeticType = is_arithmetic::value; - static const bool isQChar = is_same::value; - static const bool isUsable = isArithmeticType || isQChar; - static const bool isValidQualified = !is_const::value || Input; - static const bool isKnownSize = sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4; - static const bool isValidInferred = isKnownSize || !InferEncoding; - static const bool value = isUsable && isValidQualified && isValidInferred; - }; - - // SPackedIterators: - // A pair of iterators over some range. - // Note: Packing iterators into a single object allows us to pass them as a single argument like all other types. - template - struct SPackedIterators - { - const T begin, end; - SPackedIterators(const T& _begin, const T& _end) - : begin(_begin) - , end(_end) {} - }; - - // SPackedBuffer: - // A buffer-pointer/length tuple. - // Note: Packing them into a single object allows us to pass them as a single argument like all other types. - template - struct SPackedBuffer - { - T buffer; - size_t size; - SPackedBuffer(T _buffer, size_t _size) - : buffer(_buffer) - , size(_size) {} - }; - - // SDependentType: - // Makes the name of type T dependent on X (which is otherwise meaningless). - // Note: This is used to force two-phase lookup so we don't need the definition of T until instantiation. - // This way we can convince standards-compliant compilers Clang and GCC to not require definition of forward-declared types. - // Specifically, we forward-declare Qt's QString and QChar, for which the definition will never be available outside Editor. - template - struct SDependentType - { - typedef T type; - }; - - // EBind: - // Methods of binding a type for input and/or output. - // Note: These are used for tag-dispatch by binding functions, and are private to the implementation. - enum EBind - { // Input Output Description - eBind_Impossible, // No No Can't bind this type. - eBind_Iterators, // Yes Yes Bind by using begin() and end() member functions. - eBind_Data, // Yes Yes Bind by using data() and size() member functions. - eBind_Literal, // Yes No Bind a fixed size buffer (const element, aka string literal). - eBind_Buffer, // Yes No Bind a fixed size buffer (non-const element) that may be null-terminated. - eBind_PackedBuffer, // No Yes Bind a user-specified size buffer (non-const element). - eBind_NullTerminated, // Yes No Bind a null-terminated buffer of unknown length (C string). - eBind_CodePoint, // Yes No Bind a single code-point value. - }; - - // SBindIterator: - // Find the EBind for input from iterator pair of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible - template - struct SBindIterator - { - typedef const void CharType; - static const EBind value = eBind_Impossible; - }; - template - struct SBindIterator - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindIterator::type, - typename SVoid::type - > - { - typedef typename add_const::type CharType; - typedef typename T::iterator_category IteratorCategory; - static const bool isInputIterator = is_base_of::value; - static const bool isValid = SValidChar::value; - static const EBind value = isValid && isInputIterator ? eBind_Iterators : eBind_Impossible; - }; - - // SBindObject: - // Find the EBind for input from object of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible. - template - struct SBindObject - { - typedef typename add_const< - typename conditional< - is_array::value, - typename remove_extent::type, - typename remove_pointer::type - >::type - >::type CharType; - static const size_t FixedSize = extent::value; - COMPILE_TIME_ASSERT(!is_array::value || FixedSize > 0); - static const bool isConstArray = is_array::value && is_const::type>::value; - static const bool isBufferArray = is_array::value && !isConstArray; - static const bool isPointer = is_pointer::value; - static const bool isCodePoint = is_integral::value; - static const bool isValidChar = SValidChar::value; - static const EBind value = - !isValidChar ? eBind_Impossible : - isConstArray ? eBind_Literal : - isBufferArray ? eBind_Buffer : - isPointer ? eBind_NullTerminated : - isCodePoint ? eBind_CodePoint : - eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename add_const::type CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject, InferEncoding> - { - typedef wchar_t CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindObject - { - typedef const QChar CharType; - static const EBind value = eBind_Data; - }; - template - struct SBindObject, InferEncoding> - { - typedef typename SBindIterator::CharType CharType; - static const EBind value = eBind_Iterators; - }; - - // SBindOutput: - // Find the EBind for output to object of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible. - template - struct SBindOutput - { - typedef typename remove_extent::type CharType; - static const size_t FixedSize = extent::value; - static const bool isArray = is_array::value; - static const bool isValid = SValidChar::type, InferEncoding, false>::value; - static const EBind value = isArray && isValid ? eBind_Buffer : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef OutputCharType CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_PackedBuffer : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef CharT CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template - struct SBindOutput, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template - struct SBindOutput - { - typedef QChar CharType; - static const EBind value = eBind_Data; - }; - - // SInferEncoding: - // Infers the encoding of the given character type. - // Note: This will always pick an UTF encoding type based on the size of the element type. - template - struct SInferEncoding - { - typedef SBindObject ObjectType; - typedef SBindIterator IteratorType; - typedef typename conditional< - IteratorType::value != eBind_Impossible, - typename IteratorType::CharType, - typename ObjectType::CharType - >::type CharType; - static const EEncoding value = - sizeof(CharType) == 1 ? eEncoding_UTF8 : - sizeof(CharType) == 2 ? eEncoding_UTF16 : - eEncoding_UTF32; - COMPILE_TIME_ASSERT(value != eEncoding_UTF32 || sizeof(CharType) == 4); - }; - - // SBindCharacter: - // Pick the base character type to use during input or output with this element type. - template::value, bool IsQChar = is_same::type>::value> - struct SBindCharacter - { - typedef typename make_unsigned::type BaseType; // The standard doesn't define if a character type is signed or unsigned. - typedef typename remove_cv::type UnqualifiedType; - typedef typename conditional::type type; - }; - template - struct SBindCharacter - { - COMPILE_TIME_ASSERT(is_arithmetic::value); - typedef typename remove_cv::type UnqualifiedType; - typedef typename conditional::type type; - }; - template - struct SBindCharacter - { - typedef typename conditional::type type; - typedef typename SDependentType::type ActuallyQChar; // Force two-phase name lookup on QChar. - COMPILE_TIME_ASSERT(sizeof(ActuallyQChar) == sizeof(type)); // In case Qt ever changes QChar. - }; - - // SBindPointer: - // Pick the pointer type to use during input or output with buffers (potentially inside string types). - template - struct SBindPointer - { - COMPILE_TIME_ASSERT(is_pointer::value || is_array::value); - typedef typename conditional< - is_pointer::value, - typename remove_pointer::type, - typename remove_extent::type - >::type UnboundCharType; - typedef typename SBindCharacter::type BoundCharType; - typedef BoundCharType* type; - }; - - // SAutomaticallyDeduced: - // Placeholder type that is never defined, used by SRequire for SFINAE overloading. - struct SAutomaticallyDeduced; - - // SRequire: - // Helper for SFINAE overloading. - // Similar to C++11's std::enable_if, which is not in boost (with that exact name anyway). - template - struct SRequire - { - typedef T type; - }; - template - struct SRequire {}; - - // SafeCast: - // Cast a pointer to type T, but only allowing safe casts. - // This guards against bad code in other functions since it prevents unintended casts. - template - inline T SafeCast(SourceChar* ptr, typename SRequire::value>::type* = 0) - { - // Allow casts from pointer-to-integral to unrelated pointer-to-integral, provided they are of the same size. - typedef typename remove_pointer::type TargetChar; - COMPILE_TIME_ASSERT(is_integral::value && is_integral::value); - COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar)); - return reinterpret_cast(ptr); - } - template - inline T SafeCast(SourceChar* ptr, typename SRequire::type, QChar>::value>::type* = 0) - { - // Allow casts from pointer-to-QChar to unrelated pointer-to-integral, provided they are of the same size. - typedef typename remove_pointer::type TargetChar; - COMPILE_TIME_ASSERT(is_integral::value); - COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar)); - return reinterpret_cast(ptr); - } - template - inline T SafeCast(SourceChar* ptr, typename SRequire::value&& !is_same::type, QChar>::value>::type* = 0) - { - // Any other casts that are allowed by C++. - return static_cast(ptr); - } - - // SCharacterTrait: - // Exposes some basic traits for a given character. - // Note: Map to (hopefully optimized) CRT functions where possible. - template::value> - struct SCharacterTrait - { - static size_t StrLen(const T* nts) // Fall-back strlen. - { - size_t result = 0; - while (*nts != 0) - { - ++nts; - ++result; - } - return result; - } - static size_t StrNLen(const T* ptr, size_t len) // Fall-back strnlen. - { - size_t result = 0; - while (*ptr != 0 && result != len) - { - ++ptr; - ++result; - } - return result; - } - }; - template - struct SCharacterTrait - { - static size_t StrLen(const T* nts) // Narrow CRT strlen. - { - return ::strlen(SafeCast(nts)); - } - static size_t StrNLen(const T* ptr, size_t len) // Narrow CRT strnlen. - { - return ::strnlen(SafeCast(ptr), len); - } - }; - template - struct SCharacterTrait - { - static size_t StrLen(const T* nts) // Wide CRT strlen. - { - return ::wcslen(SafeCast(nts)); - } - static size_t StrNLen(const T* ptr, size_t len) // Wide CRT strnlen. - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION UNICODEBINDING_H_SECTION_1 - #include AZ_RESTRICTED_FILE(UnicodeBinding_h) -#endif - return ::wcsnlen(SafeCast(ptr), len); -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION UNICODEBINDING_H_SECTION_2 - #include AZ_RESTRICTED_FILE(UnicodeBinding_h) -#endif - } - }; - - // void Feed(const SPackedIterators &its, Sink &out, tag): - // Feeds the provided sink from provided packed iterator-range. - template - inline void Feed(const SPackedIterators& its, Sink& out, integral_constant) - { - typedef typename std::iterator_traits::value_type UnboundCharType; - typedef typename SBindCharacter::type BoundCharType; - for (InputIteratorType it = its.begin; it != its.end; ++it) - { - const UnboundCharType unbound = *it; - const BoundCharType bound = static_cast(unbound); - const uint32 item = static_cast(bound); - out(item); - } - } - - // void Feed(const SPackedIterators &its, Sink &out, tag): - // Feeds the provided sink from provided packed pointer-range. - // This is slightly better code-generation than using generic iterators. - template - inline void Feed(const SPackedIterators& its, Sink& out, integral_constant) - { - typedef typename SBindPointer::type PointerType; - assert(reinterpret_cast(its.begin) <= reinterpret_cast(its.end) && "Invalid range specified"); - const size_t length = its.end - its.begin; - PointerType ptr = SafeCast(its.begin); - assert((ptr || !length) && "Passed a non-empty range containing a null-pointer"); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast(*ptr); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a container, using it's iterators. - // Note: Dispatches to one of the packed-range overloads. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant tag) - { - typedef typename InputStringType::const_iterator IteratorType; - Detail::SPackedIterators its(in.begin(), in.end()); - Feed(its, out, tag); - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a string-object's buffer. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant) - { - typedef typename InputStringType::size_type SizeType; - typedef typename InputStringType::value_type ValueType; - typedef typename SBindPointer::type PointerType; - const SizeType length = in.size(); - if (length) - { - PointerType ptr = SafeCast(in.data()); - for (SizeType i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast(*ptr); - out(item); - } - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a string-literal. - // Note: The literal is assumed to be null-terminated. - // It's possible that a const-element fixed-size-buffer is mistaken as a literal. - // However, we expect no-one uses such buffers that are not null-terminated already. - // If somehow this use-case is desired, either terminate the buffer, or remove const from the buffer, or pass iterators. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - typedef typename SBindPointer::type PointerType; - const size_t length = extent::value - 1; - PointerType ptr = SafeCast(in); - assert(ptr[length] == 0 && "Literal is not null-terminated"); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast(*ptr); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a non-const-element fixed-size buffer. - // Note: The buffer is allowed to be null-terminated, but it's not required. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - typedef typename SBindPointer::type PointerType; - typedef typename SBindPointer::BoundCharType CharType; - const size_t length = extent::value; - PointerType ptr = SafeCast(in); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const CharType unbound = *ptr; - if (unbound == 0) - { - break; - } - const uint32 item = static_cast(unbound); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a null-terminated C-style string. - template - inline void Feed(const InputStringType& in, Sink& out, integral_constant) - { - COMPILE_TIME_ASSERT(is_pointer::value); - typedef typename SBindPointer::type PointerType; - typedef typename SBindPointer::BoundCharType CharType; - PointerType ptr = SafeCast(in); - if (ptr) - { - while (true) - { - const CharType unbound = *ptr; - ++ptr; - if (unbound == 0) - { - break; - } - const uint32 item = static_cast(unbound); - out(item); - } - } - } - - // void Feed(const InputCharType &in, Sink &out, tag): - // Feeds the provided sink from a single value (interpreted as an UCS code-point). - template - inline void Feed(const InputCharType& in, Sink& out, integral_constant) - { - COMPILE_TIME_ASSERT(is_arithmetic::value); - const uint32 item = static_cast(in); - out(item); - } - - // size_t EncodedLength(const SPackedIterators &its, tag): - // Determines the length of the input sequence in a range of iterators. - template - inline size_t EncodedLength(const SPackedIterators& its, integral_constant) - { - return std::distance(its.begin, its.end); // std::distance will pick optimal implementation depending on iterator category. - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of an input container, which would otherwise be enumerated with iterators. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - return in.size(); // Can there be a container without size()? At the very least, not in the supported types. - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input container. The container uses contiguous element layout. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - return in.size(); - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input string-literal. This is a compile-time constant. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - return extent::value - 1; - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input fixed-size-buffer. We look for an (optional) null-terminator in the buffer. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - typedef typename remove_extent::type CharType; - return SCharacterTrait::StrNLen(in, extent::value); - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input used-specified buffer. We look for an (optional) null-terminator in the buffer. - template - inline size_t EncodedLength(const SPackedBuffer& in, integral_constant) - { - return in.buffer ? SCharacterTrait::StrNLen(in.buffer, in.size) : 0; - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input null-terminated c-style string. We just use strlen() if available. - template - inline size_t EncodedLength(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_pointer::value); - typedef typename remove_pointer::type CharType; - return in ? SCharacterTrait::StrLen(in) : 0; - } - - // size_t EncodedLength(const InputCharType &in, tag): - // Determines the length of a single UCS code-point. This is always 1. - template - inline size_t EncodedLength([[maybe_unused]] const InputCharType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_arithmetic::value); - return 1; - } - - // const void *EncodedPointer(const SPackedIterators &its, tag): - // Get a pointer to contiguous storage for an iterator range. - // Note: This can only work if the iterators are pointers, or the storage won't be guaranteed contiguous. - template - inline const void* EncodedPointer(const SPackedIterators& its, integral_constant) - { - return its.begin; - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for string/vector object. - // Note: This can only work for containers that actually use contiguous storage, which is determined by the SBindXXX helpers. - template - inline const void* EncodedPointer(const InputStringType& in, integral_constant) - { - return in.data(); - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a string-literal. - template - inline const void* EncodedPointer(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - return in; // We can just let the array type decay to a pointer. - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a fixed-size-buffer. - template - inline const void* EncodedPointer(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_array::value && extent::value > 0); - return in; // We can just let the array type decay to a pointer. - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a null-terminated c-style-string. - template - inline const void* EncodedPointer(const InputStringType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_pointer::value); - return in; // Implied - } - - // const void *EncodedPointer(const InputCharType &in, tag): - // Get a pointer to contiguous storage for a single UCS code-point. - template - inline const void* EncodedPointer(const InputCharType& in, integral_constant) - { - COMPILE_TIME_ASSERT(is_arithmetic::value); - return ∈ // Take the address of the parameter (which is kept on the stack of the caller). - } - - // SWriteSink: - // A helper that performs writing to the type T and can be passed as Sink type to a trans-coder helper. - template - struct SWriteSink; - template - struct SWriteSink - { - typedef typename T::value_type OutputCharType; - T& out; - SWriteSink(T& _out, size_t) - : out(_out) - { - if (!Append) - { - // If not appending, clear the object beforehand. - out.clear(); - } - } - void operator()(uint32 item) - { - const OutputCharType bound = static_cast(item); - out.push_back(bound); // We assume this can't fail and STL container takes care of memory. - } - void operator()(const void*, size_t); // Not implemented. - void HintSequence(uint32 length) {} // Don't care about sequences. - bool CanWrite() const { return true; } // Always writable - }; - template - struct SWriteSink - { - typedef SBindPointer BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - CharType* ptr; - SWriteSink(T& out, size_t length) - { - const size_t offset = Append ? out.size() : 0; - length += offset; - out.resize(length); // resize() can't fail without exceptions, so assert instead. - assert((out.size() == length) && "Buffer resize failed (out-of-memory?)"); - const CharType* base = length ? out.data() : 0; - ptr = const_cast(base + offset); - } - void operator()(uint32 item) - { - *SafeCast(ptr) = static_cast(item); - ++ptr; - } - void operator()(const void* src, size_t length) - { - ::memcpy(ptr, src, length * sizeof(CharType)); - ptr += length; - } - void HintSequence([[maybe_unused]] uint32 length) {} // Don't care about sequences. - bool CanWrite() const { return true; } // Always writable - }; - template - struct SWriteSink, Append, eBind_PackedBuffer> - { - typedef typename remove_pointer

::type ElementType; - typedef SBindPointer BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - CharType* ptr; - CharType* const terminator; - SWriteSink(CharType* _terminator) - : terminator(_terminator) {} - SWriteSink(SPackedBuffer

& out, size_t) - : terminator(out.size && out.buffer ? out.buffer + out.size - 1 : 0) - { - const size_t offset = Append - ? EncodedLength(out, integral_constant()) - : 0; - const size_t fixedOffset = Append && offset >= out.size - ? out.size - 1 // In case the buffer is already full and not terminated. - : offset; - CharType* base = static_cast(out.buffer); - ptr = terminator ? base + fixedOffset : 0; - } - ~SWriteSink() - { - if (ptr) - { - *ptr = 0; // Guarantees that the output is null-terminated. - } - } - void operator()(uint32 item) - { - if (ptr != terminator) // Guarantees we don't overflow the buffer. - { - *SafeCast(ptr) = static_cast(item); - ++ptr; - } - } - void operator()(const void* src, size_t length) - { - const size_t maxLength = terminator - ptr; - if (length > maxLength) - { - length = maxLength; - } - ::memcpy(ptr, src, length * sizeof(CharType)); - ptr += length; - } - void HintSequence(uint32 length) - { - if (terminator && (ptr + length >= terminator)) - { - // This sequence will overflow the buffer. - // In this case, we prefer to not generate any part of the sequence. - // Terminate at the current position and flag as full. - *ptr = 0; - ptr = terminator; - } - } - bool CanWrite() const - { - return terminator != ptr; - } - }; - template - struct SWriteSink // Uses above implementation with specialized constructor - : SWriteSink::type*>, Append, eBind_PackedBuffer> - { - typedef typename remove_extent::type ElementType; - typedef SWriteSink, Append, eBind_PackedBuffer> Super; - typedef SBindPointer BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - SWriteSink(T& out, size_t) - : Super(out + extent::value - 1) - { - const size_t offset = Append - ? EncodedLength(out, integral_constant()) - : 0; - const size_t fixedOffset = Append && offset >= extent::value - ? extent::value - 1 // In case the buffer is already full and not terminated. - : offset; - Super::ptr = out + fixedOffset; // Qualification for Super required for two-phase lookup. - } - }; - - // SIsBlockCopyable: - // Check if block-copy optimization is possible for these types. - // InputType should be an instantiation of SBindObject or SBindIterator. - // OutputType should be an instantiation of SBindOutput. - // Note: This doesn't take into account safe/unsafe conversions, just if the underlying storage types are compatible. - template - struct SIsBlockCopyable - { - template - struct SIsContiguous - { - static const bool value = - M == eBind_Data || - M == eBind_Literal || - M == eBind_Buffer || - M == eBind_PackedBuffer || - M == eBind_NullTerminated || - M == eBind_CodePoint; - }; - template - struct SIsPointers - { - static const bool value = false; - }; - template - struct SIsPointers > - { - static const bool value = true; - }; - typedef typename SBindCharacter::type InputCharType; - typedef typename SBindCharacter::type OutputCharType; - static const bool isIntegral = is_integral::value && is_integral::value; - static const bool isSameSize = sizeof(InputCharType) == sizeof(OutputCharType); - static const bool isInputContiguous = (SIsContiguous::value || SIsPointers::value); - static const bool isOutputContiguous = (SIsContiguous::value || SIsPointers::value); - static const bool value = isIntegral && isSameSize && isInputContiguous && isOutputContiguous; - }; - } -} diff --git a/Code/Legacy/CryCommon/UnicodeEncoding.h b/Code/Legacy/CryCommon/UnicodeEncoding.h deleted file mode 100644 index a3e20b639c..0000000000 --- a/Code/Legacy/CryCommon/UnicodeEncoding.h +++ /dev/null @@ -1,767 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Generic Unicode encoding helpers. -// -// Defines encoding and decoding functions used by the higher-level functions. -// These are used by the various conversion functions in UnicodeFunctions.h and UnicodeIterator.h. -// Note: You can use these functions manually for low-level functionality, but we don't recommend that. -// In that case, you probably want to check inside the nested Detail namespace for the elementary bits. - - -#pragma once -#include "BaseTypes.h" // For uint8, uint16, uint32 -#include "CompileTimeAssert.h" // For COMPILE_TIME_ASSERT macro -namespace Unicode -{ - // Supported encoding/conversion types. - enum EEncoding - { - // UTF-8 encoding, see http://www.unicode.org/resources/utf8.html. - // Input and output are supported. - // Note: This format maps the entire UCS, where each code-point can take [1, 4] 8-bit code-units. - // Note: This is a strict super-set of Latin1/ISO-885901 as well as ASCII. - eEncoding_UTF8, - - // UTF-16 encoding, see http://tools.ietf.org/html/rfc2781. - // Input and output are supported. - // Note: This format maps the entire UCS, where each code-point can take [1, 2] 16-bit code-units. - eEncoding_UTF16, - - // UTF-32 encoding, see http://www.unicode.org/reports/tr17/. - // Input and output are supported. - // Note: This format maps the entire UCS, each code-point is stored in a single 32-bit code-unit. - eEncoding_UTF32, - - // ASCII encoding, see http://en.wikipedia.org/wiki/ASCII. - // Input and output are supported (any output UCS values out of supported range are mapped to question mark). - // Note: Only values [U+0000, U+007F] can be mapped. - eEncoding_ASCII, - - // Latin1, aka ISO-8859-1 encoding, see http://en.wikipedia.org/wiki/ISO/IEC_8859-1. - // Only input is supported. - // Note: This is a strict super-set of ASCII, it additionally maps [U+00A0, U+00FF]. - eEncoding_Latin1, - - // Windows ANSI codepage 1252, see http://en.wikipedia.org/wiki/Windows-1252. - // Only input is supported. - // Note: This is a strict super-set of ASCII and Latin1/ISO-8859-1, it maps some code-units from [0x80, 0x9F]. - eEncoding_Win1252, - }; - - // Methods of recovery from invalid encoded sequences. - enum EErrorRecovery - { - // No attempt to detect invalid encoding is performed, the input is assumed to be valid. - // If the input is not valid, the output is undefined (in debug, this condition will cause an assert to trigger). - eErrorRecovery_None, - - // When an invalidly encoded sequence is detected, the sequence is discarded (will not be part of the output). - // Typically used for logic/hashing purposes when the input is almost certainly valid. - eErrorRecovery_Discard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the replacement-character (U+FFFD). - // Typically used when the output sequence is used for UI display purposes. - eErrorRecovery_Replace, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Latin1 equivalent. - // If the sequence is also not valid Latin1 encoded, the sequence is discarded. - // Typically used when reading generic text files with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackLatin1ThenDiscard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Win1252 equivalent. - // If the sequence is also not valid codepage 1252 encoded, the sequence is discarded. - // Typically used when reading text files generated on Windows with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackWin1252ThenDiscard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Latin1 equivalent. - // If the sequence is also not valid Latin1 encoded, it is replaced with the replacement-character (U+FFFD). - // Typically used when reading generic text files with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackLatin1ThenReplace, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Win1252 equivalent. - // If the sequence is also not valid codepage 1252 encoded, it is replaced with the replacement-character (U+FFFD). - // Typically used when reading text files generated on Windows with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackWin1252ThenReplace, - }; - - namespace Detail - { - // Decode(state, unit): Decodes a single code-unit of an encoding into an UCS code-point. - // When Safe flag is set, encoding errors are detected so a fall-back encoding or other recovery method can be used. - // Interpret return value as follows: - // < 0x001FFFFF: Decoded codepoint (== return value), call again with next code-unit and clear state. - // < 0x80000000: Intermediate state returned, call again with next code-unit and the returned state. - // >= 0x80000000: Bad encoding detected, up to 16 bits (UTF-16) or 24 bits (UTF-8, last in lower bits) - // contain previous consumed values (does not happen if Safe == false). - template - inline uint32 Decode(uint32 state, uint32 unit); - - // Some constant values used when encoding/decoding. - enum - { - cDecodeShiftRemaining = 26, // Where to store the remaining count in the state. - cDecodeOneRemaining = 1 << cDecodeShiftRemaining, // Remaining value of one. - cDecodeMaskRemaining = 3 << cDecodeShiftRemaining, // All possible remaining bits that can be used. - cDecodeLeadBit = 1 << 22, // All bits up to and including this one are reserved. - cDecodeErrorBit = 1 << 31, // Set if an error occurs during decoding. - cDecodeOverlongBit = 1 << 30, // Set if overlong sequence was used. - cDecodeSurrogateBit = 1 << 29, // Set if surrogate code-point decoded in UTF-8. - cDecodeInvalidBit = 1 << 28, // Set if invalid code-point decoded (U+FFFE/FFFF). - cDecodeSuccess = 0, // Placeholder to indicate no error occurred. - cCodepointMax = 0x10FFFF, // The maximum value of an UCS code-point. - cLeadSurrogateFirst = 0xD800, // The first valid UTF-16 lead-surrogate value. - cLeadSurrogateLast = 0xDBFF, // The last valid UTF-16 lead-surrogate value. - cTrailSurrogateFirst = 0xDC00, // The first valid UTF-16 trail-surrogate value. - cTrailSurrogateLast = 0xDFFF, // The last valid UTF-16 trail-surrogate value. - cReplacementCharacter = 0xFFFD, // The default replacement character. - }; - - // Validate the UTF-8 state of a multi-byte sequence. - // The safe decoder of UTF-8 will call this function when a full potential code-point has been decoded. - // This function is (at most) called for 50% of the decoded UTF-8 code-units, but likely at much lower frequency. - inline uint32 DecodeValidate8(uint32 state) - { - uint32 errorbits = (state >> 8) | cDecodeErrorBit; - state ^= (state & 0x400000) >> 1; // For 3-byte sequences, bit 5 of the lead byte needs to be cleared. - const uint32 cp = - (state & 0x3F) | - ((state & 0x3F00) >> 2) | - ((state & 0x3F0000) >> 4) | - ((state & 0x07000000) >> 6); - if (cp <= cCodepointMax) - { - if (cp >= cLeadSurrogateFirst && cp <= cTrailSurrogateLast) - { - errorbits += cDecodeSurrogateBit; // CESU-8 encoding might have been used. - } - else - { - uint32 minval = 0x80; - minval += (0x00400000 & state) ? 0x800 - 0x80 : 0; - minval += (0x40000000 & state) ? 0x10000 - 0x80 : 0; - if (cp >= minval) - { - if ((cp & 0xFFFFFFFEU) != 0xFFFEU) - { - return cp; // Valid code-point. - } - errorbits += cDecodeInvalidBit; // Invalid character used. - } - errorbits += cDecodeOverlongBit; // Overlong encoding used. - } - } - return errorbits; - } - - // Decode UTF-8, unsafe. - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - if (state == 0) // First byte. - { - unit = unit & 0xFF; - if (unit < 0xC0) - { - return unit; // Single-unit (ASCII). - } - uint32 remaining = (unit >> 4) - 0xC; - remaining += (remaining == 0); - return (unit & 0x1F) + (remaining << cDecodeShiftRemaining); // Lead byte of multi-byte. - } - state = (state << 6) + (unit & 0x3F) + (state & cDecodeMaskRemaining) - cDecodeOneRemaining; // Apply c-byte. - return state & ~cDecodeLeadBit; // Mask off the lead bits of a 4-byte sequence. - } - - // Decode UTF-8, safe - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - if (unit <= 0xF4) // Discard out-of-range values immediately. - { - if (state == 0) // First byte. - { - if (unit < 0x80) - { - return unit; // Single-byte. - } - if (unit < 0xC2) - { - return cDecodeErrorBit; // Invalid continuation byte (or illegal 0xC0/0xC1). - } - uint32 remaining = (unit >> 4) - 0xC; - remaining += (remaining == 0); - return unit + (remaining << cDecodeShiftRemaining); // Multi-byte. - } - if ((unit & 0xC0) == 0x80) - { - const uint32 remaining = (state & cDecodeMaskRemaining) - cDecodeOneRemaining; - state = (state << 8) + unit; - if (remaining != 0) - { - return state | remaining; // Intermediate byte of a multi-byte sequence. - } - return DecodeValidate8(state); // Final byte of a multi-byte sequence. - } - } - return cDecodeErrorBit | state; - } - - // Decode UTF-16, unsafe. - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - const bool bLead = (unit >= cLeadSurrogateFirst) && (unit <= cLeadSurrogateLast); - const uint32 initial = unit + (bLead << cDecodeShiftRemaining); - const uint32 pair = 0x10000 + ((state & 0x3FF) << 10) + (unit & 0x3FF); - return state == 0 ? initial : pair; - } - - // Decode UTF-16, safe. - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - const bool bTrail = (unit >= cTrailSurrogateFirst) && (unit <= cTrailSurrogateLast); - if (state != 0 && !bTrail) - { - return cDecodeErrorBit + (state & 0xFFFF); // Lead surrogate without trail surrogate - } - uint32 result = Decode(state, unit); - bool bValid = (result & 0xFFFFFFFEU) != 0xFFFEU; - return bValid ? result : result + cDecodeErrorBit + cDecodeInvalidBit; - } - - // Decode UTF-32, unsafe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode UTF-32, safe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - if (unit > cCodepointMax) - { - return cDecodeErrorBit; - } - if (unit >= cLeadSurrogateFirst && unit <= cTrailSurrogateLast) - { - return cDecodeErrorBit | cDecodeSurrogateBit; - } - if ((unit & 0xFFFEU) == 0xFFFEU) - { - return cDecodeErrorBit | cDecodeInvalidBit; - } - return unit; - } - - // Decode ASCII, unsafe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode ASCII, safe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - if (unit > 0x7F) - { - return cDecodeErrorBit; - } - return unit; - } - - // Decode Latin1, unsafe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode Latin1, safe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - if ((unit >= 0x80 && unit <= 0x9F) || (unit > 0xFF)) - { - return cDecodeErrorBit; - } - return unit; - } - - // Decode Windows CP-1252, unsafe. - template<> - inline uint32 Decode([[maybe_unused]] uint32 state, uint32 unit) - { - static const uint16 cp1252[] = - { - 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, - 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, - 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, - 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, - }; - return (unit < 0x80 || unit > 0x9F) ? unit : cp1252[unit - 0x80]; - } - - // Decode Windows CP-1252, safe. - template<> - inline uint32 Decode(uint32 state, uint32 unit) - { - if (unit > 0xFF) - { - return cDecodeErrorBit; - } - uint32 result = Decode(state, unit); - if (!(unit < 0x80 || unit > 0x9F) && (result == unit)) - { - return cDecodeErrorBit; // Not defined in codepage 1252. - } - return result; - } - - // SBase: - // Utility to apply empty-base-optimization on type T. - // Will fall back to a member if T is a reference type. - template - struct SBase - : T - { - SBase(T base) - : T(base) {} - T& GetBase() { return *this; } - const T& GetBase() const { return *this; } - }; - template - struct SBase - { - T& base; - SBase(T& b) - : base(b) {} - T& GetBase() { return base; } - const T& GetBase() const { return base; } - }; - - // SDecoder: - // Functor to decode UCS code-points from an input range. - // Recovery functor will be invoked as a fall-back if decoding fails. - // This allows ensuring all the output is valid (even if the input isn't). - // Note: The destructor will automatically flush any remaining (erroneous) state, you can also call Finalize(). - template - struct SDecoder - : SBase - , SBase - { - uint32 state; - SDecoder(Sink sink, Recovery recovery = Recovery()) - : SBase(sink) - , SBase(recovery) - , state(0) {} - SDecoder() { Finalize(); } - Recovery& recovery() { return SBase::GetBase(); } - Sink& sink() { return SBase::GetBase(); } - void operator()(uint32 unit) - { - state = Detail::Decode(state, unit); - if (state <= 0x1FFFFF) - { - sink()(state); - state = 0; - } - else if (state & Detail::cDecodeErrorBit) - { - recovery()(sink(), state, unit); - state = 0; - } - } - void Finalize() - { - if (state) - { - recovery()(sink(), state, 0); - state = 0; - } - } - }; - - // SDecoder: - // Functor to decode to UCS code-points from an input range. - // No attempt to discover or recover from encoding errors is made, can only safely be used with known-valid input. - template - struct SDecoder - : SBase - { - uint32 state; - SDecoder(Sink sink) - : SBase(sink) - , state(0) {} - Sink& sink() { return SBase::GetBase(); } - void operator()(uint32 unit) - { - state = Detail::Decode(state, unit); - if (state <= 0x1FFFFF) - { - sink()(state); - state = 0; - } - } - void Finalize() {} - }; - - // SEncoder: - // Generic Unicode encoder functor. - // Encoding must be one an encoding type for which output is supported. - // The Sink type must have HintSequence member for UTF-8 and UTF-16 (although it may be a no-op). - // In general, you feed operator() with UCS code-points and it will emit code-units. - template - struct SEncoder - { - static const bool value = false; - }; - - // SEncoder: - // Specialization of ASCII encoder functor. - // Note: Any out-of-range character is mapped to question mark. - template - struct SEncoder - : SBase - { - static const bool value = true; - typedef uint8 value_type; - SEncoder(Sink sink) - : SBase(sink) {} - void operator()(uint32 cp) - { - cp = cp < 0x80 ? cp : (uint32)'?'; - SBase::GetBase()(value_type(cp)); - } - }; - - // SEncoder: - // Specialization of UTF-8 encoder functor. - template - struct SEncoder - : SBase - { - static const bool value = true; - typedef uint8 value_type; - SEncoder(Sink sink) - : SBase(sink) {} - Sink& sink() { return SBase::GetBase(); } - void operator()(uint32 cp) - { - if (cp < 0x80) - { - // Single byte sequence. - sink()(value_type(cp)); - } - else - { - // Expand 21-bit value to 32-bit. - uint32 bits = - (cp & 0x00003F) + - ((cp & 0x000FC0) << 2) + - ((cp & 0x03F000) << 4) + - ((cp & 0x1C0000) << 6); - - // Type of sequence. - const bool bSeq4 = (cp >= 0x10000); - const bool bSeq3 = (cp >= 0x800); - - // Mask lead-bytes and continuation-bytes. - uint32 mask = 0xEFE0C080; - mask ^= (bSeq3 << 14); - mask += (bSeq4 ? 0xA00000 : 0); - bits |= mask; - - // Length of the sequence. - const uint32 length = (uint32)bSeq4 + (uint32)bSeq3 + 1; - sink().HintSequence(length); - - // Sink the multi-byte sequence. - if (bSeq4) - { - sink()(value_type(bits >> 24)); - } - if (bSeq3) - { - sink()(value_type(bits >> 16)); - } - sink()(value_type(bits >> 8)); - sink()(value_type(bits)); - } - } - }; - - // SEncoder: - // Specialization of UTF-16 encoder functor. - template - struct SEncoder - : SBase - { - static const bool value = true; - typedef uint16 value_type; - SEncoder(Sink sink) - : SBase(sink) {} - Sink& sink() { return SBase::GetBase(); } - void operator()(uint32 cp) - { - if (cp < 0x10000) - { - // Single unit - sink()(value_type(cp)); - } - else - { - // We will generate two-element sequence - sink().HintSequence(2); - - // Surrogate pair - cp -= 0x10000; - uint32 lead = ((cp >> 10) & 0x3FF) + Detail::cLeadSurrogateFirst; - uint32 trail = (cp & 0x3FF) + Detail::cTrailSurrogateFirst; - sink()(value_type(lead)); - sink()(value_type(trail)); - } - } - }; - - // SEncoder: - // Specialization of UTF-32 encoder functor. - // Note: This is a no-op, but we want to be able to express UTF-32 just like the other encodings. - template - struct SEncoder - : SBase - { - static const bool value = true; - typedef uint32 value_type; - SEncoder(Sink sink) - : SBase(sink) {} - void operator()(uint32 cp) - { - SBase::GetBase()(value_type(cp)); - } - }; - - // SDecoder, void>: - // Specialization for unsafe no-op trans-coding. - // Since the conversion is a no-op, no need to keep any state or do any computation. - // Note: For a decoding with a fallback, this is not possible since we can't guarantee the input is valid. - template - struct SDecoder, void> - { - Sink sink; - SDecoder(Sink s) - : sink(s) {} - void operator()(uint32 unit) - { - sink(unit); - } - void Finalize() {} - }; - - // SRecoveryDiscard: - // Recovery handler that, on encoding error, discards the offending sequence. - template - struct SRecoveryDiscard - { - SRecoveryDiscard() {} - void operator()([[maybe_unused]] Sink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) {} - }; - - // SRecoveryReplace: - // Recovery handler that, on encoding error, replaces the sequence with replacement-character (U+FFFD). - // Note: This implementation matches a whole invalid sequence, it could be changed to emit for every code-unit. - template - struct SRecoveryReplace - { - SRecoveryReplace() {} - void operator()(Sink& sink, uint32 error, uint32 unit) { sink(cReplacementCharacter); } - }; - - // SRecoveryFallback: - // Recovery handler that, on encoding error, falls back to another encoding. - // The fallback encoding must be stateless (ie: ASCII, Latin1 or Win1252). - // This type assumes an 8-bit primary encoding since the only viable fallback encodings are 8-bit. - template - struct SRecoveryFallback - : NextFallback - { - SRecoveryFallback() - : NextFallback() {} - void operator()(Sink& sink, uint32 error, uint32 unit) - { - SDecoder fallback(sink, *static_cast(this)); - uint8 byte1(error >> 16); - uint8 byte2(error >> 8); - uint8 byte3(error); - uint8 byte4(unit); - if (byte1) - { - fallback(byte1); - } - if (byte1 | byte2) - { - fallback(byte2); - } - if (byte1 | byte2 | byte3) - { - fallback(byte3); - } - fallback(byte4); - } - }; - - // SRecoveryFallbackHelper: - // Helper to pick a SRecoveryFallback instantiation based on RecoveryMethod. - template - struct SRecoveryFallbackHelper - { - // A compilation error here means RecoveryMethod value was unexpected here - COMPILE_TIME_ASSERT( - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenReplace || - RecoveryMethod == eErrorRecovery_FallbackWin1252ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackWin1252ThenReplace); - typedef SEncoder SinkType; - static const EEncoding FallbackEncoding = - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenReplace - ? eEncoding_Latin1 : eEncoding_Win1252; - template - struct Pick - { - typedef SRecoveryDiscard type; - }; - template - struct Pick - { - typedef SRecoveryReplace type; - }; - typedef typename Pick::type NextFallback; - typedef SRecoveryFallback RecoveryType; - typedef SDecoder FullType; - }; - - // STranscoderSelect: - // Derives a chained decoder/encoder pair that performs code-unit -> code-unit transform. - // The RecoveryMethod template parameter determines the behavior during encoding. - // This is the basic way to perform trans-coding, and is the type instantiated by the higher-level functions. - template - struct STranscoderSelect; - template - struct STranscoderSelect - : SDecoder, void> - { - typedef SDecoder, void> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SDecoder, SRecoveryDiscard > > - { - typedef SRecoveryDiscard > RecoveryType; - typedef SDecoder, RecoveryType> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SDecoder, SRecoveryReplace > > - { - typedef SRecoveryReplace > RecoveryType; - typedef SDecoder, RecoveryType> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SRecoveryFallbackHelper::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackLatin1ThenDiscard; - typedef typename SRecoveryFallbackHelper::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SRecoveryFallbackHelper::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackLatin1ThenReplace; - typedef typename SRecoveryFallbackHelper::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SRecoveryFallbackHelper::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackWin1252ThenDiscard; - typedef typename SRecoveryFallbackHelper::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template - struct STranscoderSelect - : SRecoveryFallbackHelper::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackWin1252ThenReplace; - typedef typename SRecoveryFallbackHelper::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - - // SIsSafeEncoding: - // Check if the given recovery mode is safe. - // This is used for SFINAE checks in higher-level functions. - template - struct SIsSafeEncoding - { - static const bool value = - R == eErrorRecovery_Discard || - R == eErrorRecovery_Replace || - R == eErrorRecovery_FallbackLatin1ThenDiscard || - R == eErrorRecovery_FallbackLatin1ThenReplace || - R == eErrorRecovery_FallbackWin1252ThenDiscard || - R == eErrorRecovery_FallbackWin1252ThenReplace; - }; - - // SIsCopyableEncoding: - // Check if data in one encoding can be copied directly to another encoding. - // This is the basis for block-copy and string-assign optimizations in un-safe conversion functions. - // Note: There are more valid combinations, they are left out since those can't occur with the output encodings supported. - // Note: Only used for un-safe functions since it doesn't account for potential invalid sequences (they would be copied over). - template - struct SIsCopyableEncoding - { - static const bool value = - InputEncoding == eEncoding_ASCII || // ASCII and Latin1 values don't change in any encoding. - (InputEncoding == eEncoding_Latin1 && OutputEncoding != eEncoding_ASCII); // Except Latin1 -> ASCII is lossy. - }; - template - struct SIsCopyableEncoding - { - static const bool value = true; // If the input and output encodings are the same, then it's copyable. - }; - } -} diff --git a/Code/Legacy/CryCommon/UnicodeFunctions.h b/Code/Legacy/CryCommon/UnicodeFunctions.h deleted file mode 100644 index 48debe9706..0000000000 --- a/Code/Legacy/CryCommon/UnicodeFunctions.h +++ /dev/null @@ -1,1265 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Generic Unicode string functions. -// -// Implements the following functions: -// Analyze: Reports all information on the input string, (length for all encodings, validity- and non-ASCII flags). -// Validate: Checks if the input string is valid encoded. -// Length: Reports the encoded length of some known-valid input, as-if it was encoded in the given output encoding. -// LengthSafe: Reports the encoded length of some input, as-if it was encoded in the given output encoding/recovery. -// Convert: Converts input from a known-valid string type/encoding to another string type/encoding. -// ConvertSafe: Converts and recovers encoding errors from one string type/encoding to another string type/encoding. -// Append: Appends input from a known-valid string type/encoding to another string type/encoding. -// AppendSafe: Appends and recovers encoding errors from one string type/encoding to another string type/encoding. -// -// Note: Ideally the safe functions should be used only once when accepting input from the user or from a file. -// Afterwards, the content is known-safe and the unsafe functions can be used for optimal performance. -// Using ConvertSafe once with a reasonable fall-back (depending on the where the input is from) should be the goal. -// -// Each function has several overloads: -// - One variant to handle a string object / buffer / pointer (1 arg), and one to handle iterators (2 args). -// - One variant with automatic encoding (picks UTF encoding depending on character size), and one for specific encoding. -// - One variant that returns a new string, and one that takes an existing string to overwrite (Convert(Safe) only). -// Each function takes one default argument that employs SFINAE to pick the correct overload depending on the arguments. - - -#pragma once -#include "UnicodeBinding.h" -namespace Unicode -{ - // Results of analysis of an input range of code-units (in any encoding). - // This is returned by calling Analyze() function. - struct SAnalysisResult - { - // The type to use for counting units. - // Can be changed to uint64_t for dealing with 4GB+ of string data. - typedef uint32 size_type; - - size_type inputUnits; // The number of input units analyzed. - size_type outputUnits8; // The number of output units when encoded with UTF-8. - size_type outputUnits16; // The number of output units when encoded with UTF-16. - size_type outputUnits32; // The number of output units when encoded with UTF-32 (aka number of UCS code-points). - size_type cpNonAscii; // The number of non-ASCII UCS code-points encountered. - size_type cpInvalid; // The number of invalid UCS code-point encountered (or 0xFFFFFFFF if not available). - - // Default constructor, initialize everything to zero. - SAnalysisResult() - : inputUnits(0) - , outputUnits8(0) - , outputUnits16(0) - , outputUnits32(0) - , cpInvalid(0) - , cpNonAscii(0) {} - - // Check if the input range was empty. - bool IsEmpty() const { return inputUnits == 0; } - - // Check if the input range only contained ASCII characters. - bool IsAscii() const { return cpNonAscii == 0; } - - // Check if the input range was valid (has no encoding errors). - // Note: This returns false if an unsafe decoder was used for analysis. - bool IsValid() const { return cpInvalid == 0; } - - // Get the length of the input range, in source code-units. - size_type LengthInSourceUnits() const { return inputUnits; } - - // Get the length of the input range, in UCS code-points. - size_type LengthInUCS() const { return outputUnits32; } - - // Get the length of the input range when encoded with the given encoding, in code-units. - // Note: If the encoding is not supported for output, the function returns 0. - size_type LengthInEncodingUnits(EEncoding encoding) const - { - switch (encoding) - { - case eEncoding_ASCII: - case eEncoding_UTF32: - return outputUnits32; - case eEncoding_UTF16: - return outputUnits16; - case eEncoding_UTF8: - return outputUnits8; - default: - return 0; - } - } - - // Get the length of the input range when encoded with the given encoding, in bytes. - // Note: If the encoding is not supported for output, the function returns 0. - size_type LengthInEncodingBytes(EEncoding encoding) const - { - size_type units = LengthInEncodingUnits(encoding); - switch (encoding) - { - case eEncoding_UTF32: - return units << 2; - case eEncoding_UTF16: - return units << 1; - default: - return units; - } - } - }; - - namespace Detail - { - // SDummySink: - // A sink implementation that does nothing. - struct SDummySink - { - void operator()([[maybe_unused]] uint32 unit) {} - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SCountingSink: - // A sink that counts the number of units of output. - struct SCountingSink - { - size_t result; - - SCountingSink() - : result(0) {} - void operator()([[maybe_unused]] uint32 unit) { ++result; } - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SAnalysisSink: - // A sink that updates analysis statistics. - struct SAnalysisSink - { - SAnalysisResult& result; - - SAnalysisSink(SAnalysisResult& _result) - : result(_result) {} - void operator()(uint32 cp) - { - const bool isCat2 = cp >= 0x80; - const bool isCat3 = cp >= 0x800; - const bool isCat4 = cp >= 0x10000; - result.outputUnits32 += 1; - result.outputUnits16 += (1 + isCat4); - result.outputUnits8 += (1 + isCat4 + isCat3 + isCat2); - result.cpNonAscii += isCat2; - } - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SAnalysisRecovery: - // A recovery helper for analysis that counts invalid sequences. - struct SAnalysisRecovery - { - SAnalysisRecovery() {} - void operator()(SAnalysisSink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) - { - sink.result.cpInvalid += 1; - } - }; - - // SValidationRecovery: - // A recovery helper for validation, it tracks if there is any invalid sequence. - struct SValidationRecovery - { - bool isValid; - - SValidationRecovery() - : isValid(true) {} - void operator()([[maybe_unused]] SDummySink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) - { - isValid = false; - } - }; - - // SAnalyzer: - // Helper to perform analysis, counts the input for a given encoding. - template - struct SAnalyzer - { - SDecoder decoder; - - SAnalyzer(SAnalysisResult& result) - : decoder(result) {} - void operator()(uint32 item) - { - decoder.sink().result.inputUnits += 1; - decoder(item); - } - }; - - // Analyze(target, source): - // Analyze string and store analysis result. - // This is the generic function called by other Analyze overloads. - template - inline void Analyze(SAnalysisResult& target, const InputStringType& source) - { - // Bind methods. - const EBind bindMethod = SBindObject::value; - integral_constant tag; - - // Analyze using helper. - SAnalyzer analyzer(target); - Feed(source, analyzer, tag); - } - - // Validate(source): - // Tests that the string is valid encoding. - // This is the generic function called by other Validate overloads. - template - inline bool Validate(const InputStringType& source) - { - // Bind methods. - const EBind bindMethod = SBindObject::value; - integral_constant tag; - - // Validate using helper. - SDummySink sink; - SDecoder validator(sink); - Feed(source, validator, tag); - return validator.recovery().isValid; - } - - // Length(str): - // Find length of a string (in code-units) after trans-coding from InputEncoding to OutputEncoding. - // This is the generic function called by the other Length overloads. - template - inline size_t Length(const InputStringType& source) - { - // If this assert hits, consider using LengthSafe. - assert((Detail::Validate(source)) && "Length was used with non-safe input"); - - // Bind methods. - const EBind bindMethod = SBindObject::value; - integral_constant tag; - - // All copyable encodings have the property that the number of input encoding units equals the output units. - // In addition, this also holds for UTF-32 (always 1) -> ASCII (always 1), even though it's lossy. - const bool isCopyable = SIsCopyableEncoding::value; - const bool isCountable = isCopyable || (InputEncoding == eEncoding_UTF32 && OutputEncoding == eEncoding_ASCII); - - if (isCountable) - { - // Optimization: The number of input units is equal to the number of output units. - return EncodedLength(source, tag); - } - else - { - // We need to perform the conversion. - SCountingSink sink; - STranscoderSelect transcoder(sink); - Feed(source, transcoder, tag); - return sink.result; - } - } - - // LengthSafe(str): - // Find length of a string (in code-units) after trans-coding from InputEncoding to OutputEncoding. - // Note: The Recovery type used during conversion may influence the result, so this needs to match if you use the length information. - // This is the generic function called by the other LengthSafe overloads. - template - inline size_t LengthSafe(const InputStringType& source) - { - // SRequire a safe recovery method. - COMPILE_TIME_ASSERT(SIsSafeEncoding::value); - - // Bind methods. - const EBind bindMethod = SBindObject::value; - integral_constant tag; - - // We can't optimize here, since we cannot assume the input is validly encoded - SCountingSink sink; - STranscoderSelect transcoder(sink); - Feed(source, transcoder, tag); - return sink.result; - } - - // SBlockCopy: - // Helper for block-copying entire string at once (as an optimization) - // This optimization will effectively try to memcpy or assign the whole string at once. - // Note: We need to do some partial specialization here to find out if the optimization is valid, so we can't use a function in C++98. - template - struct SBlockCopy - { - static const EBind bindMethod = SBindObject::value; - typedef integral_constant TagType; - size_t operator()(OutputStringType& target, const InputStringType& source) - { - // Optimization: Use block copying for these types. - TagType tag; - const size_t length = EncodedLength(source, tag); - SinkType sink(target, length); - if (sink.CanWrite()) - { - const void* const dataPtr = EncodedPointer(source, tag); - sink(dataPtr, length); - } - return length; - } - }; - - // SBlockCopy: - // Specialization that will use direct string assignment. - // Note: This optimization is not selected when appending, this could be a future optimization if this is common. - // Reason for this is that the += operator is not present on all supported types (ie, std::vector) - template - struct SBlockCopy - { - size_t operator()(SameStringType& target, const SameStringType& source) - { - // Optimization: Use copy assignment. - target = source; - return source.size(); - } - }; - - // SBlockCopy: - // Fall-back specialization for Enable == false. - // Note: This specialization has to exist for the linker, but should never be called (and optimized away). - template - struct SBlockCopy - { - size_t operator()([[maybe_unused]] OutputStringType& target, [[maybe_unused]] const InputStringType& source) - { - assert(false && "Should never be called"); - return 0; - } - }; - - // Convert(target, source): - // Trans-code a string from InputEncoding to OutputEncoding. - // This is the generic function that is called by Convert and Append overloads. - // Returns the number of code-units required for full output (excluding any terminators) - template - inline size_t Convert(OutputStringType& target, const InputStringType& source) - { - // If this assert hits, consider using ConvertSafe. - assert((Detail::Validate(source)) && "Convert was used with non-safe input"); - - // Bind methods. - const EBind inputBindMethod = SBindObject::value; - const EBind outputBindMethod = SBindOutput::value; - integral_constant tag; - typedef SWriteSink SinkType; - - // Check if we can optimize this. - const bool isCopyable = SIsCopyableEncoding::value; - const bool isBlocks = SIsBlockCopyable, SBindOutput >::value; - const bool useBlockCopy = isCopyable && isBlocks; - size_t length; - if (useBlockCopy) - { - // Use optimized path. - SBlockCopy blockCopy; - length = blockCopy(target, source); - } - else - { - // We need to perform the conversion code-unit by code-unit. - length = Detail::Length(source); - SinkType sink(target, length); - if (sink.CanWrite()) - { - STranscoderSelect transcoder(sink); - Feed(source, transcoder, tag); - } - } - return length; - } - - // ConvertSafe(target, source): - // Safely trans-code a string from InputEncoding to OutputEncoding using the specified Recovery to handle encoding errors. - // This is the generic function called by ConvertSafe and AppendSafe overloads. - template - inline size_t ConvertSafe(OutputStringType& target, const InputStringType& source) - { - // SRequire a safe recovery method. - COMPILE_TIME_ASSERT(SIsSafeEncoding::value); - - // Bind methods. - const EBind inputBindMethod = SBindObject::value; - const EBind outputBindMethod = SBindOutput::value; - integral_constant tag; - typedef SWriteSink SinkType; - - // We can't optimize with block-copy here, since we cannot assume the input is validly encoded. - const size_t length = Detail::LengthSafe(source); - SinkType sink(target, length); - if (sink.CanWrite()) - { - STranscoderSelect transcoder(sink); - Feed(source, transcoder, tag); - } - return length; - } - - // SReqAutoObj: - // Require that T is usable as input object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAutoObj - : SRequire< - SBindObject::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAutoIts: - // Require that T is usable as input iterator, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAutoIts - : SRequire< - SBindIterator::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAnyObj: - // Require that T is usable as input object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAnyObj - : SRequire< - SBindObject::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAnyIts: - // Require that T is usable as input iterator, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAnyIts - : SRequire< - SBindIterator::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAutoObjOut: - // Require that I is usable as input object, and O as output object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAutoObjOut - : SRequire< - SBindObject::value != eBind_Impossible&& - SBindOutput, O>::type, true>::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAutoItsOut: - // Require that I is usable as input iterator, and O as output object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAutoItsOut - : SRequire< - SBindIterator::value != eBind_Impossible&& - SBindOutput, O>::type, true>::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAnyObjOut: - // Require that I is usable as input object, and O as output object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAnyObjOut - : SRequire< - SBindObject::value != eBind_Impossible&& - SBindOutput, O>::type, false>::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - - // SReqAnyItsOut: - // Require that I is usable as input object, and O as output object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template - struct SReqAnyItsOut - : SRequire< - SBindIterator::value != eBind_Impossible&& - SBindOutput, O>::type, false>::value != eBind_Impossible&& - SEncoder::value&& - SIsSafeEncoding::value - > {}; - } - - // SAnalysisResult Analyze(str): - // Analyze the given string with the given encoding, providing information on validity and encoding length. - template - inline SAnalysisResult Analyze(const InputStringType& str, - typename Detail::SReqAnyObj::type* = 0) - { - SAnalysisResult result; - Detail::Analyze(result, str); - return result; - } - - // SAnalysisResult Analyze(str): - // Analyze the (assumed) Unicode string input, providing information on validity and encoding length. - // The Unicode encoding is picked automatically depending on the input type. - template - inline SAnalysisResult Analyze(const InputStringType& str, - typename Detail::SReqAutoObj::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - SAnalysisResult result; - Detail::Analyze(result, str); - return result; - } - - // SAnalysisResult Analyze(begin, end): - // Analyze the given range with the given encoding, providing information on validity and encoding length. - template - inline SAnalysisResult Analyze(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - SAnalysisResult result; - Detail::Analyze(result, its); - return result; - } - - // SAnalysisResult Analyze(begin, end): - // Analyze the given (assumed) Unicode range, providing information on validity and encoding length. - // The Unicode encoding is picked automatically depending on the input type. - template - inline SAnalysisResult Analyze(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - SAnalysisResult result; - Detail::Analyze(result, its); - return result; - } - - // bool Validate(str): - // Checks if the given string is valid in the given encoding. - template - inline bool Validate(const InputStringType& str, - typename Detail::SReqAnyObj::type* = 0) - { - return Detail::Validate(str); - } - - // bool Validate(str): - // Checks if the given string is a valid Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - template - inline bool Validate(const InputStringType& str, - typename Detail::SReqAutoObj::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - return Detail::Validate(str); - } - - // bool Validate(begin, end): - // Checks if the given range is valid in the given encoding. - template - inline bool Validate(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::Validate(its); - } - - // bool Validate(begin, end): - // Checks if the given range is valid Unicode. - // The Unicode encoding is picked automatically depending on the input type. - template - inline bool Validate(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::Validate(its); - } - - // size_t Length(str): - // Get the length (in OutputEncoding) of the given known-valid string with the given InputEncoding. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template - inline size_t Length(const InputStringType& str, - typename Detail::SReqAnyObj::type* = 0) - { - return Detail::Length(str); - } - - // size_t Length(str): - // Get the length (in OutputEncoding) of the given known-valid Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template - inline size_t Length(const InputStringType& str, - typename Detail::SReqAutoObj::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - return Detail::Length(str); - } - - // size_t Length(begin, end): - // Get the length (in OutputEncoding) of the known-valid range with the given InputEncoding. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template - inline size_t Length(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::Length(its); - } - - // size_t Length(begin, end): - // Get the length (in OutputEncoding) of the known-valid Unicode range. - // The Unicode encoding is picked automatically depending on the input type. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template - inline size_t Length(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::Length(its); - } - - // size_t LengthSafe(str): - // Get the length (in OutputEncoding) of the given string with the given InputEncoding. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template - inline size_t LengthSafe(const InputStringType& str, - typename Detail::SReqAnyObj::type* = 0) - { - return Detail::LengthSafe(str); - } - - // size_t LengthSafe(str): - // Get the length (in OutputEncoding) of the given Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template - inline size_t LengthSafe(const InputStringType& str, - typename Detail::SReqAutoObj::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - return Detail::LengthSafe(str); - } - - // size_t LengthSafe(begin, end): - // Get the length (in OutputEncoding) of the range with the given InputEncoding. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template - inline size_t LengthSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::LengthSafe(its); - } - - // size_t LengthSafe(begin, end): - // Get the length (in OutputEncoding) of the Unicode range. - // The Unicode encoding is picked automatically depending on the input type. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template - inline size_t LengthSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - return Detail::LengthSafe(its); - } - - // OutputStringType &Convert(result, str): - // Converts the given string in the given input encoding and stores into the result string with the given output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType& Convert(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - Detail::Convert(result, str); - return result; - } - - // OutputStringType &Convert(result, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType& Convert(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - Detail::Convert(result, str); - return result; - } - - // OutputStringType &Convert(result, begin, end): - // Converts the given range in the given input encoding and stores into the result string with the given output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType& Convert(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::Convert(result, its); - return result; - } - - // OutputStringType &Convert(result, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType& Convert(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::Convert(result, its); - return result; - } - - // size_t Convert(buffer, length, str): - // Converts the given string in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline size_t Convert(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert(result, str) + 1; - } - - // size_t Convert(buffer, length, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline size_t Convert(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert(result, str) + 1; - } - - // size_t Convert(buffer, length, begin, end): - // Converts the given range in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline size_t Convert(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // size_t Convert(buffer, length, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline size_t Convert(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // OutputStringType Convert(str): - // Converts the given string in the given input encoding to a new string of the given type and output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType Convert(const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - OutputStringType result; - Detail::Convert(result, str); - return result; - } - - // OutputStringType Convert(str): - // Converts the (assumed) Unicode string input to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType Convert(const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - OutputStringType result; - Detail::Convert(result, str); - return result; - } - - // OutputStringType Convert(begin, end): - // Converts the given range in the given input encoding to a new string of the given type and output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType Convert(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::Convert(result, its); - return result; - } - - // OutputStringType Convert(begin, end): - // Converts the (assumed) Unicode range to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template - inline OutputStringType Convert(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::Convert(result, its); - return result; - } - - // OutputStringType &ConvertSafe(result, str): - // Converts the given string in the given input encoding and stores into the result string with the given output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType& ConvertSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType &ConvertSafe(result, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType& ConvertSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType &ConvertSafe(result, begin, end): - // Converts the given range in the given input encoding and stores into the result string with the given output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType& ConvertSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe(result, its); - return result; - } - - // OutputStringType &ConvertSafe(result, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType& ConvertSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe(result, its); - return result; - } - - // size_t ConvertSafe(buffer, length, str): - // Converts the given string in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, str) + 1; - } - - // size_t ConvertSafe(buffer, length, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, str) + 1; - } - - // size_t ConvertSafe(buffer, length, begin, end): - // Converts the given range in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, its) + 1; - } - - // size_t ConvertSafe(buffer, length, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // OutputStringType ConvertSafe(str): - // Converts the given string in the given input encoding to a new string of the given type and output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType ConvertSafe(const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - OutputStringType result; - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType ConvertSafe(str): - // Converts the (assumed) Unicode string input to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType ConvertSafe(const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - OutputStringType result; - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType ConvertSafe(begin, end): - // Converts the given range in the given input encoding to a new string of the given type and output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType ConvertSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::ConvertSafe(result, its); - return result; - } - - // OutputStringType ConvertSafe(begin, end): - // Converts the (assumed) Unicode range to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template - inline OutputStringType ConvertSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::ConvertSafe(result, its); - return result; - } - - // OutputStringType &Append(result, str): - // Appends the given string in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline OutputStringType& Append(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - Detail::Convert(result, str); - return result; - } - - // OutputStringType &Append(result, str): - // Appends the (assumed) Unicode string input and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline OutputStringType& Append(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - Detail::Convert(result, str); - return result; - } - - // OutputStringType &Append(result, begin, end): - // Appends the given range in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline OutputStringType& Append(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::Convert(result, its); - return result; - } - - // OutputStringType &Append(result, begin, end): - // Appends the (assumed) Unicode range and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline OutputStringType& Append(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::Convert(result, its); - return result; - } - - // size_t Append(buffer, length, str): - // Appends the given string in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline size_t Append(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert(result, str) + 1; - } - - // size_t Append(buffer, length, str): - // Appends the (assumed) Unicode string input to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline size_t Append(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert(result, str) + 1; - } - - // size_t Append(buffer, length, begin, end): - // Appends the given range in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline size_t Append(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // size_t Append(buffer, length, begin, end): - // Appends the (assumed) Unicode range to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template - inline size_t Append(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } - - // OutputStringType &AppendSafe(result, str): - // Appends the given string in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline OutputStringType& AppendSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType &AppendSafe(result, str): - // Appends the (assumed) Unicode string input and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline OutputStringType& AppendSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - Detail::ConvertSafe(result, str); - return result; - } - - // OutputStringType &AppendSafe(result, begin, end): - // Appends the given range in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline OutputStringType& AppendSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe(result, its); - return result; - } - - // OutputStringType &AppendSafe(result, begin, end): - // Appends the (assumed) Unicode range and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline OutputStringType& AppendSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe(result, its); - return result; - } - - // size_t AppendSafe(buffer, length, str): - // Appends the given string in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline size_t AppendSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut::type* = 0) - { - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, str) + 1; - } - - // size_t AppendSafe(buffer, length, str): - // Appends the (assumed) Unicode string input to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline size_t AppendSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedBuffer OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, str) + 1; - } - - // size_t AppendSafe(buffer, length, begin, end): - // Appends the given range in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline size_t AppendSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut::type* = 0) - { - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::ConvertSafe(result, its) + 1; - } - - // size_t AppendSafe(buffer, length, begin, end): - // Appends the (assumed) Unicode range to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template - inline size_t AppendSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding::value; - const EEncoding OutputEncoding = Detail::SInferEncoding::value; - typedef Detail::SPackedIterators InputStringType; - typedef Detail::SPackedBuffer OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert(result, its) + 1; - } -} diff --git a/Code/Legacy/CryCommon/UnicodeIterator.h b/Code/Legacy/CryCommon/UnicodeIterator.h deleted file mode 100644 index d939eaa721..0000000000 --- a/Code/Legacy/CryCommon/UnicodeIterator.h +++ /dev/null @@ -1,615 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Encoded Unicode sequence iteration. -// -// For lower level accessing of encoded text, an STL compatible iterator wrapper is provided. -// This iterator will decode the underlying sequence, abstracting it to a sequence of UCS code-points. -// Using the iterator wrapper, you can find where in an encoded string code-points (or encoding errors) are located. -// Note: The iterator is an input-only iterator, you cannot write to the underlying sequence. - - -#pragma once -#include "UnicodeBinding.h" -namespace Unicode -{ - namespace Detail - { - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Non-specialized version (for 1:1 code-unit to code-point). - template - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, const integral_constant) - { - COMPILE_TIME_ASSERT( - Encoding == eEncoding_ASCII || - Encoding == eEncoding_UTF32 || - Encoding == eEncoding_Latin1 || - Encoding == eEncoding_Win1252); - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // All of these encodings use a single code-unit for each code-point. - ++it; - } - - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Specialized for UTF-8. - template - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, integral_constant) - { - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // UTF-8: just need to skip up to 3 continuation bytes. - for (int i = 0; i < 4; ++i) - { - ++it; - if (checker.IsEnd(it)) // :WARN: always returns false if "safe" bool is false! - { - break; - } - uint32 val = static_cast(*it); - if ((val & 0xC0) != 0x80) - { - break; - } - } - } - - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Specialized for UTF-16. - template - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, integral_constant) - { - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // UTF-16: just need to skip one lead surrogate. - ++it; - uint32 val = static_cast(*it); - if (val >= cLeadSurrogateFirst && val <= cLeadSurrogateLast) - { - if (!checker.IsEnd(it)) - { - ++it; - } - } - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Non-specialized version (for 1:1 code-unit to code-point). - template - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, const integral_constant) - { - COMPILE_TIME_ASSERT( - Encoding == eEncoding_ASCII || - Encoding == eEncoding_UTF32 || - Encoding == eEncoding_Latin1 || - Encoding == eEncoding_Win1252); - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // All of these encodings use a single code-unit for each code-point. - --it; - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Specialized for UTF-8. - template - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, integral_constant) - { - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // UTF-8: just need to skip up to 3 continuation bytes. - for (int i = 0; i < 4; ++i) - { - --it; - if (checker.IsBegin(it)) - { - break; - } - uint32 val = static_cast(*it); - if ((val & 0xC0) != 0x80) - { - break; - } - } - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Specialized for UTF-16. - template - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, integral_constant) - { - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // UTF-16: just need to skip one lead surrogate. - --it; - uint32 val = static_cast(*it); - if (val >= cLeadSurrogateFirst && val <= cLeadSurrogateLast) - { - if (!checker.IsBegin(it)) - { - --it; - } - } - } - - // SBaseIterators: - // Utility to access base iterators properties from CIterator. - // This is the bounds-checked specialization, the range information is kept to defend against malformed sequences. - template - struct SBaseIterators - { - typedef BaseIterator type; - type begin, end; - type it; - - SBaseIterators(const BaseIterator& _begin, const BaseIterator& _end) - : begin(_begin) - , end(_end) - , it(_begin) {} - - SBaseIterators(const SBaseIterators& other) - : begin(other.begin) - , end(other.end) - , it(other.it) {} - - SBaseIterators& operator =(const SBaseIterators& other) - { - begin = other.begin; - end = other.end; - it = other.it; - return *this; - } - - bool IsBegin(const BaseIterator& _it) const - { - return begin == _it; - } - - bool IsEnd(const BaseIterator& _it) const - { - return end == _it; - } - - bool IsEqual(const SBaseIterators& other) const - { - return it == other.it - && begin == other.begin - && end == other.end; - } - - // Note: Only called inside assert. - // O(N) version; works with any forward-iterator (or better) - bool IsInRange(const BaseIterator& _it, std::forward_iterator_tag) const - { - for (BaseIterator i = begin; i != end; ++i) - { - if (_it == i) - { - return true; - } - } - return false; - } - - // Note: Only called inside assert. - // O(1) version; requires random-access-iterator. - bool IsInRange(const BaseIterator& _it, std::random_access_iterator_tag) const - { - return (begin <= _it && _it < end); - } - - // Note: Only called inside assert. - // Dispatches to the O(1) version if a random-access iterator is used (common case). - bool IsInRange(const BaseIterator& _it) const - { - return IsInRange(_it, typename std::iterator_traits::iterator_category()); - } - }; - - // SBaseIterators: - // Utility to access base iterators properties from CIterator. - // This is the un-checked specialization for known-safe sequences. - template - struct SBaseIterators - { - typedef BaseIterator type; - type it; - - explicit SBaseIterators(const BaseIterator& begin) - : it(begin) {} - - SBaseIterators(const BaseIterator& begin, const BaseIterator& end) - : it(begin) {} - - SBaseIterators(const SBaseIterators& other) - : it(other.it) {} - - SBaseIterators& operator =(const SBaseIterators& other) - { - it = other.it; - return *this; - } - - bool IsBegin(const BaseIterator&) const - { - return false; - } - - bool IsEnd(const BaseIterator&) const - { - return false; - } - - bool IsEqual(const SBaseIterators& other) const - { - return it == other.it; - } - - bool IsInRange(const BaseIterator&) const - { - return true; - } - }; - - // SIteratorSink: - // Helper to store the last code-point and error bit that was decoded. - // This is the safe specialization for potentially malformed sequences. - template - struct SIteratorSink - { - static const uint32 cEmpty = 0xFFFFFFFFU; - uint32 value; - bool error; - - void Clear() - { - value = cEmpty; - error = false; - } - - bool IsEmpty() const - { - return value == cEmpty; - } - - bool IsError() const - { - return error; - } - - const uint32& GetValue() const - { - return value; - } - - void MarkDecodingError() - { - value = cReplacementCharacter; - error = true; - } - - template - void Decode(const SBaseIterators& its, integral_constant) - { - typedef SDecoder DecoderType; - DecoderType decoder(*this, *this); - Clear(); - for (BaseIterator it = its.it; IsEmpty(); ++it) - { - uint32 val = static_cast(*it); - decoder(val); - if (its.IsEnd(it)) - { - break; - } - } - if (IsEmpty()) - { - // If we still have neither a new value or an error flag, just treat as error. - // This can happen if we reached the end of the sequence, but it ends in an incomplete code-sequence. - MarkDecodingError(); - } - } - - template - void DecodeIfEmpty(const SBaseIterators& its, integral_constant tag) - { - if (IsEmpty()) - { - Decode(its, tag); - } - } - - void operator()(uint32 unit) - { - value = unit; - } - - void operator()(SIteratorSink&, uint32, uint32) - { - MarkDecodingError(); - } - }; - - // SIteratorSink: - // Helper to store the last code-point that was decoded. - // This is the un-safe specialization for known-valid sequences. - // Note: No error-state is tracked since we won't handle that regardless for un-safe CIterator. - template<> - struct SIteratorSink - { - static const uint32 cEmpty = 0xFFFFFFFFU; - uint32 value; - - void Clear() - { - value = cEmpty; - } - - bool IsEmpty() const - { - return value == cEmpty; - } - - bool IsError() const - { - return false; - } - - const uint32& GetValue() const - { - return value; - } - - template - void Decode(const SBaseIterators& its, integral_constant) - { - typedef SDecoder DecoderType; - DecoderType decoder(*this); - for (BaseIterator it = its.it; IsEmpty(); ++it) - { - uint32 val = static_cast(*it); - decoder(val); - } - } - - template - void DecodeIfEmpty(const SBaseIterators& its, integral_constant tag) - { - if (IsEmpty()) - { - Decode(its, tag); - } - } - - void operator()(uint32 unit) - { - value = unit; - } - }; - } - - // CIterator: - // Helper class that can iterate over an encoded text sequence and read the underlying UCS code-points. - // If the Safe flag is set, bounds checking is performed inside multi-unit sequences to guard against decoding errors. - // This requires the user to know where the sequence ends (use the constructor taking two parameters). - // Note: The BaseIterator must be forward-iterator or better when Safe flag is set. - // If the Safe flag is not set, you must guarantee the sequence is validly encoded, and allows the use of the single argument constructor. - // In the case of unsafe iterator used for C-style string pointer, look for a U+0000 dereferenced value to end the iteration. - // Regardless of the Safe flag, the user must ensure that the iterator is never moved past the beginning or end of the range (just like any other STL iterator). - // Example of typical usage: - // string utf8 = "foo"; // UTF-8 - // for (Unicode::CIterator it(utf8.begin(), utf8.end()); it != utf8.end(); ++it) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - // Example unsafe usage: (for known-valid encoded C-style strings): - // const char *pValid = "foo"; // UTF-8 - // for (Unicode::CIterator it = pValid; *it != 0; ++it) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - template::value> - class CIterator - { - // The iterator value in the encoded sequence. - // Optionally provides bounds-checking. - Detail::SBaseIterators its; - - // The cached UCS code-point at the current position. - // Mutable because dereferencing is conceptually const, but does cache some state in this case. - mutable Detail::SIteratorSink sink; - - public: - // Types for compatibility with STL bidirectional iterator requirements. - typedef const uint32 value_type; - typedef const uint32& reference; - typedef const uint32* pointer; - typedef const ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - - // Construct an iterator for the given range. - // The initial position of the iterator as at the beginning of the range. - CIterator(const BaseIterator& begin, const BaseIterator& end) - : its(begin, end) - { - sink.Clear(); - } - - // Construct an iterator from a single iterator (typically C-style string pointer). - // This can only be used for unsafe iterators. - template - CIterator(const IteratorType& it, typename Detail::SRequire::value, IteratorType>::type* = 0) - : its(static_cast(it)) - { - sink.Clear(); - } - - // Copy-construct an iterator. - CIterator(const CIterator& other) - : its(other.its) - , sink(other.sink) {} - - // Copy-assign an iterator. - CIterator& operator =(const CIterator& other) - { - its = other.its; - sink = other.sink; - return *this; - } - - // Test if the iterator points at an encoding error in the underlying encoded sequence. - // If so, the function returns false. - // When using an un-safe iterator, this function always returns true, if a sequence can contain encoding errors, you must use the safe variant. - // Note: This requires the underlying iterator to be dereferenced, so you cannot use it only while the iterator is inside the valid range. - bool IsAtValidCodepoint() const - { - assert(!its.IsEnd(its.it) && "Attempt to dereference the past-the-end iterator"); - Detail::integral_constant tag; - sink.DecodeIfEmpty(its, tag); - return !sink.IsError(); - } - - // Gets the current position in the underlying encoded sequence. - // If the iterator points to an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // In that case the returned position is approximated; to work around this: move all iterators of which the position is compared in the same direction. - const BaseIterator& GetPosition() const - { - return its.it; - } - - // Sets the current position in the underlying encoded sequence. - // You may not set the position outside the range for which this iterator was constructed. - void SetPosition(const BaseIterator& it) - { - assert(its.IsInRange(it) && "Attempt to set the underlying iterator outside of the supported range"); - its.it = it; - } - - // Test if this iterator is equal to another iterator instance. - // Note: In the presence of an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // To work around this, you can either: - // 1) Move all iterators that will be compared in the same direction; or - // 2) Compare the dereferenced iterator value(s) instead (if applicable). - bool operator ==(const CIterator& other) const - { - return its.IsEqual(other.its); - } - - // Test if this iterator is equal to another base iterator. - // Note: If the provided iterator does not point to the the first code-unit of an UCS code-point, the behavior is undefined. - bool operator ==(const BaseIterator& other) const - { - return its.it == other; - } - - // Test if this iterator is equal to another iterator instance. - // Note: In the presence of an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // To work around this, you can either: - // 1) Move all iterators that will be compared in the same direction; or - // 2) Compare the dereferenced iterator value(s) instead (if applicable). - bool operator !=(const CIterator& other) const - { - return !its.IsEqual(other.its); - } - - // Test if this iterator is equal to another base iterator. - // Note: If the provided iterator does not point to the the first code-unit of an UCS code-point, the behavior is undefined. - bool operator !=(const BaseIterator& other) const - { - return its.it != other; - } - - // Get the decoded UCS code-point at the current position in the sequence. - // If the iterator points to an invalidly encoded sequence (ie, IsError() returns true) the function returns U+FFFD (replacement character). - reference operator *() const - { - assert(!its.IsEnd(its.it) && "Attempt to dereference the past-the-end iterator"); - Detail::integral_constant tag; - sink.DecodeIfEmpty(its, tag); - return sink.GetValue(); - } - - // Advance the iterator to the next UCS code-point. - // Note: You must make sure the iterator is not at the end of the sequence, even in Safe mode. - // However, in Safe mode, the iterator will never move past the end of the sequence in the presence of encoding errors. - CIterator& operator ++() - { - Detail::integral_constant tag; - Detail::MoveNext(its.it, its, tag); - sink.Clear(); - return *this; - } - - // Go back to the previous UCS code-point. - // Note: You must make sure the iterator is not at the beginning of the sequence, even in Safe mode. - // However, in Safe mode, the iterators will never move past the beginning of the sequence in the presence of encoding errors. - CIterator& operator --() - { - Detail::integral_constant tag; - Detail::MovePrev(its.it, its, tag); - sink.Clear(); - return *this; - } - - // Advance the iterator to the next UCS code-point, return a copy of the iterator position before advancing. - // Note: You must make sure the iterator is not at the end of the sequence, even in Safe mode. - // However, in Safe mode, the iterator will never move past the end of the sequence in the presence of encoding errors. - CIterator operator ++(int) - { - CIterator result = *this; - ++*this; - return result; - } - - // Go back to the previous UCS code-point, return a copy of the iterator position before going back. - // Note: You must make sure the iterator is not at the beginning of the sequence, even in Safe mode. - // However, in Safe mode, the iterators will never move past the beginning of the sequence in the presence of encoding errors. - CIterator operator --(int) - { - CIterator result = *this; - --*this; - return result; - } - }; - - namespace Detail - { - // SIteratorSpecializer: - // Specializes the CIterator template to use for a given string type. - // Note: The reason we use this is because MSVC doesn't want to deduce this on the MakeIterator declaration. - template - struct SIteratorSpecializer - { - typedef CIterator type; - }; - } - - // MakeIterator(const StringType &str): - // Helper function to make an UCS code-point iterator given an Unicode string. - // Example usage: - // string utf8 = "foo"; // UTF-8 - // auto it = Unicode::MakeIterator(utf8); - // while (it != utf8.end()) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - // Or, in a for-loop: - // for (auto it = Unicode::MakeIterator(utf8); it != utf8.end(); ++it) {} - template - inline typename Detail::SIteratorSpecializer::type MakeIterator(const StringType& str) - { - return typename Detail::SIteratorSpecializer::type(str.begin(), str.end()); - } -} diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index 63c5b49513..c78a6a4df0 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -116,10 +116,6 @@ set(FILES TimeValue_info.h TypeInfo_decl.h TypeInfo_impl.h - UnicodeBinding.h - UnicodeEncoding.h - UnicodeFunctions.h - UnicodeIterator.h VectorMap.h VectorSet.h VertexFormats.h From b86349c3bf909d8181af535cd6efff77c8a8b446 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:50:39 -0700 Subject: [PATCH 020/205] Some fixes for AzCore Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../AzCore/Debug/StackTracer_Windows.cpp | 18 +++++++-------- .../IO/Streamer/StorageDrive_Windows.cpp | 15 +++++++++---- .../AzCore/IPC/SharedMemory_Windows.cpp | 13 +++++++---- .../NativeUISystemComponent_Windows.cpp | 13 ++++++++--- .../Windows/AzCore/Platform_Windows.cpp | 8 +++---- .../Windows/AzCore/Utils/Utils_Windows.cpp | 7 +++++- .../std/parallel/internal/thread_Windows.cpp | 22 +++++++++++-------- 7 files changed, 62 insertions(+), 34 deletions(-) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index d2cdac84c7..8a99616de3 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -90,7 +90,7 @@ namespace AZ { { case CBA_EVENT: evt = (PIMAGEHLP_CBA_EVENT)CallbackData; - _tprintf(_T("%s"), (PTSTR)evt->desc); + _tprintf(_T("%s"), evt->desc); break; default: @@ -300,7 +300,7 @@ namespace AZ { return; } - const HMODULE hNtDll = GetModuleHandle(_T("ntdll.dll")); + const HMODULE hNtDll = GetModuleHandleW(L"ntdll.dll"); m_LdrRegisterDllNotification = reinterpret_cast(GetProcAddress(hNtDll, "LdrRegisterDllNotification")); if (m_LdrRegisterDllNotification) @@ -324,7 +324,7 @@ namespace AZ { return; } - const HMODULE hNtDll = GetModuleHandle(_T("ntdll.dll")); + const HMODULE hNtDll = GetModuleHandleW(L"ntdll.dll"); m_LdrUnregisterDllNotification = reinterpret_cast(GetProcAddress(hNtDll, "LdrUnregisterDllNotification")); if (m_LdrUnregisterDllNotification) @@ -609,8 +609,8 @@ namespace AZ { if (GetFileVersionInfoA(szImg, dwHandle, dwSize, vData) != 0) { UINT len; - TCHAR szSubBlock[] = _T("\\"); - if (VerQueryValue(vData, szSubBlock, (LPVOID*) &fInfo, &len) == 0) + TCHAR szSubBlock[] = L"\\"; + if (VerQueryValueW(vData, szSubBlock, (LPVOID*) &fInfo, &len) == 0) { fInfo = NULL; } @@ -711,7 +711,7 @@ namespace AZ { typedef BOOL (__stdcall * tM32N)(HANDLE hSnapshot, LPMODULEENTRY32 lpme); // try both dlls... - const TCHAR* dllname[] = { _T("kernel32.dll"), _T("tlhelp32.dll") }; + const TCHAR* dllname[] = { L"kernel32.dll", L"tlhelp32.dll" }; HINSTANCE hToolhelp = NULL; tCT32S pCT32S = NULL; tM32F pM32F = NULL; @@ -822,7 +822,7 @@ namespace AZ { const SIZE_T TTBUFLEN = 8096; int cnt = 0; - hPsapi = LoadLibrary(_T("psapi.dll")); + hPsapi = LoadLibraryW(L"psapi.dll"); if (hPsapi == NULL) { return FALSE; @@ -956,10 +956,10 @@ cleanup: // In that scenario, we may try to load and older dbghelp.dll which could cause issues // To overcome this, we try to load dbghelp.dll from the Win 10 SDK folder, if that doesn't // work, load the default. - g_dbgHelpDll = LoadLibrary(_T(R"(C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\dbghelp.dll)")); + g_dbgHelpDll = LoadLibraryW(LR"(C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\dbghelp.dll)"); if (g_dbgHelpDll == NULL) { - g_dbgHelpDll = LoadLibrary(_T("dbghelp.dll")); + g_dbgHelpDll = LoadLibrary(L"dbghelp.dll"); } } if (g_dbgHelpDll == NULL) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp index 671cc99aac..2489749b51 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp @@ -16,6 +16,7 @@ #include #include #include +#include namespace AZ::IO { @@ -467,8 +468,10 @@ namespace AZ::IO DWORD createFlags = m_constructionOptions.m_enableUnbufferedReads ? (FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING) : FILE_FLAG_OVERLAPPED; DWORD shareMode = (m_constructionOptions.m_enableSharing || data.m_sharedRead) ? FILE_SHARE_READ: 0; - file = ::CreateFile( - data.m_path.GetAbsolutePath(), // file name + AZStd::wstring filenameW; + AZStd::to_wstring(filenameW, data.m_path.GetAbsolutePath()); + file = ::CreateFileW( + filenameW.c_str(), // file name FILE_GENERIC_READ, // desired access shareMode, // share mode nullptr, // security attributes @@ -806,7 +809,9 @@ namespace AZ::IO } WIN32_FILE_ATTRIBUTE_DATA attributes; - if (::GetFileAttributesEx(fileExists.m_path.GetAbsolutePath(), GetFileExInfoStandard, &attributes)) + AZStd::wstring filenameW; + AZStd::to_wstring(filenameW, fileExists.m_path.GetAbsolutePath()); + if (::GetFileAttributesExW(filenameW.c_str(), GetFileExInfoStandard, &attributes)) { if ((attributes.dwFileAttributes != INVALID_FILE_ATTRIBUTES) && ((attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) @@ -863,7 +868,9 @@ namespace AZ::IO else { WIN32_FILE_ATTRIBUTE_DATA attributes; - if (::GetFileAttributesEx(command.m_path.GetAbsolutePath(), GetFileExInfoStandard, &attributes) && + AZStd::wstring filenameW; + AZStd::to_wstring(filenameW, command.m_path.GetAbsolutePath()); + if (::GetFileAttributesExW(filenameW.c_str(), GetFileExInfoStandard, &attributes) && (attributes.dwFileAttributes != INVALID_FILE_ATTRIBUTES) && ((attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) { fileSize.LowPart = attributes.nFileSizeLow; diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp index 0797541652..21b2a76ba0 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp @@ -10,6 +10,7 @@ #include #include +#include namespace AZ { @@ -41,7 +42,9 @@ namespace AZ SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE); // Obtain global mutex - m_globalMutex = CreateMutex(&secAttr, FALSE, fullName); + AZStd::wstring fullNameW; + AZStd::to_wstring(fullNameW, fullName); + m_globalMutex = CreateMutexW(&secAttr, FALSE, fullNameW.c_str()); DWORD error = GetLastError(); if (m_globalMutex == NULL || (error == ERROR_ALREADY_EXISTS && openIfCreated == false)) { @@ -51,7 +54,7 @@ namespace AZ // Create the file mapping. azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name); - m_mapHandle = CreateFileMapping(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, size, fullName); + m_mapHandle = CreateFileMappingW(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, size, fullNameW.c_str()); error = GetLastError(); if (m_mapHandle == NULL || (error == ERROR_ALREADY_EXISTS && openIfCreated == false)) { @@ -66,8 +69,10 @@ namespace AZ { char fullName[256]; ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name); + AZStd::wstring fullNameW; + AZStd::to_wstring(fullNameW, fullName); - m_globalMutex = OpenMutex(SYNCHRONIZE, TRUE, fullName); + m_globalMutex = OpenMutex(SYNCHRONIZE, TRUE, fullNameW.c_str()); AZ_Warning("AZSystem", m_globalMutex != NULL, "Failed to open OS mutex [%s]\n", m_name); if (m_globalMutex == NULL) { @@ -76,7 +81,7 @@ namespace AZ } azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name); - m_mapHandle = OpenFileMapping(FILE_MAP_WRITE, false, fullName); + m_mapHandle = OpenFileMapping(FILE_MAP_WRITE, false, fullNameW.c_str()); if (m_mapHandle == NULL) { AZ_TracePrintf("AZSystem", "OpenFileMapping %s failed with error %d\n", m_name, GetLastError()); diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/NativeUI/NativeUISystemComponent_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/NativeUI/NativeUISystemComponent_Windows.cpp index 568f727905..af2a629092 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/NativeUI/NativeUISystemComponent_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/NativeUI/NativeUISystemComponent_Windows.cpp @@ -10,6 +10,7 @@ #include #include +#include namespace { @@ -105,11 +106,17 @@ namespace { // Set the text for window title, message, buttons. info = (DlgInfo*)lParam; - SetWindowText(hDlg, info->m_title.c_str()); - SetWindowText(GetDlgItem(hDlg, 0), info->m_message.c_str()); + AZStd::wstring titleW; + AZStd::to_wstring(titleW, info->m_title.c_str()); + SetWindowTextW(hDlg, titleW.c_str()); + AZStd::wstring messageW; + AZStd::to_wstring(messageW, info->m_message.c_str()); + SetWindowTextW(GetDlgItem(hDlg, 0), messageW.c_str()); for (int i = 0; i < info->m_options.size(); i++) { - SetWindowText(GetDlgItem(hDlg, i + 1), info->m_options[i].c_str()); + AZStd::wstring optionW; + AZStd::to_wstring(optionW, info->m_options[i].c_str()); + SetWindowTextW(GetDlgItem(hDlg, i + 1), optionW.c_str()); } } break; diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp index 27e0bd11e1..dc675cd931 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp @@ -37,7 +37,7 @@ namespace AZ { DWORD dataType = REG_SZ; DWORD dataSize = sizeof(machineInfo); - ret = RegQueryValueEx(key, "MachineGuid", 0, &dataType, (LPBYTE)machineInfo, &dataSize); + ret = RegQueryValueExW(key, L"MachineGuid", 0, &dataType, (LPBYTE)machineInfo, &dataSize); RegCloseKey(key); } else @@ -45,7 +45,7 @@ namespace AZ AZ_Error("System", false, "Failed to open HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid!") } - TCHAR* hostname = machineInfo + _tcslen(machineInfo); + TCHAR* hostname = machineInfo + wcslen(machineInfo); // salt the guid time with ComputerName/UserName DWORD bufCharCount = DWORD(sizeof(machineInfo) - (hostname - machineInfo)); if (!::GetComputerName(hostname, &bufCharCount)) @@ -53,7 +53,7 @@ namespace AZ AZ_Error("System", false, "GetComputerName filed with code %d", GetLastError()); } - TCHAR* username = hostname + _tcslen(hostname); + TCHAR* username = hostname + wcslen(hostname); bufCharCount = DWORD(sizeof(machineInfo) - (username - machineInfo)); if( !GetUserName( username, &bufCharCount ) ) { @@ -62,7 +62,7 @@ namespace AZ Sha1 hash; AZ::u32 digest[5] = { 0 }; - hash.ProcessBytes(machineInfo, _tcslen(machineInfo) * sizeof(TCHAR)); + hash.ProcessBytes(machineInfo, wcslen(machineInfo) * sizeof(TCHAR)); hash.GetDigest(digest); s_machineId = digest[0]; if (s_machineId == 0) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp index 749cf1ba82..fd8353b45f 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Utils/Utils_Windows.cpp @@ -8,6 +8,7 @@ #include #include +#include #include @@ -15,7 +16,11 @@ namespace AZ::Utils { void NativeErrorMessageBox(const char* title, const char* message) { - ::MessageBox(0, message, title, MB_OK | MB_ICONERROR); + AZStd::wstring wtitle; + AZStd::to_wstring(wtitle, title); + AZStd::wstring wmessage; + AZStd::to_wstring(wmessage, message); + ::MessageBoxW(0, wmessage.c_str(), wtitle.c_str(), MB_OK | MB_ICONERROR); } AZ::IO::FixedMaxPathString GetHomeDirectory() diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/std/parallel/internal/thread_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/std/parallel/internal/thread_Windows.cpp index ea92a16838..246181334a 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/std/parallel/internal/thread_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/std/parallel/internal/thread_Windows.cpp @@ -8,6 +8,7 @@ #include #include +#include #include @@ -37,17 +38,20 @@ namespace AZStd // SetThreadDescription was added in 1607 (aka RS1). Since we can't guarantee the user is running 1607 or later, we need to ask for the function from the kernel. using SetThreadDescriptionFunc = HRESULT(WINAPI*)(_In_ HANDLE hThread, _In_ PCWSTR lpThreadDescription); - auto setThreadDescription = reinterpret_cast(::GetProcAddress(::GetModuleHandle("Kernel32.dll"), "SetThreadDescription")); - if (setThreadDescription) + HMODULE kernel32Handle = ::GetModuleHandleW(L"Kernel32.dll"); + if (kernel32Handle) { - // Convert the thread name to Unicode - wchar_t threadNameW[MAX_PATH]; - size_t numCharsConverted; - errno_t wcharResult = mbstowcs_s(&numCharsConverted, threadNameW, threadName, AZ_ARRAY_SIZE(threadNameW) - 1); - if (wcharResult == 0) + SetThreadDescriptionFunc setThreadDescription = reinterpret_cast(::GetProcAddress(kernel32Handle, "SetThreadDescription")); + if (setThreadDescription) { - setThreadDescription(hThread, threadNameW); - return true; + // Convert the thread name to Unicode + AZStd::wstring threadNameW; + AZStd::to_wstring(threadNameW, threadName); + if (!threadNameW.empty()) + { + setThreadDescription(hThread, threadNameW.c_str()); + return true; + } } } From 95c6fd83ead69bad55b067fe3eb3a9549064738a Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:53:16 -0700 Subject: [PATCH 021/205] remove !defined(RESOURCE_COMPILER) since is not defined anywhere (resource compiler was removed) Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/ILog.h | 2 -- Code/Legacy/CryCommon/IXml.h | 10 ---------- Code/Legacy/CryCommon/ProjectDefines.h | 7 ++----- Code/Legacy/CryCommon/platform_impl.cpp | 2 -- 4 files changed, 2 insertions(+), 19 deletions(-) diff --git a/Code/Legacy/CryCommon/ILog.h b/Code/Legacy/CryCommon/ILog.h index de60c1e9e0..e71e1f036d 100644 --- a/Code/Legacy/CryCommon/ILog.h +++ b/Code/Legacy/CryCommon/ILog.h @@ -145,9 +145,7 @@ struct ILog virtual void Unindent(class CLogIndenter* indenter) = 0; #endif -#if !defined(RESOURCE_COMPILER) virtual void FlushAndClose() = 0; -#endif }; #if !defined(SUPPORT_LOG_IDENTER) diff --git a/Code/Legacy/CryCommon/IXml.h b/Code/Legacy/CryCommon/IXml.h index e4cb752234..a380ce167b 100644 --- a/Code/Legacy/CryCommon/IXml.h +++ b/Code/Legacy/CryCommon/IXml.h @@ -147,13 +147,11 @@ public: XmlNodeRef& operator=(IXmlNode* newp); XmlNodeRef& operator=(const XmlNodeRef& newp); -#if !defined(RESOURCE_COMPILER) template void GetMemoryUsage(Sizer* pSizer) const { pSizer->AddObject(p); } -#endif //Support for range based for, and stl algorithms. class XmlNodeRefIterator begin(); @@ -399,7 +397,6 @@ public: // -#if !defined(RESOURCE_COMPILER) // // Summary: // Collect all allocated memory @@ -423,7 +420,6 @@ public: // Save in small memory chunks. virtual bool saveToFile(const char* fileName, size_t chunkSizeBytes, AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle) = 0; // -#endif //##@} @@ -792,12 +788,9 @@ struct IXmlSerializer virtual ISerialize* GetWriter(XmlNodeRef& node) = 0; virtual ISerialize* GetReader(XmlNodeRef& node) = 0; // -#if !defined(RESOURCE_COMPILER) virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; -#endif }; -#if !defined(RESOURCE_COMPILER) ////////////////////////////////////////////////////////////////////////// // Summary: // XML Parser interface. @@ -867,7 +860,6 @@ struct IXmlTableReader virtual float GetCurrentRowHeight() = 0; // }; -#endif ////////////////////////////////////////////////////////////////////////// // Summary: @@ -900,7 +892,6 @@ struct IXmlUtils virtual IXmlSerializer* CreateXmlSerializer() = 0; // -#if !defined(RESOURCE_COMPILER) // // Summary: // Creates XML Parser. @@ -945,7 +936,6 @@ struct IXmlUtils // Set to NULL to clear an existing transform and disable further patching virtual void SetXMLPatcher(XmlNodeRef* pPatcher) = 0; // -#endif }; #endif // CRYINCLUDE_CRYCOMMON_IXML_H diff --git a/Code/Legacy/CryCommon/ProjectDefines.h b/Code/Legacy/CryCommon/ProjectDefines.h index 3d635c491c..e359fe669b 100644 --- a/Code/Legacy/CryCommon/ProjectDefines.h +++ b/Code/Legacy/CryCommon/ProjectDefines.h @@ -42,10 +42,7 @@ // Type used for vertex indices // WARNING: If you change this typedef, you need to update AssetProcessorPlatformConfig.ini to convert cgf and abc files to the proper index format. -#if defined(RESOURCE_COMPILER) -typedef uint32 vtx_idx; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(MOBILE) +#if defined(MOBILE) typedef uint16 vtx_idx; #define AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(AZ_RESTRICTED_PLATFORM) @@ -138,7 +135,7 @@ typedef uint32 vtx_idx; # define PHYSICS_STACK_SIZE (128U << 10) #endif -#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !defined(RESOURCE_COMPILER) +#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) #ifndef ENABLE_PROFILING_CODE #define ENABLE_PROFILING_CODE #endif diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index 6ec8df0365..54bf38aaa0 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -240,13 +240,11 @@ void CryLowLatencySleep(unsigned int dwMilliseconds) int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const char* lpCaption, [[maybe_unused]] unsigned int uType) { #ifdef WIN32 -#if !defined(RESOURCE_COMPILER) ICVar* const pCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_crash_dialog") : NULL; if ((pCVar && pCVar->GetIVal() != 0) || (gEnv && gEnv->bNoAssertDialog)) { return 0; } -#endif return MessageBox(NULL, lpText, lpCaption, uType); #else return 0; From 99bf5e54c4a7db18bf20b3029259771375d3ddc8 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:53:32 -0700 Subject: [PATCH 022/205] More string fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/IMovieSystem.h | 11 +- Code/Legacy/CryCommon/LyShine/ILyShine.h | 10 +- Code/Legacy/CrySystem/CmdLine.h | 8 +- Code/Legacy/CrySystem/CmdLineArg.h | 4 +- Code/Legacy/CrySystem/ConsoleBatchFile.cpp | 26 +-- Code/Legacy/CrySystem/ConsoleHelpGen.cpp | 68 +++--- Code/Legacy/CrySystem/ConsoleHelpGen.h | 10 +- Code/Legacy/CrySystem/DebugCallStack.cpp | 38 ++-- Code/Legacy/CrySystem/DebugCallStack.h | 10 +- Code/Legacy/CrySystem/IDebugCallStack.cpp | 2 +- Code/Legacy/CrySystem/IDebugCallStack.h | 10 +- .../CrySystem/LevelSystem/LevelSystem.cpp | 2 +- .../CrySystem/LocalizedStringManager.cpp | 209 ++++++++++-------- .../Legacy/CrySystem/LocalizedStringManager.h | 66 +++--- Code/Legacy/CrySystem/Log.cpp | 28 +-- Code/Legacy/CrySystem/System.cpp | 30 +-- Code/Legacy/CrySystem/System.h | 14 +- Code/Legacy/CrySystem/SystemCFG.cpp | 62 +++--- Code/Legacy/CrySystem/SystemCFG.h | 16 +- Code/Legacy/CrySystem/SystemInit.cpp | 1 - Code/Legacy/CrySystem/SystemWin32.cpp | 8 +- Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h | 2 +- Code/Legacy/CrySystem/XML/ReadXMLSink.cpp | 9 +- .../CrySystem/XML/SerializeXMLWriter.cpp | 4 +- .../Legacy/CrySystem/XML/SerializeXMLWriter.h | 2 +- Code/Legacy/CrySystem/XML/WriteXMLSource.cpp | 4 +- Code/Legacy/CrySystem/XML/XMLBinaryWriter.h | 12 +- Code/Legacy/CrySystem/XML/XMLPatcher.cpp | 17 +- Code/Legacy/CrySystem/XML/XmlUtils.cpp | 2 +- Code/Legacy/CrySystem/XML/xml.cpp | 18 +- Code/Tools/GridHub/GridHub/gridhub.cpp | 4 - Code/Tools/Standalone/CMakeLists.txt | 2 - .../Platform/Windows/FFontXML_Windows.cpp | 12 +- .../Platform/Windows/FontTexture_Windows.cpp | 2 +- .../AtomFont/Code/Source/AtomFont.cpp | 121 +++++----- .../AtomFont/Code/Source/FFont.cpp | 4 +- .../Code/Editor/PropertyHandlerChar.cpp | 3 +- .../Platform/Windows/UiClipboard_Windows.cpp | 6 +- Gems/LyShine/Code/Source/StringUtfUtils.h | 3 +- .../LyShine/Code/Source/UiButtonComponent.cpp | 2 +- Gems/LyShine/Code/Source/UiImageComponent.cpp | 2 +- Gems/LyShine/Code/Source/UiTextComponent.cpp | 2 +- .../Code/Source/UiTextInputComponent.cpp | 5 +- 43 files changed, 439 insertions(+), 432 deletions(-) diff --git a/Code/Legacy/CryCommon/IMovieSystem.h b/Code/Legacy/CryCommon/IMovieSystem.h index 074c7ab01d..915dc925bf 100644 --- a/Code/Legacy/CryCommon/IMovieSystem.h +++ b/Code/Legacy/CryCommon/IMovieSystem.h @@ -112,7 +112,7 @@ public: CAnimParamType() : m_type(kAnimParamTypeInvalid) {} - CAnimParamType(const string& name) + CAnimParamType(const AZStd::string& name) { *this = name; } @@ -128,17 +128,12 @@ public: m_type = type; } - void operator =(const string& name) - { - m_type = kAnimParamTypeByString; - m_name = name; - } - void operator =(const AZStd::string& name) { m_type = kAnimParamTypeByString; m_name = name; } + // Convert to enum. This needs to be explicit, // otherwise operator== will be ambiguous AnimParamType GetType() const { return m_type; } @@ -1437,7 +1432,7 @@ inline void SAnimContext::Serialize(XmlNodeRef& xmlNode, bool bLoading) { if (sequence) { - string fullname = sequence->GetName(); + AZStd::string fullname = sequence->GetName(); xmlNode->setAttr("sequence", fullname.c_str()); } xmlNode->setAttr("dt", dt); diff --git a/Code/Legacy/CryCommon/LyShine/ILyShine.h b/Code/Legacy/CryCommon/LyShine/ILyShine.h index 07bffda0fe..7832497d8c 100644 --- a/Code/Legacy/CryCommon/LyShine/ILyShine.h +++ b/Code/Legacy/CryCommon/LyShine/ILyShine.h @@ -46,7 +46,7 @@ public: virtual AZ::EntityId CreateCanvas() = 0; //! Load a UI Canvas from in-game - virtual AZ::EntityId LoadCanvas(const string& assetIdPathname) = 0; + virtual AZ::EntityId LoadCanvas(const AZStd::string& assetIdPathname) = 0; //! Create an empty UI Canvas (for the UI editor) // @@ -54,7 +54,7 @@ public: virtual AZ::EntityId CreateCanvasInEditor(UiEntityContext* entityContext) = 0; //! Load a UI Canvas from the UI editor - virtual AZ::EntityId LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext) = 0; + virtual AZ::EntityId LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext) = 0; //! Reload a UI Canvas from xml. For use in the editor for the undo system only virtual AZ::EntityId ReloadCanvasFromXml(const AZStd::string& xmlString, UiEntityContext* entityContext) = 0; @@ -65,7 +65,7 @@ public: //! Get a loaded canvas by path name //! NOTE: this only searches canvases loaded in the game (not the editor) - virtual AZ::EntityId FindLoadedCanvasByPathName(const string& assetIdPathname) = 0; + virtual AZ::EntityId FindLoadedCanvasByPathName(const AZStd::string& assetIdPathname) = 0; //! Release a canvas from use either in-game or in editor, destroy UI Canvas if no longer used in either virtual void ReleaseCanvas(AZ::EntityId canvas, bool forEditor = false) = 0; @@ -74,10 +74,10 @@ public: virtual void ReleaseCanvasDeferred(AZ::EntityId canvas) = 0; //! Load a sprite object. - virtual ISprite* LoadSprite(const string& pathname) = 0; + virtual ISprite* LoadSprite(const AZStd::string& pathname) = 0; //! Create a sprite that references the specified render target - virtual ISprite* CreateSprite(const string& renderTargetName) = 0; + virtual ISprite* CreateSprite(const AZStd::string& renderTargetName) = 0; //! Check if a sprite's texture asset exists. The .sprite sidecar file is optional and is not checked virtual bool DoesSpriteTextureAssetExist(const AZStd::string& pathname) = 0; diff --git a/Code/Legacy/CrySystem/CmdLine.h b/Code/Legacy/CrySystem/CmdLine.h index 9ad7effebd..5e5c6466f1 100644 --- a/Code/Legacy/CrySystem/CmdLine.h +++ b/Code/Legacy/CrySystem/CmdLine.h @@ -29,13 +29,13 @@ public: virtual const ICmdLineArg* GetArg(int n) const; virtual int GetArgCount() const; virtual const ICmdLineArg* FindArg(const ECmdLineArgType ArgType, const char* name, bool caseSensitive = false) const; - virtual const char* GetCommandLine() const { return m_sCmdLine; }; + virtual const char* GetCommandLine() const { return m_sCmdLine.c_str(); }; private: - void PushCommand(const string& sCommand, const string& sParameter); - string Next(char*& str); + void PushCommand(const AZStd::string& sCommand, const AZStd::string& sParameter); + AZStd::string Next(char*& str); - string m_sCmdLine; + AZStd::string m_sCmdLine; std::vector m_args; }; diff --git a/Code/Legacy/CrySystem/CmdLineArg.h b/Code/Legacy/CrySystem/CmdLineArg.h index cc79981a72..5e3a629e7c 100644 --- a/Code/Legacy/CrySystem/CmdLineArg.h +++ b/Code/Legacy/CrySystem/CmdLineArg.h @@ -34,8 +34,8 @@ public: private: ECmdLineArgType m_type; - string m_name; - string m_value; + AZStd::string m_name; + AZStd::string m_value; }; #endif // CRYINCLUDE_CRYSYSTEM_CMDLINEARG_H diff --git a/Code/Legacy/CrySystem/ConsoleBatchFile.cpp b/Code/Legacy/CrySystem/ConsoleBatchFile.cpp index 6e36780ac0..8b25773c45 100644 --- a/Code/Legacy/CrySystem/ConsoleBatchFile.cpp +++ b/Code/Legacy/CrySystem/ConsoleBatchFile.cpp @@ -57,7 +57,7 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) Init(); } - string filename; + AZStd::string filename; if (sFilename[0] != '@') // console config files are actually by default in @root@ instead of @assets@ { @@ -78,7 +78,7 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) filename = sFilename; } - if (strlen(PathUtil::GetExt(filename)) == 0) + if (strlen(PathUtil::GetExt(filename.c_str())) == 0) { filename = PathUtil::ReplaceExtension(filename, "cfg"); } @@ -88,20 +88,20 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) { const char* szLog = "Executing console batch file (try game,config,root):"; - string filenameLog; - string sfn = PathUtil::GetFile(filename); + AZStd::string filenameLog; + AZStd::string sfn = PathUtil::GetFile(filename); - if (file.Open(filename, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) + if (file.Open(filename.c_str(), "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) { - filenameLog = string("game/") + sfn; + filenameLog = AZStd::string("game/") + sfn; } - else if (file.Open(string("config/") + sfn, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) + else if (file.Open((AZStd::string("config/") + sfn).c_str(), "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) { - filenameLog = string("game/config/") + sfn; + filenameLog = AZStd::string("game/config/") + sfn; } - else if (file.Open(string("./") + sfn, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) + else if (file.Open((AZStd::string("./") + sfn).c_str(), "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) { - filenameLog = string("./") + sfn; + filenameLog = AZStd::string("./") + sfn; } else { @@ -142,11 +142,11 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) str++; } - string strLine = s; + AZStd::string strLine = s; //trim all whitespace characters at the beginning and the end of the current line and store its size - strLine.Trim(); + AZ::StringFunc::TrimWhiteSpace(strLine, true, true); size_t strLineSize = strLine.size(); //skip comments, comments start with ";" or "--" but may have preceding whitespace characters @@ -168,7 +168,7 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) } { - m_pConsole->ExecuteString(strLine); + m_pConsole->ExecuteString(strLine.c_str()); } } // See above diff --git a/Code/Legacy/CrySystem/ConsoleHelpGen.cpp b/Code/Legacy/CrySystem/ConsoleHelpGen.cpp index 0740e3a0f7..ff86577258 100644 --- a/Code/Legacy/CrySystem/ConsoleHelpGen.cpp +++ b/Code/Legacy/CrySystem/ConsoleHelpGen.cpp @@ -17,9 +17,9 @@ // remove bad characters, toupper, not very fast -string CConsoleHelpGen::FixAnchorName(const char* szName) +AZStd::string CConsoleHelpGen::FixAnchorName(const char* szName) { - string ret; + AZStd::string ret; const char* p = szName; @@ -45,9 +45,9 @@ string CConsoleHelpGen::FixAnchorName(const char* szName) return ret; } -string CConsoleHelpGen::GetCleanPrefix(const char* p) +AZStd::string CConsoleHelpGen::GetCleanPrefix(const char* p) { - string sRet; + AZStd::string sRet; while (*p != '_' && *p != 0) { @@ -58,9 +58,9 @@ string CConsoleHelpGen::GetCleanPrefix(const char* p) } -string CConsoleHelpGen::SplitPrefixString_Part1(const char* p) +AZStd::string CConsoleHelpGen::SplitPrefixString_Part1(const char* p) { - string sRet; + AZStd::string sRet; while (*p != 10 && *p != 13 && *p != 0) { @@ -140,7 +140,7 @@ void CConsoleHelpGen::LogVersion(FILE* f) const char fext[_MAX_PATH]; _splitpath_s(s, fdrive, fdir, file, fext); - KeyValue(f, "Executable", (string(file) + fext).c_str()); + KeyValue(f, "Executable", (AZStd::string(file) + fext).c_str()); } { @@ -273,11 +273,11 @@ void CConsoleHelpGen::SingleLinePrefix(FILE* f, const char* szPrefix, const char } else if (m_eWorkMode == eWM_Confluence) { - string sPrefix; + AZStd::string sPrefix; if (*szPrefix) { - sPrefix = string(szPrefix) + "_"; + sPrefix = AZStd::string(szPrefix) + "_"; } // fprintf(f,"| %s | [%s|%s] |\n",sPrefix.c_str(),szPrefixDesc,szLink); // e.g. "" "CL_" "CC_" "I_" "T_" @@ -406,7 +406,7 @@ void CConsoleHelpGen::InsertConsoleCommands(std::setsecond; - if (_strnicmp(cmd.m_sName, szLocalPrefix, strlen(szLocalPrefix)) == 0) + if (_strnicmp(cmd.m_sName.c_str(), szLocalPrefix, strlen(szLocalPrefix)) == 0) { setCmdAndVars.insert(cmd.m_sName.c_str()); } @@ -415,7 +415,7 @@ void CConsoleHelpGen::InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const +void CConsoleHelpGen::InsertConsoleVars(std::set& setCmdAndVars, std::map mapPrefix) const { CXConsole::ConsoleVariablesMap::const_iterator itrVar, itrVarEnd = m_rParent.m_mapVariables.end(); @@ -425,11 +425,11 @@ void CConsoleHelpGen::InsertConsoleVars(std::set& bool bInsert = true; { - std::map::const_iterator it2, end = mapPrefix.end(); + std::map::const_iterator it2, end = mapPrefix.end(); for (it2 = mapPrefix.begin(); it2 != end; ++it2) { - if (it2->first != "___" && _strnicmp(var->GetName(), it2->first, it2->first.size()) == 0) + if (it2->first != "___" && _strnicmp(var->GetName(), it2->first.c_str(), it2->first.size()) == 0) { bInsert = false; break; @@ -446,7 +446,7 @@ void CConsoleHelpGen::InsertConsoleVars(std::set& -void CConsoleHelpGen::InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const +void CConsoleHelpGen::InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const { CXConsole::ConsoleCommandsMap::const_iterator itrCmd, itrCmdEnd = m_rParent.m_mapCommands.end(); @@ -456,11 +456,11 @@ void CConsoleHelpGen::InsertConsoleCommands(std::set::const_iterator it2, end = mapPrefix.end(); + std::map::const_iterator it2, end = mapPrefix.end(); for (it2 = mapPrefix.begin(); it2 != end; ++it2) { - if (it2->first != "___" && _strnicmp(cmd.m_sName, it2->first, it2->first.size()) == 0) + if (it2->first != "___" && _strnicmp(cmd.m_sName.c_str(), it2->first.c_str(), it2->first.size()) == 0) { bInsert = false; break; @@ -480,7 +480,7 @@ void CConsoleHelpGen::CreateSingleEntryFile(const char* szName) const assert(m_eWorkMode == eWM_Confluence); // only needed for confluence FILE* f3 = nullptr; - azfopen(&f3, (string(GetFolderName()) + GetFileExtension() + "/" + FixAnchorName(szName)).c_str(), "w"); + azfopen(&f3, (AZStd::string(GetFolderName()) + GetFileExtension() + "/" + FixAnchorName(szName)).c_str(), "w"); if (!f3) { @@ -582,7 +582,7 @@ void CConsoleHelpGen::IncludeSingleEntry(FILE* f, const char* szName) const { fprintf(f, "

\n");
 
-            string sHelp = szHelp;
+            AZStd::string sHelp = szHelp;
 
             // currently not required as the {noformat} is used
             //          sHelp.replace("[","\\[");       sHelp.replace("]","\\]");
@@ -604,7 +604,7 @@ void CConsoleHelpGen::IncludeSingleEntry(FILE* f, const char* szName) const
 
 void CConsoleHelpGen::Work()
 {
-    //  string sEngineFolder = string("@user@/")+GetFolderName();
+    //  AZStd::string sEngineFolder = AZStd::string("@user@/")+GetFolderName();
     //  gEnv->pCryPak->RemoveDir(sEngineFolder.c_str());            // todo: check if that works
     //  gEnv->pFileIO->CreatePath(sEngineFolder.c_str());
 
@@ -653,7 +653,7 @@ void CConsoleHelpGen::CreateMainPages()
 {
     gEnv->pFileIO->CreatePath(GetFolderName());
 
-    std::map mapPrefix;
+    std::map mapPrefix;
 
     // order here doesn't matter, after the name some help can be added (after the first return)
     mapPrefix[     "AI_"] = "Artificial Intelligence";
@@ -701,7 +701,7 @@ void CConsoleHelpGen::CreateMainPages()
     mapPrefix[     "___"] = "Remaining";            // key defined to get it sorted in the end
 
     FILE* f1 = nullptr;
-    azfopen(&f1, (string(GetFolderName()) + "/index" + GetFileExtension()).c_str(), "w");
+    azfopen(&f1, (AZStd::string(GetFolderName()) + "/index" + GetFileExtension()).c_str(), "w");
     if (!f1)
     {
         return;
@@ -729,17 +729,17 @@ void CConsoleHelpGen::CreateMainPages()
 
     // show all registered Prefix with one line
     {
-        std::map::const_iterator it, end = mapPrefix.end();
+        std::map::const_iterator it, end = mapPrefix.end();
 
         StartH3(f1, "Registered Prefixes");
 
         for (it = mapPrefix.begin(); it != end; ++it)
         {
             const char* szLocalPrefix = it->first.c_str();      // can be 0 for remaining ones
-            string sCleanPrefix = GetCleanPrefix(szLocalPrefix);
-            string sPrefixName = SplitPrefixString_Part1(it->second);
+            AZStd::string sCleanPrefix = GetCleanPrefix(szLocalPrefix);
+            AZStd::string sPrefixName = SplitPrefixString_Part1(it->second);
 
-            SingleLinePrefix(f1, sCleanPrefix.c_str(), sPrefixName.c_str(), (string("CONSOLEPREFIX") + FixAnchorName(sCleanPrefix.c_str()) + GetFileExtension()).c_str());
+            SingleLinePrefix(f1, sCleanPrefix.c_str(), sPrefixName.c_str(), (AZStd::string("CONSOLEPREFIX") + FixAnchorName(sCleanPrefix.c_str()) + GetFileExtension()).c_str());
             //          fprintf(f1,"   * [[CONSOLEPREFIX%s][%s_ %s]]\n",FixAnchorName(sCleanPrefix.c_str()).c_str(),sCleanPrefix.c_str(),sPrefixName.c_str());
         }
 
@@ -750,15 +750,15 @@ void CConsoleHelpGen::CreateMainPages()
 
 
     {
-        std::map::const_iterator it, it2, end = mapPrefix.end();
+        std::map::const_iterator it, it2, end = mapPrefix.end();
 
         StartH3(f1, "Console Commands and Variables Sorted by Prefix");
 
         for (it = mapPrefix.begin(); it != end; ++it)
         {
             const char* szLocalPrefix = it->first.c_str();      // can be 0 for remaining ones
-            string sCleanPrefix = GetCleanPrefix(szLocalPrefix);
-            string sPrefixName = SplitPrefixString_Part1(it->second);
+            AZStd::string sCleanPrefix = GetCleanPrefix(szLocalPrefix);
+            AZStd::string sPrefixName = SplitPrefixString_Part1(it->second);
 
             std::set setCmdAndVars;      // to get console variables and commands sorted together
 
@@ -777,11 +777,11 @@ void CConsoleHelpGen::CreateMainPages()
 
             // -------------------------------
 
-            string sSubName = string("CONSOLEPREFIX") + sCleanPrefix;
+            AZStd::string sSubName = AZStd::string("CONSOLEPREFIX") + sCleanPrefix;
 
             StartPrefix(f1, sCleanPrefix.c_str(), sPrefixName.c_str(), (sSubName + GetFileExtension()).c_str());
 
-            string sFileOut = string(GetFolderName()) + "/" + sSubName + GetFileExtension();
+            AZStd::string sFileOut = AZStd::string(GetFolderName()) + "/" + sSubName + GetFileExtension();
             FILE* f2 = nullptr;
             azfopen(&f2, sFileOut.c_str(), "w");
             if (!f2)
@@ -792,7 +792,7 @@ void CConsoleHelpGen::CreateMainPages()
 
             // headline
             {
-                string sHeadline;
+                AZStd::string sHeadline;
 
                 if (sCleanPrefix.empty())
                 {
@@ -800,7 +800,7 @@ void CConsoleHelpGen::CreateMainPages()
                 }
                 else
                 {
-                    sHeadline = string("Console Commands and Variables with Prefix ") + sCleanPrefix + "_";
+                    sHeadline = AZStd::string("Console Commands and Variables with Prefix ") + sCleanPrefix + "_";
                 }
 
                 StartH1(f2, sHeadline.c_str());
@@ -821,7 +821,7 @@ void CConsoleHelpGen::CreateMainPages()
                 for (itI = setCmdAndVars.begin(); itI != endI; ++itI)
                 {
                     SingleLineEntry_InGlobal(f1, *itI, (sSubName + GetFileExtension() + "#Anchor" + FixAnchorName(*itI)).c_str());
-                    SingleLineEntry_InGroup(f2, *itI, (string("#Anchor") + FixAnchorName(*itI)).c_str());
+                    SingleLineEntry_InGroup(f2, *itI, (AZStd::string("#Anchor") + FixAnchorName(*itI)).c_str());
                 }
 
                 EndH3(f2);
@@ -842,7 +842,7 @@ void CConsoleHelpGen::CreateMainPages()
                         }
                         bFirst = false;
 
-                        Anchor(f2, (string("Anchor") + FixAnchorName(*itI)).c_str());      // anchor
+                        Anchor(f2, (AZStd::string("Anchor") + FixAnchorName(*itI)).c_str());      // anchor
 
                         IncludeSingleEntry(f2, *itI);
                     }
diff --git a/Code/Legacy/CrySystem/ConsoleHelpGen.h b/Code/Legacy/CrySystem/ConsoleHelpGen.h
index 9ff797ca07..576232fe7a 100644
--- a/Code/Legacy/CrySystem/ConsoleHelpGen.h
+++ b/Code/Legacy/CrySystem/ConsoleHelpGen.h
@@ -59,19 +59,19 @@ private: // --------------------------------------------------------
     // insert if the name starts with the with prefix
     void InsertConsoleCommands(std::set& setCmdAndVars, const char* szPrefix) const;
     // insert if the name does not start with any of the prefix in the map
-    void InsertConsoleVars(std::set& setCmdAndVars, std::map mapPrefix) const;
+    void InsertConsoleVars(std::set& setCmdAndVars, std::map mapPrefix) const;
     // insert if the name does not start with any of the prefix in the map
-    void InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const;
+    void InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const;
 
     // a single file for the entry is generate
     void CreateSingleEntryFile(const char* szName) const;
 
     void IncludeSingleEntry(FILE* f, const char* szName) const;
 
-    static string FixAnchorName(const char* szName);
-    static string GetCleanPrefix(const char* p);
+    static AZStd::string FixAnchorName(const char* szName);
+    static AZStd::string GetCleanPrefix(const char* p);
     // split before "|" (to get the prefix itself)
-    static string SplitPrefixString_Part1(const char* p);
+    static AZStd::string SplitPrefixString_Part1(const char* p);
     // split string after "|" (to get the optional help)
     static const char* SplitPrefixString_Part2(const char* p);
 
diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp
index 1914e82515..c5d932429c 100644
--- a/Code/Legacy/CrySystem/DebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/DebugCallStack.cpp
@@ -348,7 +348,7 @@ void DebugCallStack::ReportBug(const char* szErrorMessage)
     m_szBugMessage = NULL;
 }
 
-void DebugCallStack::dumpCallStack(std::vector& funcs)
+void DebugCallStack::dumpCallStack(std::vector& funcs)
 {
     WriteLineToLog("=============================================================================");
     int len = (int)funcs.size();
@@ -364,7 +364,7 @@ void DebugCallStack::dumpCallStack(std::vector& funcs)
 //////////////////////////////////////////////////////////////////////////
 void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
 {
-    string path("");
+    AZStd::string path("");
     if ((gEnv) && (gEnv->pFileIO))
     {
         const char* logAlias = gEnv->pFileIO->GetAlias("@log@");
@@ -379,12 +379,12 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         }
     }
 
-    string fileName = path;
+    AZStd::string fileName = path;
     fileName += "error.log";
 
     struct stat fileInfo;
-    string timeStamp;
-    string backupPath;
+    AZStd::string timeStamp;
+    AZStd::string backupPath;
     if (gEnv->IsDedicated())
     {
         backupPath = PathUtil::ToUnixPath(PathUtil::AddSlash(path + "DumpBackups"));
@@ -399,7 +399,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
             strftime(tempBuffer, sizeof(tempBuffer), "%d %b %Y (%H %M %S)", &creationTime);
             timeStamp = tempBuffer;
 
-            string backupFileName = backupPath + timeStamp + " error.log";
+            AZStd::string backupFileName = backupPath + timeStamp + " error.log";
             CopyFile(fileName.c_str(), backupFileName.c_str(), true);
         }
     }
@@ -414,8 +414,8 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
     char versionbuf[1024];
     azstrcpy(versionbuf, AZ_ARRAY_SIZE(versionbuf), "");
     PutVersion(versionbuf, AZ_ARRAY_SIZE(versionbuf));
-    cry_strcat(errorString, versionbuf);
-    cry_strcat(errorString, "\n");
+    azstrcat(errorString, versionbuf);
+    azstrcat(errorString, "\n");
 
     char excCode[MAX_WARNING_LENGTH];
     char excAddr[80];
@@ -481,9 +481,9 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         excCode, excAddr, m_excModule, excName, desc);
 
 
-    cry_strcat(errs, "\nCall Stack Trace:\n");
+    azstrcat(errs, "\nCall Stack Trace:\n");
 
-    std::vector funcs;
+    std::vector funcs;
     {
         AZ::Debug::StackFrame frames[25];
         AZ::Debug::SymbolStorage::StackLine lines[AZ_ARRAY_SIZE(frames)];
@@ -504,15 +504,15 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         {
             char temp[s_iCallStackSize];
             sprintf_s(temp, "%2zd) %s", funcs.size() - i, (const char*)funcs[i].c_str());
-            cry_strcat(str, temp);
-            cry_strcat(str, "\r\n");
-            cry_strcat(errs, temp);
-            cry_strcat(errs, "\n");
+            azstrcat(str, temp);
+            azstrcat(str, "\r\n");
+            azstrcat(errs, temp);
+            azstrcat(errs, "\n");
         }
         azstrcpy(m_excCallstack, str);
     }
 
-    cry_strcat(errorString, errs);
+    azstrcat(errorString, errs);
 
     if (f)
     {
@@ -593,7 +593,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
                     timeStamp = tempBuffer;
                 }
 
-                string backupFileName = backupPath + timeStamp + " error.dmp";
+                AZStd::string backupFileName = backupPath + timeStamp + " error.dmp";
                 CopyFile(fileName.c_str(), backupFileName.c_str(), true);
             }
 
@@ -818,7 +818,7 @@ void DebugCallStack::ResetFPU(EXCEPTION_POINTERS* pex)
     }
 }
 
-string DebugCallStack::GetModuleNameForAddr(void* addr)
+AZStd::string DebugCallStack::GetModuleNameForAddr(void* addr)
 {
     if (m_modules.empty())
     {
@@ -844,7 +844,7 @@ string DebugCallStack::GetModuleNameForAddr(void* addr)
     return m_modules.rbegin()->second;
 }
 
-void DebugCallStack::GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line)
+void DebugCallStack::GetProcNameForAddr(void* addr, AZStd::string& procName, void*& baseAddr, AZStd::string& filename, int& line)
 {
     AZ::Debug::SymbolStorage::StackLine func, file, module;
     AZ::Debug::SymbolStorage::FindFunctionFromIP(addr, &func, &file, &module, line, baseAddr);
@@ -852,7 +852,7 @@ void DebugCallStack::GetProcNameForAddr(void* addr, string& procName, void*& bas
     filename = file;
 }
 
-string DebugCallStack::GetCurrentFilename()
+AZStd::string DebugCallStack::GetCurrentFilename()
 {
     char fullpath[MAX_PATH_LENGTH + 1];
     GetModuleFileName(NULL, fullpath, MAX_PATH_LENGTH);
diff --git a/Code/Legacy/CrySystem/DebugCallStack.h b/Code/Legacy/CrySystem/DebugCallStack.h
index f0c708a2b5..28f587011e 100644
--- a/Code/Legacy/CrySystem/DebugCallStack.h
+++ b/Code/Legacy/CrySystem/DebugCallStack.h
@@ -35,20 +35,20 @@ public:
 
     ISystem* GetSystem() { return m_pSystem; };
 
-    virtual string GetModuleNameForAddr(void* addr);
-    virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line);
-    virtual string GetCurrentFilename();
+    virtual AZStd::string GetModuleNameForAddr(void* addr);
+    virtual void GetProcNameForAddr(void* addr, AZStd::string& procName, void*& baseAddr, AZStd::string& filename, int& line);
+    virtual AZStd::string GetCurrentFilename();
 
     void installErrorHandler(ISystem* pSystem);
     virtual int handleException(EXCEPTION_POINTERS* exception_pointer);
 
     virtual void ReportBug(const char*);
 
-    void dumpCallStack(std::vector& functions);
+    void dumpCallStack(std::vector& functions);
 
     void SetUserDialogEnable(const bool bUserDialogEnable);
 
-    typedef std::map TModules;
+    typedef std::map TModules;
 protected:
     static void RemoveOldFiles();
     static void RemoveFile(const char* szFileName);
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp
index 4ca481be88..ff43f6e56f 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp
@@ -237,7 +237,7 @@ void IDebugCallStack::WriteLineToLog(const char* format, ...)
     char        szBuffer[MAX_WARNING_LENGTH];
     va_start(ArgList, format);
     vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, format, ArgList);
-    cry_strcat(szBuffer, "\n");
+    azstrcat(szBuffer, "\n");
     szBuffer[sizeof(szBuffer) - 1] = '\0';
     va_end(ArgList);
 
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.h b/Code/Legacy/CrySystem/IDebugCallStack.h
index c05d0827b0..a2c1d3f5e2 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.h
+++ b/Code/Legacy/CrySystem/IDebugCallStack.h
@@ -33,23 +33,23 @@ public:
     virtual int handleException([[maybe_unused]] EXCEPTION_POINTERS* exception_pointer){return 0; }
 
     // returns the module name of a given address
-    virtual string GetModuleNameForAddr([[maybe_unused]] void* addr) { return "[unknown]"; }
+    virtual AZStd::string GetModuleNameForAddr([[maybe_unused]] void* addr) { return "[unknown]"; }
 
     // returns the function name of a given address together with source file and line number (if available) of a given address
-    virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line)
+    virtual void GetProcNameForAddr(void* addr, AZStd::string& procName, void*& baseAddr, AZStd::string& filename, int& line)
     {
         filename = "[unknown]";
         line = 0;
         baseAddr = addr;
 #if defined(PLATFORM_64BIT)
-        procName.Format("[%016llX]", addr);
+        procName = AZStd::string::format("[%016llX]", addr);
 #else
-        procName.Format("[%08X]", addr);
+        procName = AZStd::string::format("[%08X]", addr);
 #endif
     }
 
     // returns current filename
-    virtual string GetCurrentFilename()  { return "[unknown]"; }
+    virtual AZStd::string GetCurrentFilename()  { return "[unknown]"; }
 
     //! Dumps Current Call Stack to log.
     virtual void LogCallstack();
diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
index 83db5e4a29..3e6432a721 100644
--- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
+++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
@@ -480,7 +480,7 @@ CLevelInfo* CLevelSystem::GetLevelInfoInternal(const AZStd::string& levelName)
     for (AZStd::vector::iterator it = m_levelInfos.begin(); it != m_levelInfos.end(); ++it)
     {
         {
-            if (!azstricmp(PathUtil::GetFileName(it->GetName()), levelName.c_str()))
+            if (!azstricmp(PathUtil::GetFileName(it->GetName()).c_str(), levelName.c_str()))
             {
                 return &(*it);
             }
diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
index fe0fd9cb22..e3ccb22f88 100644
--- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp
+++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
@@ -20,7 +20,6 @@
 #include "System.h" // to access InitLocalization()
 #include 
 #include 
-#include 
 #include 
 #include 
 
@@ -146,9 +145,9 @@ static void ReloadDialogData([[maybe_unused]] IConsoleCmdArgs* pArgs)
 #if !defined(_RELEASE)
 static void TestFormatMessage ([[maybe_unused]] IConsoleCmdArgs* pArgs)
 {
-    string fmt1 ("abc %1 def % gh%2i %");
-    string fmt2 ("abc %[action:abc] %2 def % gh%1i %1");
-    string out1, out2;
+    AZStd::string fmt1 ("abc %1 def % gh%2i %");
+    AZStd::string fmt2 ("abc %[action:abc] %2 def % gh%1i %1");
+    AZStd::string out1, out2;
     LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::FormatStringMessage, out1, fmt1, "first", "second", "third", nullptr);
     CryLogAlways("%s", out1.c_str());
     LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::FormatStringMessage, out2, fmt2, "second", nullptr, nullptr, nullptr);
@@ -206,18 +205,18 @@ CLocalizedStringsManager::CLocalizedStringsManager(ISystem* pSystem)
 
     // Populate available languages by scanning the localization directory for paks
     // Default to US English if language is not supported
-    string sPath;
-    const string sLocalizationFolder(PathUtil::GetLocalizationFolder());
+    AZStd::string sPath;
+    const AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
     ILocalizationManager::TLocalizationBitfield availableLanguages = 0;
     
     AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
     // test language name against supported languages
     for (int i = 0; i < ILocalizationManager::ePILID_MAX_OR_INVALID; i++)
     {
-        string sCurrentLanguage = LangNameFromPILID((ILocalizationManager::EPlatformIndependentLanguageID)i);  
+        AZStd::string sCurrentLanguage = LangNameFromPILID((ILocalizationManager::EPlatformIndependentLanguageID)i);
         sPath = sLocalizationFolder.c_str() + sCurrentLanguage;
-        sPath.MakeLower();
-        if (fileIO && fileIO->IsDirectory(sPath))
+        AZStd::to_lower(sPath.begin(), sPath.end());
+        if (fileIO && fileIO->IsDirectory(sPath.c_str()))
         {
             availableLanguages |= ILocalizationManager::LocalizationBitfieldFromPILID((ILocalizationManager::EPlatformIndependentLanguageID)i);
             if (m_cvarLocalizationDebug >= 2)
@@ -366,7 +365,7 @@ bool CLocalizedStringsManager::SetLanguage(const char* sLanguage)
     // Check if already language loaded.
     for (uint32 i = 0; i < m_languages.size(); i++)
     {
-        if (_stricmp(sLanguage, m_languages[i]->sLanguage) == 0)
+        if (_stricmp(sLanguage, m_languages[i]->sLanguage.c_str()) == 0)
         {
             InternalSetCurrentLanguage(m_languages[i]);
             return true;
@@ -441,9 +440,9 @@ void CLocalizedStringsManager::AddControl([[maybe_unused]] int nKey)
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CLocalizedStringsManager::ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex)
+void CLocalizedStringsManager::ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex)
 {
-    string sCellContent;
+    AZStd::string sCellContent;
 
     for (;; )
     {
@@ -466,7 +465,7 @@ void CLocalizedStringsManager::ParseFirstLine(IXmlTableReader* pXmlTableReader,
         }
 
         sCellContent.assign(pContent, contentSize);
-        sCellContent.MakeLower();
+        AZStd::to_lower(sCellContent.begin(), sCellContent.end());
 
         for (int i = 0; i < sizeof(sLocalizedColumnNames) / sizeof(sLocalizedColumnNames[0]); ++i)
         {
@@ -530,8 +529,8 @@ static void CopyLowercase(char* dst, size_t dstSize, const char* src, size_t src
 //////////////////////////////////////////////////////////////////////////
 static void ReplaceEndOfLine(AZStd::fixed_string& s)
 {
-    const string oldSubstr("\\n");
-    const string newSubstr(" \n");
+    const AZStd::string oldSubstr("\\n");
+    const AZStd::string newSubstr(" \n");
     size_t pos = 0;
     for (;; )
     {
@@ -565,7 +564,7 @@ void CLocalizedStringsManager::OnSystemEvent(
 
             for (TStringVec::iterator it = m_tagLoadRequests.begin(); it != m_tagLoadRequests.end(); ++it)
             {
-                LoadLocalizationDataByTag(*it);
+                LoadLocalizationDataByTag(it->c_str());
             }
         }
 
@@ -577,7 +576,7 @@ void CLocalizedStringsManager::OnSystemEvent(
         // Load all tags after the Editor has finished initialization.
         for (TTagFileNames::iterator it = m_tagFileNames.begin(); it != m_tagFileNames.end(); ++it)
         {
-            LoadLocalizationDataByTag(it->first);
+            LoadLocalizationDataByTag(it->first.c_str());
         }
 
         break;
@@ -600,7 +599,7 @@ bool CLocalizedStringsManager::InitLocalizationData(
     for (int i = 0; i < root->getChildCount(); i++)
     {
         XmlNodeRef typeNode = root->getChild(i);
-        string sType = typeNode->getTag();
+        AZStd::string sType = typeNode->getTag();
 
         // tags should be unique
         if (m_tagFileNames.find(sType) != m_tagFileNames.end())
@@ -678,9 +677,9 @@ bool CLocalizedStringsManager::LoadLocalizationDataByTag(
     for (TStringVec::iterator it2 = vEntries.begin(); it2 != vEntries.end(); ++it2)
     {
         //Only load files of the correct type for the configured format
-        if ((m_cvarLocalizationFormat == 0 && strstr(*it2, ".xml")) || (m_cvarLocalizationFormat == 1 && strstr(*it2, ".agsxml")))
+        if ((m_cvarLocalizationFormat == 0 && strstr(it2->c_str(), ".xml")) || (m_cvarLocalizationFormat == 1 && strstr(it2->c_str(), ".agsxml")))
         {
-            bResult &= (this->*loadFunction)(*it2, it->second.id, bReload);
+            bResult &= (this->*loadFunction)(it2->c_str(), it->second.id, bReload);
         }
     }
 
@@ -824,7 +823,7 @@ bool CLocalizedStringsManager::LoadAllLocalizationData(bool bReload)
 {
     for (TTagFileNames::iterator it = m_tagFileNames.begin(); it != m_tagFileNames.end(); ++it)
     {
-        if(!LoadLocalizationDataByTag(it->first, bReload))
+        if(!LoadLocalizationDataByTag(it->first.c_str(), bReload))
             return false;
     }
     return true;
@@ -837,6 +836,37 @@ bool CLocalizedStringsManager::LoadExcelXmlSpreadsheet(const char* sFileName, bo
     return (this->*loadFunction)(sFileName, 0, bReload);
 }
 
+enum class YesNoType
+{
+    Yes,
+    No,
+    Invalid
+};
+
+// parse the yes/no string
+/*!
+\param szString any of the following strings: yes, enable, true, 1, no, disable, false, 0
+\return YesNoType::Yes if szString is yes/enable/true/1, YesNoType::No if szString is no, disable, false, 0 and YesNoType::Invalid if the string is not one of the expected values.
+*/
+inline YesNoType ToYesNoType(const char* szString)
+{
+    if (!_stricmp(szString, "yes")
+        || !_stricmp(szString, "enable")
+        || !_stricmp(szString, "true")
+        || !_stricmp(szString, "1"))
+    {
+        return YesNoType::Yes;
+    }
+    if (!_stricmp(szString, "no")
+        || !_stricmp(szString, "disable")
+        || !_stricmp(szString, "false")
+        || !_stricmp(szString, "0"))
+    {
+        return YesNoType::No;
+    }
+    return YesNoType::Invalid;
+}
+
 //////////////////////////////////////////////////////////////////////
 // Loads a string-table from a Excel XML Spreadsheet file.
 bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName, uint8 nTagID, bool bReload)
@@ -850,7 +880,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
     //check if this table has already been loaded
     if (!bReload)
     {
-        if (m_loadedTables.find(CONST_TEMP_STRING(sFileName)) != m_loadedTables.end())
+        if (m_loadedTables.find(AZStd::string(sFileName)) != m_loadedTables.end())
         {
             return (true);
         }
@@ -866,12 +896,12 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
     }
 
     XmlNodeRef root;
-    string sPath;
+    AZStd::string sPath;
     {
-        const string sLocalizationFolder(PathUtil::GetLocalizationRoot());
-        const string& languageFolder = m_pLanguage->sLanguage;
+        const AZStd::string sLocalizationFolder(PathUtil::GetLocalizationRoot());
+        const AZStd::string& languageFolder = m_pLanguage->sLanguage;
         sPath = sLocalizationFolder.c_str() + languageFolder + PathUtil::GetSlash() + sFileName;
-        root = m_pSystem->LoadXmlFromFile(sPath);
+        root = m_pSystem->LoadXmlFromFile(sPath.c_str());
         if (!root)
         {
             CryLog("Loading Localization File %s failed!", sPath.c_str());
@@ -948,10 +978,10 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
     memset(nCellIndexToType, 0, sizeof(nCellIndexToType));
 
     // SoundMood Index
-    std::map SoundMoodIndex;
+    std::map SoundMoodIndex;
 
     // EventParameter Index
-    std::map EventParameterIndex;
+    std::map EventParameterIndex;
 
     bool bFirstRow = true;
 
@@ -1083,7 +1113,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
                 break;
             case ELOCALIZED_COLUMN_USE_SUBTITLE:
                 sTmp.assign(cell.ptr, cell.count);
-                bUseSubtitle = CryStringUtils::ToYesNoType(sTmp.c_str()) == CryStringUtils::YesNoType::No ? false : true; // favor yes (yes and invalid -> yes)
+                bUseSubtitle = ToYesNoType(sTmp.c_str()) == YesNoType::No ? false : true; // favor yes (yes and invalid -> yes)
                 break;
             case ELOCALIZED_COLUMN_VOLUME:
                 sTmp.assign(cell.ptr, cell.count);
@@ -1121,7 +1151,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
                 {
                     bIsIntercepted = true;
                 }
-                bIsDirectRadio = bIsIntercepted || (CryStringUtils::ToYesNoType(sTmp.c_str()) == CryStringUtils::YesNoType::Yes ? true : false); // favor no (no and invalid -> no)
+                bIsDirectRadio = bIsIntercepted || (ToYesNoType(sTmp.c_str()) == YesNoType::Yes ? true : false); // favor no (no and invalid -> no)
                 ++nItems;
                 break;
             // legacy names
@@ -1358,7 +1388,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
             }
             else
             {
-                pEntry->TranslatedText.psUtf8Uncompressed = new string(sTmp.c_str(), sTmp.c_str() + sTmp.length());
+                pEntry->TranslatedText.psUtf8Uncompressed = new AZStd::string(sTmp.c_str(), sTmp.c_str() + sTmp.length());
             }
         }
 
@@ -1367,7 +1397,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
         // the CryString makes sure, that only the ref-count is increment on assignment
         if (*szLowerCaseEvent)
         {
-            PrototypeSoundEvents::iterator it = m_prototypeEvents.find(CONST_TEMP_STRING(szLowerCaseEvent));
+            PrototypeSoundEvents::iterator it = m_prototypeEvents.find(AZStd::string(szLowerCaseEvent));
             if (it != m_prototypeEvents.end())
             {
                 pEntry->sPrototypeSoundEvent = *it;
@@ -1384,8 +1414,8 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
         {
             sTmp.assign(sWho.ptr, sWho.count);
             ReplaceEndOfLine(sTmp);
-            sTmp.replace(" ", "_");
-            string tmp;
+            AZStd::replace(sTmp.begin(), sTmp.end(), ' ', '_');
+            AZStd::string tmp;
             {
                 tmp = sTmp.c_str();
             }
@@ -1531,19 +1561,19 @@ bool CLocalizedStringsManager::DoLoadAGSXmlDocument(const char* sFileName, uint8
     }
     if (!bReload)
     {
-        if (m_loadedTables.find(CONST_TEMP_STRING(sFileName)) != m_loadedTables.end())
+        if (m_loadedTables.find(AZStd::string(sFileName)) != m_loadedTables.end())
         {
             return true;
         }
     }
     ListAndClearProblemLabels();
     XmlNodeRef root;
-    string sPath;
+    AZStd::string sPath;
     {
-        const string sLocalizationFolder(PathUtil::GetLocalizationRoot());
-        const string& languageFolder = m_pLanguage->sLanguage;
+        const AZStd::string sLocalizationFolder(PathUtil::GetLocalizationRoot());
+        const AZStd::string& languageFolder = m_pLanguage->sLanguage;
         sPath = sLocalizationFolder.c_str() + languageFolder + PathUtil::GetSlash() + sFileName;
-        root = m_pSystem->LoadXmlFromFile(sPath);
+        root = m_pSystem->LoadXmlFromFile(sPath.c_str());
         if (!root)
         {
             AZ_TracePrintf(LOC_WINDOW, "Loading Localization File %s failed!", sPath.c_str());
@@ -1654,7 +1684,7 @@ bool CLocalizedStringsManager::DoLoadAGSXmlDocument(const char* sFileName, uint8
             }
             else
             {
-                pEntry->TranslatedText.psUtf8Uncompressed = new string(textString, textString + textLength);
+                pEntry->TranslatedText.psUtf8Uncompressed = new AZStd::string(textString, textString + textLength);
             }
         }
         {
@@ -1714,7 +1744,7 @@ void CLocalizedStringsManager::ReloadData()
     FreeLocalizationData();
     for (tmapFilenames::iterator it = temp.begin(); it != temp.end(); it++)
     {
-        (this->*loadFunction)((*it).first, (*it).second.nTagID, true);
+        (this->*loadFunction)((*it).first.c_str(), (*it).second.nTagID, true);
     }
 }
 
@@ -1732,19 +1762,19 @@ void CLocalizedStringsManager::AddLocalizedString(SLanguage* pLanguage, SLocaliz
 }
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish)
+bool CLocalizedStringsManager::LocalizeString_ch(const char* sString, AZStd::string& outLocalizedString, bool bEnglish)
 {
     return LocalizeStringInternal(sString, strlen(sString), outLocalizedString, bEnglish);
 }
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish)
+bool CLocalizedStringsManager::LocalizeString_s(const AZStd::string& sString, AZStd::string& outLocalizedString, bool bEnglish)
 {
     return LocalizeStringInternal(sString.c_str(), sString.length(), outLocalizedString, bEnglish);
 }
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t len, string& outLocalizedString, bool bEnglish)
+bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t len, AZStd::string& outLocalizedString, bool bEnglish)
 {
     assert (m_pLanguage);
     if (m_pLanguage == 0)
@@ -1755,7 +1785,7 @@ bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t l
     }
 
     // note: we don't write directly to outLocalizedString, in case it aliases pStr
-    string out;
+    AZStd::string out;
 
     // scan the string
     const char* pPos = pStr;
@@ -1783,8 +1813,8 @@ bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t l
         }
 
         // localize token
-        string token(pLabel, pLabelEnd);
-        string sLocalizedToken;
+        AZStd::string token(pLabel, pLabelEnd);
+        AZStd::string sLocalizedToken;
         if (bEnglish)
         {
             GetEnglishString(token.c_str(), sLocalizedToken);
@@ -1803,7 +1833,7 @@ bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t l
 
 void CLocalizedStringsManager::LocalizeAndSubstituteInternal(AZStd::string& locString, const AZStd::vector& keys, const AZStd::vector& values)
 {
-    string outString;
+    AZStd::string outString;
     LocalizeString_ch(locString.c_str(), outString);
     locString = outString .c_str();
     if (values.size() != keys.size())
@@ -1866,7 +1896,7 @@ static void LogDecompTimer(__int64 nTotalTicks, __int64 nDecompTicks, __int64 nA
 }
 #endif
 
-string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const SLanguage* pLanguage) const
+AZStd::string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const SLanguage* pLanguage) const
 {
     FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled);
     if ((flags & IS_COMPRESSED) != 0)
@@ -1876,7 +1906,7 @@ string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const
         nTotalTicks = CryGetTicks();
 #endif  //LOG_DECOMP_TIMES
 
-        string outputString;
+        AZStd::string outputString;
         if (TranslatedText.szCompressed != NULL)
         {
             uint8 decompressionBuffer[COMPRESSION_FIXED_BUFFER_LENGTH];
@@ -1923,7 +1953,7 @@ string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const
         }
         else
         {
-            string emptyOutputString;
+            AZStd::string emptyOutputString;
             return emptyOutputString;
         }
     }
@@ -1949,7 +1979,7 @@ void CLocalizedStringsManager::ListAndClearProblemLabels()
         CryLog ("These labels caused localization problems:");
         INDENT_LOG_DURING_SCOPE();
 
-        for (std::map::iterator iter = m_warnedAboutLabels.begin(); iter != m_warnedAboutLabels.end(); iter++)
+        for (std::map::iterator iter = m_warnedAboutLabels.begin(); iter != m_warnedAboutLabels.end(); iter++)
         {
             CryLog ("%s", iter->first.c_str());
         }
@@ -1961,7 +1991,7 @@ void CLocalizedStringsManager::ListAndClearProblemLabels()
 #endif
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, string& outLocalString, bool bEnglish)
+bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, AZStd::string& outLocalString, bool bEnglish)
 {
     assert(sLabel);
     if (!m_pLanguage || !sLabel)
@@ -1979,8 +2009,7 @@ bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, string& outLoca
 
             if (entry != NULL)
             {
-                
-                string translatedText = entry->GetTranslatedText(m_pLanguage);
+                AZStd::string translatedText = entry->GetTranslatedText(m_pLanguage);
                 if ((bEnglish || translatedText.empty()) && entry->pEditorExtension != NULL)
                 {
                     //assert(!"No Localization Text available!");
@@ -2011,7 +2040,7 @@ bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, string& outLoca
 
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::GetEnglishString(const char* sKey, string& sLocalizedString)
+bool CLocalizedStringsManager::GetEnglishString(const char* sKey, AZStd::string& sLocalizedString)
 {
     assert(sKey);
     if (!m_pLanguage || !sKey)
@@ -2086,7 +2115,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByKey(const char* sKey, SLocalize
         const SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL);
         if (entry != NULL)
         {
-            outGameInfo.szCharacterName = entry->sCharacterName;
+            outGameInfo.szCharacterName = entry->sCharacterName.c_str();
             outGameInfo.sUtf8TranslatedText = entry->GetTranslatedText(m_pLanguage);
 
             outGameInfo.bUseSubtitle = (entry->flags & SLocalizedStringEntry::USE_SUBTITLE);
@@ -2119,7 +2148,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByKey(const char* sKey, SLocalize
         {
             bResult = true;
 
-            pOutSoundInfo->szCharacterName = pEntry->sCharacterName;
+            pOutSoundInfo->szCharacterName = pEntry->sCharacterName.c_str();
             pOutSoundInfo->sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage);
 
             //pOutSoundInfo->sOriginalActorLine = pEntry->sOriginalActorLine.c_str();
@@ -2213,7 +2242,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByIndex(int nIndex, SLocalizedInf
     }
     const SLocalizedStringEntry* pEntry = entryVec[nIndex];
 
-    outGameInfo.szCharacterName = pEntry->sCharacterName;
+    outGameInfo.szCharacterName = pEntry->sCharacterName.c_str();
     outGameInfo.sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage);
 
     outGameInfo.bUseSubtitle = (pEntry->flags & SLocalizedStringEntry::USE_SUBTITLE);
@@ -2233,18 +2262,18 @@ bool CLocalizedStringsManager::GetLocalizedInfoByIndex(int nIndex, SLocalizedInf
         return false;
     }
     const SLocalizedStringEntry* pEntry = entryVec[nIndex];
-    outEditorInfo.szCharacterName = pEntry->sCharacterName;
+    outEditorInfo.szCharacterName = pEntry->sCharacterName.c_str();
     outEditorInfo.sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage);
 
     assert(pEntry->pEditorExtension != NULL);
 
-    outEditorInfo.sKey = pEntry->pEditorExtension->sKey;
+    outEditorInfo.sKey = pEntry->pEditorExtension->sKey.c_str();
 
-    outEditorInfo.sOriginalActorLine = pEntry->pEditorExtension->sOriginalActorLine;
-    outEditorInfo.sUtf8TranslatedActorLine = pEntry->pEditorExtension->sUtf8TranslatedActorLine;
+    outEditorInfo.sOriginalActorLine = pEntry->pEditorExtension->sOriginalActorLine.c_str();
+    outEditorInfo.sUtf8TranslatedActorLine = pEntry->pEditorExtension->sUtf8TranslatedActorLine.c_str();
 
     //outEditorInfo.sOriginalText = pEntry->sOriginalText;
-    outEditorInfo.sOriginalCharacterName = pEntry->pEditorExtension->sOriginalCharacterName;
+    outEditorInfo.sOriginalCharacterName = pEntry->pEditorExtension->sOriginalCharacterName.c_str();
 
     outEditorInfo.nRow = pEntry->pEditorExtension->nRow;
     outEditorInfo.bUseSubtitle = (pEntry->flags & SLocalizedStringEntry::USE_SUBTITLE);
@@ -2252,7 +2281,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByIndex(int nIndex, SLocalizedInf
 }
 
 //////////////////////////////////////////////////////////////////////////
-bool CLocalizedStringsManager::GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle)
+bool CLocalizedStringsManager::GetSubtitle(const char* sKeyOrLabel, AZStd::string& outSubtitle, bool bForceSubtitle)
 {
     assert(sKeyOrLabel);
     if (!m_pLanguage || !sKeyOrLabel || !*sKeyOrLabel)
@@ -2376,13 +2405,13 @@ void InternalFormatStringMessage(StringClass& outString, const StringClass& sStr
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CLocalizedStringsManager::FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams)
+void CLocalizedStringsManager::FormatStringMessage_List(AZStd::string& outString, const AZStd::string& sString, const char** sParams, int nParams)
 {
     InternalFormatStringMessage(outString, sString, sParams, nParams);
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CLocalizedStringsManager::FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2, const char* param3, const char* param4)
+void CLocalizedStringsManager::FormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char* param1, const char* param2, const char* param3, const char* param4)
 {
     InternalFormatStringMessage(outString, sString, param1, param2, param3, param4);
 }
@@ -2462,7 +2491,7 @@ void CLocalizedStringsManager::InternalSetCurrentLanguage(CLocalizedStringsManag
 #if defined (WIN32) || defined(WIN64)
     if (m_pLanguage != 0)
     {
-        g_currentLanguageID = GetLanguageID(m_pLanguage->sLanguage);
+        g_currentLanguageID = GetLanguageID(m_pLanguage->sLanguage.c_str());
     }
     else
     {
@@ -2494,7 +2523,7 @@ void CLocalizedStringsManager::InternalSetCurrentLanguage(CLocalizedStringsManag
     }
 }
 
-void CLocalizedStringsManager::LocalizeDuration(int seconds, string& outDurationString)
+void CLocalizedStringsManager::LocalizeDuration(int seconds, AZStd::string& outDurationString)
 {
     int s = seconds;
     int d, h, m;
@@ -2504,27 +2533,27 @@ void CLocalizedStringsManager::LocalizeDuration(int seconds, string& outDuration
     s -= h * 3600;
     m = s / 60;
     s = s - m * 60;
-    string str;
+    AZStd::string str;
     if (d > 1)
     {
-        str.Format("%d @ui_days %02d:%02d:%02d", d, h, m, s);
+        str = AZStd::string::format("%d @ui_days %02d:%02d:%02d", d, h, m, s);
     }
     else if (d > 0)
     {
-        str.Format("%d @ui_day %02d:%02d:%02d", d, h, m, s);
+        str = AZStd::string::format("%d @ui_day %02d:%02d:%02d", d, h, m, s);
     }
     else if (h > 0)
     {
-        str.Format("%02d:%02d:%02d", h, m, s);
+        str = AZStd::string::format("%02d:%02d:%02d", h, m, s);
     }
     else
     {
-        str.Format("%02d:%02d", m, s);
+        str = AZStd::string::format("%02d:%02d", m, s);
     }
     LocalizeString_s(str, outDurationString);
 }
 
-void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberString)
+void CLocalizedStringsManager::LocalizeNumber(int number, AZStd::string& outNumberString)
 {
     if (number == 0)
     {
@@ -2535,7 +2564,7 @@ void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberStrin
     outNumberString.assign("");
 
     int n = abs(number);
-    string separator;
+    AZStd::string separator;
     AZStd::fixed_string<64> tmp;
     LocalizeString_ch("@ui_thousand_separator", separator);
     while (n > 0)
@@ -2544,41 +2573,41 @@ void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberStrin
         int b = n - (a * 1000);
         if (a > 0)
         {
-            tmp.Format("%s%03d%s", separator.c_str(), b, tmp.c_str());
+            tmp = AZStd::string::format("%s%03d%s", separator.c_str(), b, tmp.c_str());
         }
         else
         {
-            tmp.Format("%d%s", b, tmp.c_str());
+            tmp = AZStd::string::format("%d%s", b, tmp.c_str());
         }
         n = a;
     }
 
     if (number < 0)
     {
-        tmp.Format("-%s", tmp.c_str());
+        tmp = AZStd::string::format("-%s", tmp.c_str());
     }
 
     outNumberString.assign(tmp.c_str());
 }
 
-void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals, string& outNumberString)
+void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals, AZStd::string& outNumberString)
 {
     if (number == 0.0f)
     {
         AZStd::fixed_string<64> tmp;
-        tmp.Format("%.*f", decimals, number);
+        tmp = AZStd::fixed_string<64>::format("%.*f", decimals, number);
         outNumberString.assign(tmp.c_str());
         return;
     }
 
     outNumberString.assign("");
 
-    string commaSeparator;
+    AZStd::string commaSeparator;
     LocalizeString_ch("@ui_decimal_separator", commaSeparator);
     float f = number > 0.0f ? number : -number;
     int d = (int)f;
 
-    string intPart;
+    AZStd::string intPart;
     LocalizeNumber(d, intPart);
 
     float decimalsOnly = f - (float)d;
@@ -2586,7 +2615,7 @@ void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals
     int decimalsAsInt = aznumeric_cast(int_round(decimalsOnly * pow(10.0f, decimals)));
 
     AZStd::fixed_string<64> tmp;
-    tmp.Format("%s%s%0*d", intPart.c_str(), commaSeparator.c_str(), decimals, decimalsAsInt);
+    tmp = AZStd::fixed_string<64>::format("%s%s%0*d", intPart.c_str(), commaSeparator.c_str(), decimals, decimalsAsInt);
 
     outNumberString.assign(tmp.c_str());
 }
@@ -2640,7 +2669,7 @@ namespace
     }
 };
 
-void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString)
+void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString)
 {
     if (bMakeLocalTime)
     {
@@ -2664,7 +2693,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
     }
 }
 
-void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString)
+void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString)
 {
     if (bMakeLocalTime)
     {
@@ -2689,7 +2718,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
             // len includes terminating null!
             tmpString.resize(len);
             ::GetDateFormatW(lcID, 0, &systemTime, L"ddd", (wchar_t*) tmpString.c_str(), len);
-            string utf8;
+            AZStd::string utf8;
             Unicode::Convert(utf8, tmpString);
             outDateString.append(utf8);
             outDateString.append(" ");
@@ -2702,7 +2731,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
         // len includes terminating null!
         tmpString.resize(len);
         ::GetDateFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len);
-        string utf8;
+        AZStd::string utf8;
         Unicode::Convert(utf8, tmpString);
         outDateString.append(utf8);
     }
@@ -2710,7 +2739,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
 
 #else // #if defined (WIN32) || defined(WIN64)
 
-void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString)
+void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString)
 {
     struct tm theTime;
     if (bMakeLocalTime)
@@ -2737,7 +2766,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
     Unicode::Convert(outTimeString, buf);
 }
 
-void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString)
+void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString)
 {
     struct tm theTime;
     if (bMakeLocalTime)
diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.h b/Code/Legacy/CrySystem/LocalizedStringManager.h
index 581a657c81..72a7916d1f 100644
--- a/Code/Legacy/CrySystem/LocalizedStringManager.h
+++ b/Code/Legacy/CrySystem/LocalizedStringManager.h
@@ -25,7 +25,7 @@ class CLocalizedStringsManager
     , public ISystemEventListener
 {
 public:
-    typedef std::vector TLocalizationTagVec;
+    typedef std::vector TLocalizationTagVec;
 
     constexpr const static size_t LOADING_FIXED_STRING_LENGTH = 2048;
     constexpr const static size_t COMPRESSION_FIXED_BUFFER_LENGTH = 6144;
@@ -56,11 +56,11 @@ public:
     void ReloadData() override;
     void FreeData();
 
-    bool LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish = false) override;
-    bool LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish = false) override;
+    bool LocalizeString_s(const AZStd::string& sString, AZStd::string& outLocalizedString, bool bEnglish = false) override;
+    bool LocalizeString_ch(const char* sString, AZStd::string& outLocalizedString, bool bEnglish = false) override;
 
     void LocalizeAndSubstituteInternal(AZStd::string& locString, const AZStd::vector& keys, const AZStd::vector& values) override;
-    bool LocalizeLabel(const char* sLabel, string& outLocalizedString, bool bEnglish = false) override;
+    bool LocalizeLabel(const char* sLabel, AZStd::string& outLocalizedString, bool bEnglish = false) override;
     bool IsLocalizedInfoFound(const char* sKey);
     bool GetLocalizedInfoByKey(const char* sKey, SLocalizedInfoGame& outGameInfo);
     bool GetLocalizedInfoByKey(const char* sKey, SLocalizedSoundInfoGame* pOutSoundInfoGame);
@@ -68,17 +68,17 @@ public:
     bool GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoGame& outGameInfo);
     bool GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoEditor& outEditorInfo);
 
-    bool GetEnglishString(const char* sKey, string& sLocalizedString) override;
-    bool GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle = false) override;
+    bool GetEnglishString(const char* sKey, AZStd::string& sLocalizedString) override;
+    bool GetSubtitle(const char* sKeyOrLabel, AZStd::string& outSubtitle, bool bForceSubtitle = false) override;
 
-    void FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams) override;
-    void FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) override;
+    void FormatStringMessage_List(AZStd::string& outString, const AZStd::string& sString, const char** sParams, int nParams) override;
+    void FormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) override;
 
-    void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString) override;
-    void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString) override;
-    void LocalizeDuration(int seconds, string& outDurationString) override;
-    void LocalizeNumber(int number, string& outNumberString) override;
-    void LocalizeNumber_Decimal(float number, int decimals, string& outNumberString) override;
+    void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString) override;
+    void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString) override;
+    void LocalizeDuration(int seconds, AZStd::string& outDurationString) override;
+    void LocalizeNumber(int number, AZStd::string& outNumberString) override;
+    void LocalizeNumber_Decimal(float number, int decimals, AZStd::string& outNumberString) override;
 
     bool ProjectUsesLocalization() const override;
     // ~ILocalizationManager
@@ -95,7 +95,7 @@ public:
 private:
     void SetAvailableLocalizationsBitfield(const ILocalizationManager::TLocalizationBitfield availableLocalizations);
 
-    bool LocalizeStringInternal(const char* pStr, size_t len, string& outLocalizedString, bool bEnglish);
+    bool LocalizeStringInternal(const char* pStr, size_t len, AZStd::string& outLocalizedString, bool bEnglish);
 
     bool DoLoadExcelXmlSpreadsheet(const char* sFileName, uint8 tagID, bool bReload);
     typedef bool(CLocalizedStringsManager::*LoadFunc)(const char*, uint8, bool);
@@ -104,11 +104,11 @@ private:
 
     struct SLocalizedStringEntryEditorExtension
     {
-        string  sKey;                                           // Map key text equivalent (without @)
-        string  sOriginalActorLine;             // english text
-        string  sUtf8TranslatedActorLine;       // localized text
-        string  sOriginalText;                      // subtitle. if empty, uses English text
-        string  sOriginalCharacterName;     // english character name speaking via XML asset
+        AZStd::string  sKey;                                           // Map key text equivalent (without @)
+        AZStd::string  sOriginalActorLine;             // english text
+        AZStd::string  sUtf8TranslatedActorLine;       // localized text
+        AZStd::string  sOriginalText;                      // subtitle. if empty, uses English text
+        AZStd::string  sOriginalCharacterName;     // english character name speaking via XML asset
 
         unsigned int nRow;                              // Number of row in XML file
 
@@ -141,15 +141,15 @@ private:
 
         union trans_text
         {
-            string*     psUtf8Uncompressed;
+            AZStd::string*     psUtf8Uncompressed;
             uint8*      szCompressed;       // Note that no size information is stored. This is for struct size optimization and unfortunately renders the size info inaccurate.
         };
 
-        string sCharacterName;  // character name speaking via XML asset
+        AZStd::string sCharacterName;  // character name speaking via XML asset
         trans_text TranslatedText;  // Subtitle of this line
 
         // audio specific part
-        string      sPrototypeSoundEvent;           // associated sound event prototype (radio, ...)
+        AZStd::string      sPrototypeSoundEvent;           // associated sound event prototype (radio, ...)
         CryHalf     fVolume;
         CryHalf     fRadioRatio;
         // SoundMoods
@@ -191,7 +191,7 @@ private:
             }
         };
 
-        string GetTranslatedText(const SLanguage* pLanguage) const;
+        AZStd::string GetTranslatedText(const SLanguage* pLanguage) const;
 
         void GetMemoryUsage(ICrySizer* pSizer) const
         {
@@ -224,7 +224,7 @@ private:
         typedef std::vector TLocalizedStringEntries;
         typedef std::vector THuffmanCoders;
 
-        string sLanguage;
+        AZStd::string sLanguage;
         StringsKeyMap m_keysMap;
         TLocalizedStringEntries m_vLocalizedStrings;
         THuffmanCoders m_vEncoders;
@@ -246,7 +246,7 @@ private:
     };
 
 #ifndef _RELEASE
-    std::map m_warnedAboutLabels;
+    std::map m_warnedAboutLabels;
     bool m_haveWarnedAboutAtLeastOneLabel;
 
     void LocalizedStringsManagerWarning(const char* label, const char* message);
@@ -259,45 +259,45 @@ private:
     void AddLocalizedString(SLanguage* pLanguage, SLocalizedStringEntry* pEntry, const uint32 keyCRC32);
     void AddControl(int nKey);
     //////////////////////////////////////////////////////////////////////////
-    void ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex);
+    void ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex);
     void InternalSetCurrentLanguage(SLanguage* pLanguage);
     ISystem* m_pSystem;
     // Pointer to the current language.
     SLanguage* m_pLanguage;
 
     // all loaded Localization Files
-    typedef std::pair pairFileName;
-    typedef std::map tmapFilenames;
+    typedef std::pair pairFileName;
+    typedef std::map tmapFilenames;
     tmapFilenames m_loadedTables;
 
 
     // filenames per tag
-    typedef std::vector TStringVec;
+    typedef std::vector TStringVec;
     struct STag
     {
         TStringVec  filenames;
         uint8               id;
         bool                loaded;
     };
-    typedef std::map TTagFileNames;
+    typedef std::map TTagFileNames;
     TTagFileNames m_tagFileNames;
     TStringVec m_tagLoadRequests;
 
     // Array of loaded languages.
     std::vector m_languages;
 
-    typedef std::set PrototypeSoundEvents;
+    typedef std::set PrototypeSoundEvents;
     PrototypeSoundEvents m_prototypeEvents;  // this set is purely used for clever string/string assigning to save memory
 
     struct less_strcmp
     {
-        bool operator()(const string& left, const string& right) const
+        bool operator()(const AZStd::string& left, const AZStd::string& right) const
         {
             return strcmp(left.c_str(), right.c_str()) < 0;
         }
     };
 
-    typedef std::set CharacterNameSet;
+    typedef std::set CharacterNameSet;
     CharacterNameSet m_characterNameSet; // this set is purely used for clever string/string assigning to save memory
 
     // CVARs
diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp
index 2c7c307d50..c23ed6e264 100644
--- a/Code/Legacy/CrySystem/Log.cpp
+++ b/Code/Legacy/CrySystem/Log.cpp
@@ -466,7 +466,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
     {
     case eWarning:
     case eWarningAlways:
-        cry_strcpy(szString, MAX_WARNING_LENGTH, "$6[Warning] ");
+        azstrcpy(szString, MAX_WARNING_LENGTH, "$6[Warning] ");
         szString += 12;     // strlen("$6[Warning] ");
         szAfterColour += 2;
         prefixSize = 12;
@@ -474,7 +474,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
 
     case eError:
     case eErrorAlways:
-        cry_strcpy(szString, MAX_WARNING_LENGTH, "$4[Error] ");
+        azstrcpy(szString, MAX_WARNING_LENGTH, "$4[Error] ");
         szString += 10;     // strlen("$4[Error] ");
         szAfterColour += 2;
         prefixSize = 10;
@@ -532,7 +532,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
             }
         }
         i = m_iLastHistoryItem = m_iLastHistoryItem + 1 & sz - 1;
-        cry_strcpy(m_history[i].str, m_history[i].ptr = szSpamCheck);
+        azstrcpy(m_history[i].str, m_history[i].ptr = szSpamCheck);
         m_history[i].type = type;
         m_history[i].time = time;
     }
@@ -956,7 +956,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
             {
                 timeStr.clear();
                 uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
-                timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
+                timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
                 tempString = timeStr + tempString;
             }
             lasttime = currenttime;
@@ -983,7 +983,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
             {
                 timeStr.clear();
                 uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
-                timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
+                timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
                 tempString = timeStr + tempString;
             }
             lasttime = currenttime;
@@ -1000,7 +1000,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
                 {
                     timeStr.clear();
                     uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
-                    timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
+                    timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
                     tempString = timeStr + tempString;
                 }
                 if (bFirst)
@@ -1218,10 +1218,10 @@ void CLog::CreateBackupFile() const
 
     // boswej: only create a backup if logging to the engine root, otherwise the
     // log output has been overridden and the user is responsible
-    string logDir = PathUtil::RemoveSlash(PathUtil::ToUnixPath(PathUtil::GetParentDirectory(m_szFilename)));
+    AZStd::string logDir = PathUtil::RemoveSlash(PathUtil::ToUnixPath(PathUtil::GetParentDirectory(m_szFilename)));
 
-    string sExt = PathUtil::GetExt(m_szFilename);
-    string sFileWithoutExt = PathUtil::GetFileName(m_szFilename);
+    AZStd::string sExt = PathUtil::GetExt(m_szFilename);
+    AZStd::string sFileWithoutExt = PathUtil::GetFileName(m_szFilename);
 
     {
         assert(::strstr(sFileWithoutExt, ":") == 0);
@@ -1234,14 +1234,14 @@ void CLog::CreateBackupFile() const
     AZ::IO::HandleType inFileHandle = AZ::IO::InvalidHandle;
     fileSystem->Open(m_szFilename, AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, inFileHandle);
 
-    string sBackupNameAttachment;
+    AZStd::string sBackupNameAttachment;
 
     // parse backup name attachment
     // e.g. BackupNameAttachment="attachment name"
     if (inFileHandle != AZ::IO::InvalidHandle)
     {
         bool bKeyFound = false;
-        string sName;
+        AZStd::string sName;
 
         while (!fileSystem->Eof(inFileHandle))
         {
@@ -1253,7 +1253,7 @@ void CLog::CreateBackupFile() const
                 {
                     bKeyFound = true;
 
-                    if (sName.find("BackupNameAttachment=") == string::npos)
+                    if (sName.find("BackupNameAttachment=") == AZStd::string::npos)
                     {
 #ifdef WIN32
                         OutputDebugString("Log::CreateBackupFile ERROR '");
@@ -1284,12 +1284,12 @@ void CLog::CreateBackupFile() const
         fileSystem->Close(inFileHandle);
     }
 
-    string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt);
+    AZStd::string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt);
     fileSystem->CreatePath(LOG_BACKUP_PATH);
     azstrcpy(m_sBackupFilename, bakdest.c_str());
     // Remove any existing backup file with the same name first since the copy will fail otherwise.
     fileSystem->Remove(m_sBackupFilename);
-    fileSystem->Copy(m_szFilename, bakdest);
+    fileSystem->Copy(m_szFilename, bakdest.c_str());
 #endif // AZ_LEGACY_CRYSYSTEM_TRAIT_ALLOW_CREATE_BACKUP_LOG_FILE
 }
 
diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp
index bf4de8489d..9c2e1b1129 100644
--- a/Code/Legacy/CrySystem/System.cpp
+++ b/Code/Legacy/CrySystem/System.cpp
@@ -88,14 +88,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
     }
 
     // Handle with the default procedure
-#if defined(UNICODE) || defined(_UNICODE)
     assert(IsWindowUnicode(hWnd) && "Window should be Unicode when compiling with UNICODE");
-#else
-    if (!IsWindowUnicode(hWnd))
-    {
-        return DefWindowProcA(hWnd, uMsg, wParam, lParam);
-    }
-#endif
     return DefWindowProcW(hWnd, uMsg, wParam, lParam);
 }
 #endif
@@ -138,7 +131,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
 #include "RemoteConsole/RemoteConsole.h"
 
 #include 
-#include 
 
 #include 
 #include 
@@ -1209,10 +1201,11 @@ void CSystem::WarningV(EValidatorModule module, EValidatorSeverity severity, int
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CSystem::GetLocalizedPath(const char* sLanguage, string& sLocalizedPath)
+void CSystem::GetLocalizedPath(const char* sLanguage, AZStd::string& sLocalizedPath)
 {
     // Omit the trailing slash!
-    string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1));
+    AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
+    sLocalizationFolder.pop_back();
 
     int locFormat = 0;
     LocalizationManagerRequestBus::BroadcastResult(locFormat, &LocalizationManagerRequestBus::Events::GetLocalizationFormat);
@@ -1228,16 +1221,17 @@ void CSystem::GetLocalizedPath(const char* sLanguage, string& sLocalizedPath)
     }
     else
     {
-        sLocalizedPath = string("Localized/") + sLanguage + "_xml.pak";
+        sLocalizedPath = AZStd::string("Localized/") + sLanguage + "_xml.pak";
         }
     }
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CSystem::GetLocalizedAudioPath(const char* sLanguage, string& sLocalizedPath)
+void CSystem::GetLocalizedAudioPath(const char* sLanguage, AZStd::string& sLocalizedPath)
 {
     // Omit the trailing slash!
-    string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1));
+    AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
+    sLocalizationFolder.pop_back();
 
     if (sLocalizationFolder.compareNoCase("Languages") != 0)
     {
@@ -1245,14 +1239,14 @@ void CSystem::GetLocalizedAudioPath(const char* sLanguage, string& sLocalizedPat
     }
     else
     {
-        sLocalizedPath = string("Localized/") + sLanguage + ".pak";
+        sLocalizedPath = AZStd::string("Localized/") + sLanguage + ".pak";
     }
 }
 
 //////////////////////////////////////////////////////////////////////////
 void CSystem::CloseLanguagePak(const char* sLanguage)
 {
-    string sLocalizedPath;
+    AZStd::string sLocalizedPath;
     GetLocalizedPath(sLanguage, sLocalizedPath);
     m_env.pCryPak->ClosePacks({ sLocalizedPath.c_str(), sLocalizedPath.size() });
 }
@@ -1260,7 +1254,7 @@ void CSystem::CloseLanguagePak(const char* sLanguage)
 //////////////////////////////////////////////////////////////////////////
 void CSystem::CloseLanguageAudioPak(const char* sLanguage)
 {
-    string sLocalizedPath;
+    AZStd::string sLocalizedPath;
     GetLocalizedAudioPath(sLanguage, sLocalizedPath);
     m_env.pCryPak->ClosePacks({ sLocalizedPath.c_str(), sLocalizedPath.size() });
 }
@@ -1334,11 +1328,11 @@ void CSystem::ExecuteCommandLine(bool deferred)
 
         if (pCmd->GetType() == eCLAT_Post)
         {
-            string sLine = pCmd->GetName();
+            AZStd::string sLine = pCmd->GetName();
             {
                 if (pCmd->GetValue())
                 {
-                    sLine += string(" ") + pCmd->GetValue();
+                    sLine += AZStd::string(" ") + pCmd->GetValue();
                 }
 
                 GetILog()->Log("Executing command from command line: \n%s\n", sLine.c_str()); // - the actual command might be executed much later (e.g. level load pause)
diff --git a/Code/Legacy/CrySystem/System.h b/Code/Legacy/CrySystem/System.h
index c66b2aab60..b6c4e0a96a 100644
--- a/Code/Legacy/CrySystem/System.h
+++ b/Code/Legacy/CrySystem/System.h
@@ -453,7 +453,7 @@ private:
     bool ReLaunchMediaCenter();
     void UpdateAudioSystems();
 
-    void AddCVarGroupDirectory(const string& sPath);
+    void AddCVarGroupDirectory(const AZStd::string& sPath);
 
     AZStd::unique_ptr LoadDynamiclibrary(const char* dllName) const;
 
@@ -623,7 +623,7 @@ private: // ------------------------------------------------------
     //  ICVar *m_sys_filecache;
     ICVar* m_gpu_particle_physics;
 
-    string  m_sSavedRDriver;                                //!< to restore the driver when quitting the dedicated server
+    AZStd::string  m_sSavedRDriver;                                //!< to restore the driver when quitting the dedicated server
 
     //////////////////////////////////////////////////////////////////////////
     //! User define callback for system events.
@@ -672,8 +672,8 @@ public:
     void OpenBasicPaks();
     void OpenLanguagePak(const char* sLanguage);
     void OpenLanguageAudioPak(const char* sLanguage);
-    void GetLocalizedPath(const char* sLanguage, string& sLocalizedPath);
-    void GetLocalizedAudioPath(const char* sLanguage, string& sLocalizedPath);
+    void GetLocalizedPath(const char* sLanguage, AZStd::string& sLocalizedPath);
+    void GetLocalizedAudioPath(const char* sLanguage, AZStd::string& sLocalizedPath);
     void CloseLanguagePak(const char* sLanguage);
     void CloseLanguageAudioPak(const char* sLanguage);
     void UpdateMovieSystem(const int updateFlags, const float fFrameTime, const bool bPreUpdate);
@@ -718,14 +718,14 @@ protected: // -------------------------------------------------------------
 
     CCmdLine*                                      m_pCmdLine;
 
-    string  m_currentLanguageAudio;
-    string  m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_android.cfg or system_windows_pc.cfg
+    AZStd::string  m_currentLanguageAudio;
+    AZStd::string  m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_android.cfg or system_windows_pc.cfg
 
     std::vector< std::pair > m_updateTimes;
 
     struct SErrorMessage
     {
-        string m_Message;
+        AZStd::string m_Message;
         float m_fTimeToShow;
         float m_Color[4];
         bool m_HardFailure;
diff --git a/Code/Legacy/CrySystem/SystemCFG.cpp b/Code/Legacy/CrySystem/SystemCFG.cpp
index 719928384b..062713c015 100644
--- a/Code/Legacy/CrySystem/SystemCFG.cpp
+++ b/Code/Legacy/CrySystem/SystemCFG.cpp
@@ -279,7 +279,7 @@ public:
         int nFlags = pCVar->GetFlags();
         if (((nFlags & VF_DUMPTODISK) && (nFlags & VF_MODIFIED)) || (nFlags & VF_WASINCONFIG))
         {
-            string szValue = pCVar->GetString();
+            AZStd::string szValue = pCVar->GetString();
             int pos;
 
             pos = 1;
@@ -287,7 +287,7 @@ public:
             {
                 pos = szValue.find_first_of("\\", pos);
 
-                if (pos == string::npos)
+                if (pos == AZStd::string::npos)
                 {
                     break;
                 }
@@ -302,7 +302,7 @@ public:
             {
                 pos = szValue.find_first_of("\"", pos);
 
-                if (pos == string::npos)
+                if (pos == AZStd::string::npos)
                 {
                     break;
                 }
@@ -311,7 +311,7 @@ public:
                 pos += 2;
             }
 
-            string szLine = pCVar->GetName();
+            AZStd::string szLine = pCVar->GetName();
 
             if (pCVar->GetType() == CVAR_STRING)
             {
@@ -344,7 +344,7 @@ void CSystem::SaveConfiguration()
 //////////////////////////////////////////////////////////////////////////
 // system cfg
 //////////////////////////////////////////////////////////////////////////
-CSystemConfiguration::CSystemConfiguration(const string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing)
+CSystemConfiguration::CSystemConfiguration(const AZStd::string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing)
     : m_strSysConfigFilePath(strSysConfigFilePath)
     , m_bError(false)
     , m_pSink(pSink)
@@ -364,14 +364,14 @@ CSystemConfiguration::~CSystemConfiguration()
 //////////////////////////////////////////////////////////////////////////
 bool CSystemConfiguration::ParseSystemConfig()
 {
-    string filename = m_strSysConfigFilePath;
-    if (strlen(PathUtil::GetExt(filename)) == 0)
+    AZStd::string filename = m_strSysConfigFilePath;
+    if (strlen(PathUtil::GetExt(filename.c_str())) == 0)
     {
         filename = PathUtil::ReplaceExtension(filename, "cfg");
     }
 
     CCryFile file;
-    string filenameLog;
+    AZStd::string filenameLog;
     {
         int flags = AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK;
 
@@ -380,7 +380,7 @@ bool CSystemConfiguration::ParseSystemConfig()
             // this is used when theres a very specific file to read, like @user@/game.cfg which is read
             // IN ADDITION to the one in the game folder, and afterwards to override values in it.
             // if the file is missing and its already prefixed with an alias, there is no need to look any further.
-            if (!(file.Open(filename, "rb", flags)))
+            if (!(file.Open(filename.c_str(), "rb", flags)))
             {
                 if (m_warnIfMissing)
                 {
@@ -394,11 +394,11 @@ bool CSystemConfiguration::ParseSystemConfig()
             // otherwise, if the file isn't prefixed with an alias, then its likely one of the convenience mappings
             // to either root or assets/config.  this is done so that code can just request a simple file name and get its data
             if (
-                !(file.Open(filename, "rb", flags)) &&
-                !(file.Open(string("@root@/") + filename, "rb", flags)) &&
-                !(file.Open(string("@assets@/") + filename, "rb", flags)) &&
-                !(file.Open(string("@assets@/config/") + filename, "rb", flags)) &&
-                !(file.Open(string("@assets@/config/spec/") + filename, "rb", flags))
+                !(file.Open(filename.c_str(), "rb", flags)) &&
+                !(file.Open((AZStd::string("@root@/") + filename).c_str(), "rb", flags)) &&
+                !(file.Open((AZStd::string("@assets@/") + filename).c_str(), "rb", flags)) &&
+                !(file.Open((AZStd::string("@assets@/config/") + filename).c_str(), "rb", flags)) &&
+                !(file.Open((AZStd::string("@assets@/config/spec/") + filename).c_str(), "rb", flags))
                 )
             {
                 if (m_warnIfMissing)
@@ -429,7 +429,7 @@ bool CSystemConfiguration::ParseSystemConfig()
     sAllText[nLen] = '\0';
     sAllText[nLen + 1] = '\0';
 
-    string strGroup;            // current group e.g. "[General]"
+    AZStd::string strGroup;            // current group e.g. "[General]"
 
     char* strLast = sAllText + nLen;
     char* str = sAllText;
@@ -447,11 +447,11 @@ bool CSystemConfiguration::ParseSystemConfig()
             str++;
         }
 
-        string strLine = s;
+        AZStd::string strLine = s;
 
         // detect groups e.g. "[General]"   should set strGroup="General"
         {
-            string strTrimmedLine(RemoveWhiteSpaces(strLine));
+            AZStd::string strTrimmedLine(RemoveWhiteSpaces(strLine));
             size_t size = strTrimmedLine.size();
 
             if (size >= 3)
@@ -466,7 +466,7 @@ bool CSystemConfiguration::ParseSystemConfig()
         }
 
         //trim all whitespace characters at the beginning and the end of the current line and store its size
-        strLine.Trim();
+        AZ::StringFunc::TrimWhiteSpace(strLine, true, true);
         size_t strLineSize = strLine.size();
 
         //skip comments, comments start with ";" or "--" but may have preceding whitespace characters
@@ -488,35 +488,35 @@ bool CSystemConfiguration::ParseSystemConfig()
         }
 
         //if line contains a '=' try to read and assign console variable
-        string::size_type posEq(strLine.find("=", 0));
-        if (string::npos != posEq)
+        AZStd::string::size_type posEq(strLine.find("=", 0));
+        if (AZStd::string::npos != posEq)
         {
-            string stemp(strLine, 0, posEq);
-            string strKey(RemoveWhiteSpaces(stemp));
+            AZStd::string stemp(strLine, 0, posEq);
+            AZStd::string strKey(RemoveWhiteSpaces(stemp));
 
             {
                 // extract value
-                string::size_type posValueStart(strLine.find("\"", posEq + 1) + 1);
-                string::size_type posValueEnd(strLine.rfind('\"'));
+                AZStd::string::size_type posValueStart(strLine.find("\"", posEq + 1) + 1);
+                AZStd::string::size_type posValueEnd(strLine.rfind('\"'));
 
-                string strValue;
+                AZStd::string strValue;
 
-                if (string::npos != posValueStart && string::npos != posValueEnd)
+                if (AZStd::string::npos != posValueStart && AZStd::string::npos != posValueEnd)
                 {
-                    strValue = string(strLine, posValueStart, posValueEnd - posValueStart);
+                    strValue = AZStd::string(strLine, posValueStart, posValueEnd - posValueStart);
                 }
                 else
                 {
-                    string strTmp(strLine, posEq + 1, strLine.size() - (posEq + 1));
+                    AZStd::string strTmp(strLine, posEq + 1, strLine.size() - (posEq + 1));
                     strValue = RemoveWhiteSpaces(strTmp);
                 }
 
                 {
                     // replace '\\\\' with '\\' and '\\\"' with '\"'
-                    strValue.replace("\\\\", "\\");
-                    strValue.replace("\\\"", "\"");
+                    AZ::StringFunc::Replace(strValue, "\\\\", "\\");
+                    AZ::StringFunc::Replace(strValue, "\\\"", "\"");
                     
-                    m_pSink->OnLoadConfigurationEntry(strKey, strValue, strGroup);
+                    m_pSink->OnLoadConfigurationEntry(strKey.c_str(), strValue.c_str(), strGroup.c_str());
                 }
             }
         }
diff --git a/Code/Legacy/CrySystem/SystemCFG.h b/Code/Legacy/CrySystem/SystemCFG.h
index ac4f04d146..cfaefd2e45 100644
--- a/Code/Legacy/CrySystem/SystemCFG.h
+++ b/Code/Legacy/CrySystem/SystemCFG.h
@@ -15,17 +15,17 @@
 #include 
 #include 
 
-typedef string SysConfigKey;
-typedef string SysConfigValue;
+typedef AZStd::string SysConfigKey;
+typedef AZStd::string SysConfigValue;
 
 //////////////////////////////////////////////////////////////////////////
 class CSystemConfiguration
 {
 public:
-    CSystemConfiguration(const string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing = true);
+    CSystemConfiguration(const AZStd::string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing = true);
     ~CSystemConfiguration();
 
-    string RemoveWhiteSpaces(string& s)
+    AZStd::string RemoveWhiteSpaces(AZStd::string& s)
     {
         s.Trim();
         return s;
@@ -39,10 +39,10 @@ private: // ----------------------------------------
     //   success
     bool ParseSystemConfig();
 
-    CSystem*                                               m_pSystem;
-    string                                                  m_strSysConfigFilePath;
-    bool                                                        m_bError;
-    ILoadConfigurationEntrySink*       m_pSink;                                         // never 0
+    CSystem*                           m_pSystem;
+    AZStd::string                      m_strSysConfigFilePath;
+    bool                               m_bError;
+    ILoadConfigurationEntrySink*       m_pSink;  // never 0
     bool m_warnIfMissing;
 };
 
diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp
index cce3cf4aec..ae177a9974 100644
--- a/Code/Legacy/CrySystem/SystemInit.cpp
+++ b/Code/Legacy/CrySystem/SystemInit.cpp
@@ -33,7 +33,6 @@
 
 #include "CryLibrary.h"
 #include "CryPath.h"
-#include 
 
 #include 
 #include 
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index 943a540ae6..a4be0e5054 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -505,9 +505,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
             if (bSucceeded)
             {
                 // Convert from UNICODE to UTF-8
-                AZStd::string str;
-                AZStd::to_string(str, AZStd::wstring(wMyDocumentsPath));
-                azstrcpy(szMyDocumentsPath, maxPathSize, str.c_str());
+                azstrcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath));
                 CoTaskMemFree(wMyDocumentsPath);
             }
         }
@@ -521,9 +519,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
         bSucceeded = SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, wMyDocumentsPath));
         if (bSucceeded)
         {
-            AZStd::string str;
-            AZStd::to_string(str, AZStd::wstring(wMyDocumentsPath));
-            azstrcpy(szMyDocumentsPath, maxPathSize, str.c_str());
+            azstrcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath));
         }
     }
 
diff --git a/Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h b/Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h
index 2634195f64..b4dd28e813 100644
--- a/Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h
+++ b/Code/Legacy/CrySystem/XML/ReadWriteXMLSink.h
@@ -36,7 +36,7 @@ public:
     ELSE_LOAD_PROPERTY(Vec3);                       \
     ELSE_LOAD_PROPERTY(int);                        \
     ELSE_LOAD_PROPERTY(float);                      \
-    ELSE_LOAD_PROPERTY(string);                     \
+    ELSE_LOAD_PROPERTY(AZStd::string);              \
     ELSE_LOAD_PROPERTY(bool);
 
 
diff --git a/Code/Legacy/CrySystem/XML/ReadXMLSink.cpp b/Code/Legacy/CrySystem/XML/ReadXMLSink.cpp
index bddc538bba..e75fed22ed 100644
--- a/Code/Legacy/CrySystem/XML/ReadXMLSink.cpp
+++ b/Code/Legacy/CrySystem/XML/ReadXMLSink.cpp
@@ -13,7 +13,7 @@
 #include 
 #include 
 
-typedef std::map IdTable;
+typedef std::map IdTable;
 struct SParseParams
 {
     IdTable idTable;
@@ -98,7 +98,7 @@ struct ReadPropertyTyped
 };
 
 template <>
-struct ReadPropertyTyped
+struct ReadPropertyTyped
 {
     static bool Load(const SParseParams& parseParams, const char* name, XmlNodeRef& definition, XmlNodeRef& data, IReadXMLSink* pSink)
     {
@@ -235,8 +235,9 @@ bool LoadProperty(const SParseParams& parseParams, XmlNodeRef& definition, XmlNo
 
             dataToRead = GetISystem()->CreateXmlNode(data->getTag());
 
-            string content = childRef->getContent();
-            dataToRead->setAttr(name, content.Trim().c_str());
+            AZStd::string content = childRef->getContent();
+            AZ::StringFunc::TrimWhiteSpace(content, true, true);
+            dataToRead->setAttr(name, content.c_str());
         }
 
         if (!dataToRead->haveAttr(name))
diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
index e98071ace0..26007eb229 100644
--- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
+++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
@@ -114,7 +114,7 @@ void CSerializeXMLWriterImpl::GetMemoryUsage(ICrySizer* pSizer) const
 //////////////////////////////////////////////////////////////////////////
 const char* CSerializeXMLWriterImpl::GetStackInfo() const
 {
-    static string str;
+    static AZStd::string str;
     str.assign("");
     for (int i = 0; i < (int)m_nodeStack.size(); i++)
     {
@@ -138,7 +138,7 @@ const char* CSerializeXMLWriterImpl::GetStackInfo() const
 //////////////////////////////////////////////////////////////////////////
 const char* CSerializeXMLWriterImpl::GetLuaStackInfo() const
 {
-    static string str;
+    static AZStd::string str;
     str.assign("");
     for (int i = 0; i < (int)m_luaSaveStack.size(); i++)
     {
diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
index 12a2f6f151..41dbe3dd7b 100644
--- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
+++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
@@ -138,7 +138,7 @@ private:
     bool IsDefaultValue(const Quat& v) const { return v.w == 1.0f && v.v.x == 0 && v.v.y == 0 && v.v.z == 0; };
     bool IsDefaultValue(const CTimeValue& v) const { return v.GetValue() == 0; };
     bool IsDefaultValue(const char* str) const { return !str || !*str; };
-    bool IsDefaultValue(const string& str) const { return str.empty(); };
+    bool IsDefaultValue(const AZStd::string& str) const { return str.empty(); };
     bool IsDefaultValue(const SSerializeString& str) const { return str.empty(); };
     //////////////////////////////////////////////////////////////////////////
 
diff --git a/Code/Legacy/CrySystem/XML/WriteXMLSource.cpp b/Code/Legacy/CrySystem/XML/WriteXMLSource.cpp
index 2a532befd3..b0d7a6f1af 100644
--- a/Code/Legacy/CrySystem/XML/WriteXMLSource.cpp
+++ b/Code/Legacy/CrySystem/XML/WriteXMLSource.cpp
@@ -12,7 +12,7 @@
 
 #include 
 
-typedef std::map IdTable;
+typedef std::map IdTable;
 
 static bool IsOptionalWriteXML(XmlNodeRef& definition);
 
@@ -66,7 +66,7 @@ struct WritePropertyTyped
 };
 
 template <>
-struct WritePropertyTyped
+struct WritePropertyTyped
     : public WritePropertyTyped
 {
 };
diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.h b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.h
index 7dcbe075cd..810a2268c9 100644
--- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.h
+++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.h
@@ -25,25 +25,25 @@ namespace XMLBinary
     {
     public:
         CXMLBinaryWriter();
-        bool WriteNode(IDataWriter* pFile, XmlNodeRef node, bool bNeedSwapEndian, XMLBinary::IFilter* pFilter, string& error);
+        bool WriteNode(IDataWriter* pFile, XmlNodeRef node, bool bNeedSwapEndian, XMLBinary::IFilter* pFilter, AZStd::string & error);
 
     private:
-        bool CompileTables(XmlNodeRef node, XMLBinary::IFilter* pFilter, string& error);
+        bool CompileTables(XmlNodeRef node, XMLBinary::IFilter* pFilter, AZStd::string& error);
 
-        bool CompileTablesForNode(XmlNodeRef node, int nParentIndex, XMLBinary::IFilter* pFilter, string& error);
-        bool CompileChildTable(XmlNodeRef node, XMLBinary::IFilter* pFilter, string& error);
+        bool CompileTablesForNode(XmlNodeRef node, int nParentIndex, XMLBinary::IFilter* pFilter, AZStd::string& error);
+        bool CompileChildTable(XmlNodeRef node, XMLBinary::IFilter* pFilter, AZStd::string& error);
         int AddString(const XmlString& sString);
 
     private:
         // tables.
         typedef std::map NodesMap;
-        typedef std::map StringMap;
+        typedef std::map StringMap;
 
         std::vector m_nodes;
         NodesMap m_nodesMap;
         std::vector m_attributes;
         std::vector m_childs;
-        std::vector m_strings;
+        std::vector m_strings;
         StringMap m_stringMap;
 
         uint m_nStringDataSize;
diff --git a/Code/Legacy/CrySystem/XML/XMLPatcher.cpp b/Code/Legacy/CrySystem/XML/XMLPatcher.cpp
index ff4cfc91d2..03c5af92d3 100644
--- a/Code/Legacy/CrySystem/XML/XMLPatcher.cpp
+++ b/Code/Legacy/CrySystem/XML/XMLPatcher.cpp
@@ -9,7 +9,6 @@
 
 #include "CrySystem_precompiled.h"
 #include "XMLPatcher.h"
-#include "StringUtils.h"
 
 CXMLPatcher::CXMLPatcher(XmlNodeRef& patchXML)
 {
@@ -84,7 +83,7 @@ XmlNodeRef CXMLPatcher::FindPatchForFile(
             {
                 const char* pForFile = child->getAttr("forfile");
 
-                if (pForFile && CryStringUtils::stristr(pForFile, pInFileToPatch) != 0)
+                if (pForFile && AZ::StringFunc::Find(pForFile, pInFileToPatch) != AZStd::string::npos)
                 {
                     result = child;
                     break;
@@ -353,7 +352,7 @@ void CXMLPatcher::DumpXMLNodes(
 
     INDENT();
 
-    ioTempString->Format("<%s ", inNode->getTag());
+    *ioTempString = AZStd::fixed_string<512>::format("<%s ", inNode->getTag());
 
     pPak->FWrite(ioTempString->c_str(), ioTempString->length(), inFileHandle);
 
@@ -361,7 +360,7 @@ void CXMLPatcher::DumpXMLNodes(
     {
         const char* pKey, * pVal;
         inNode->getAttributeByIndex(i, &pKey, &pVal);
-        ioTempString->Format("%s=\"%s\" ", pKey, pVal);
+        *ioTempString = AZStd::fixed_string<512>::format("%s=\"%s\" ", pKey, pVal);
         pPak->FWrite(ioTempString->c_str(), ioTempString->length(), inFileHandle);
     }
     pPak->FWrite(">\n", 2, inFileHandle);
@@ -372,7 +371,7 @@ void CXMLPatcher::DumpXMLNodes(
     }
 
     INDENT();
-    ioTempString->Format("\n", inNode->getTag());
+    *ioTempString = AZStd::fixed_string<512>::format("\n", inNode->getTag());
     pPak->FWrite(ioTempString->c_str(), ioTempString->length(), inFileHandle);
 }
 
@@ -391,12 +390,12 @@ void CXMLPatcher::DumpFiles(
         {
             pOrigFileName++;
 
-            DumpXMLFile(string().Format("PATCH_%s", pOrigFileName), inBefore);
+            DumpXMLFile(AZStd::string::format("PATCH_%s", pOrigFileName).c_str(), inBefore);
 
-            AZStd::fixed_string<128>        newFileName(pOrigFileName);
-            newFileName.replace(".xml", "_patched.xml");
+            AZStd::string newFileName(pOrigFileName);
+            AZ::StringFunc::Replace(newFileName, ".xml", "_patched.xml");
 
-            DumpXMLFile(string().Format("PATCH_%s", newFileName.c_str()), inAfter);
+            DumpXMLFile(AZStd::string::format("PATCH_%s", newFileName.c_str()).c_str(), inAfter);
         }
         else
         {
diff --git a/Code/Legacy/CrySystem/XML/XmlUtils.cpp b/Code/Legacy/CrySystem/XML/XmlUtils.cpp
index 1b341ee99e..5e31fff8d7 100644
--- a/Code/Legacy/CrySystem/XML/XmlUtils.cpp
+++ b/Code/Legacy/CrySystem/XML/XmlUtils.cpp
@@ -313,7 +313,7 @@ bool CXmlUtils::SaveBinaryXmlFile(const char* filename, XmlNodeRef root)
         return false;
     }
     XMLBinary::CXMLBinaryWriter writer;
-    string error;
+    AZStd::string error;
     return writer.WriteNode(&fileSink, root, false, 0, error);
 }
 
diff --git a/Code/Legacy/CrySystem/XML/xml.cpp b/Code/Legacy/CrySystem/XML/xml.cpp
index c6e660155f..728d9441f2 100644
--- a/Code/Legacy/CrySystem/XML/xml.cpp
+++ b/Code/Legacy/CrySystem/XML/xml.cpp
@@ -984,13 +984,13 @@ XmlString CXmlNode::MakeValidXmlString(const XmlString& instr) const
     XmlString str = instr;
 
     // check if str contains any invalid characters
-    str.replace("&", "&");
-    str.replace("\"", """);
-    str.replace("\'", "'");
-    str.replace("<", "<");
-    str.replace(">", ">");
-    str.replace("...", ">");
-    str.replace("\n", "
");
+    AZ::StringFunc::Replace(str, "&", "&");
+    AZ::StringFunc::Replace(str, "\"", """);
+    AZ::StringFunc::Replace(str, "\'", "'");
+    AZ::StringFunc::Replace(str, "<", "<");
+    AZ::StringFunc::Replace(str, ">", ">");
+    AZ::StringFunc::Replace(str, "...", ">");
+    AZ::StringFunc::Replace(str, "\n", "
");
 
     return str;
 }
@@ -1732,9 +1732,9 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString,
             return 0;
         }
         adjustedFilename = xmlFile.GetAdjustedFilename();
-        adjustedFilename.replace('\\', '/');
+        AZStd::replace(adjustedFilename.begin(), adjustedFilename.end(), '\\', '/');
         pakPath = xmlFile.GetPakPath();
-        pakPath.replace('\\', '/');
+        AZStd::replace(pakPath.begin(), pakPath.end(), '\\', '/');
     }
 
     if (g_bEnableBinaryXmlLoading)
diff --git a/Code/Tools/GridHub/GridHub/gridhub.cpp b/Code/Tools/GridHub/GridHub/gridhub.cpp
index f6f0988022..3dbecf681f 100644
--- a/Code/Tools/GridHub/GridHub/gridhub.cpp
+++ b/Code/Tools/GridHub/GridHub/gridhub.cpp
@@ -362,13 +362,9 @@ GridHubComponent::GridHubComponent()
     DWORD dwCompNameLen = AZ_ARRAY_SIZE(name);
     if ( GetComputerName(name, &dwCompNameLen) != 0 ) 
     {
-#ifdef _UNICODE
         char c[MAX_COMPUTERNAME_LENGTH + 1];
         wcstombs(c, name, AZ_ARRAY_SIZE(c));
         m_hubName = c;
-#else
-        m_hubName = name;
-#endif
     }
     else
 #endif
diff --git a/Code/Tools/Standalone/CMakeLists.txt b/Code/Tools/Standalone/CMakeLists.txt
index 479b8be11f..a8242022a8 100644
--- a/Code/Tools/Standalone/CMakeLists.txt
+++ b/Code/Tools/Standalone/CMakeLists.txt
@@ -36,7 +36,6 @@ ly_add_target(
             ${additional_dependencies}
     COMPILE_DEFINITIONS 
         PRIVATE
-            UNICODE
             STANDALONETOOLS_ENABLE_LUA_IDE
 )
 
@@ -68,6 +67,5 @@ ly_add_target(
             ${additional_dependencies}
     COMPILE_DEFINITIONS 
         PRIVATE
-            UNICODE
             STANDALONETOOLS_ENABLE_PROFILER
 )
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
index f72ba6e1ff..4c923c43c4 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
@@ -8,6 +8,8 @@
 
 #include 
 
+#include 
+
 #include 
 
 namespace AtomFontInternal
@@ -17,13 +19,11 @@ namespace AtomFontInternal
         TCHAR sysFontPath[MAX_PATH];
         if (SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0, SHGFP_TYPE_DEFAULT, sysFontPath)))
         {
-            const char* fontPath = m_strFontPath.c_str();
-            const char* fontName = AZ::IO::PathView(fontPath).Filename();
+            const AZ::IO::PathView fontName = AZ::IO::PathView(m_strFontPath.c_str()).Filename();
 
-            string newFontPath(sysFontPath);
-            newFontPath += "/";
-            newFontPath += fontName;
-            m_font->Load(newFontPath, m_FontTexSize.x, m_FontTexSize.y, m_slotSizes.x, m_slotSizes.y, CreateTTFFontFlag(m_FontSmoothMethod, m_FontSmoothAmount), m_SizeRatio);
+            AZ::IO::Path newFontPath(sysFontPath);
+            newFontPath /= fontName;
+            m_font->Load(newFontPath.c_str(), m_FontTexSize.x, m_FontTexSize.y, m_slotSizes.x, m_slotSizes.y, CreateTTFFontFlag(m_FontSmoothMethod, m_FontSmoothAmount), m_SizeRatio);
         }
     }
 }
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FontTexture_Windows.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FontTexture_Windows.cpp
index 5aae754a7d..33950689f5 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FontTexture_Windows.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FontTexture_Windows.cpp
@@ -11,7 +11,7 @@
 #include 
 
 //-------------------------------------------------------------------------------------------------
-int AZ::FontTexture::WriteToFile(const string& fileName)
+int AZ::FontTexture::WriteToFile(const AZStd::string& fileName)
 {
     AZ::IO::FileIOStream outputFile(fileName.c_str(), AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeBinary);
 
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp
index 35c2b26b48..ecf0789220 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/AtomFont.cpp
@@ -46,7 +46,7 @@ static void DumfontTexture(IConsoleCmdArgs* cmdArgs)
 
     if (fontName && *fontName && *fontName != '0')
     {
-        string fontFilePath("@devroot@/");
+        AZStd::string fontFilePath("@devroot@/");
         fontFilePath += fontName;
         fontFilePath += ".bmp";
 
@@ -61,7 +61,7 @@ static void DumfontTexture(IConsoleCmdArgs* cmdArgs)
 
 static void DumfontNames([[maybe_unused]] IConsoleCmdArgs* cmdArgs)
 {
-    string names = gEnv->pCryFont->GetLoadedFontNames();
+    AZStd::string names = gEnv->pCryFont->GetLoadedFontNames();
     gEnv->pLog->LogWithType(IMiniLog::eInputResponse, "Currently loaded fonts: %s", names.c_str());
 }
 
@@ -97,15 +97,15 @@ namespace
                 && !m_boldItalicFontFilename.empty();
         }
 
-        string m_lang;                      //!< Stores a comma-separated list of languages this collection of fonts applies to.
+        AZStd::string m_lang;               //!< Stores a comma-separated list of languages this collection of fonts applies to.
                                             //!< If this is an empty string, it implies that these set of fonts will be applied
                                             //!< by default (when a language is being used but no fonts in the font family are
                                             //!< mapped to that language).
 
-        string m_fontFilename;              //!< Font used when no styling is applied.
-        string m_boldFontFilename;          //!< Bold-styled font
-        string m_italicFontFilename;        //!< Italic-styled font
-        string m_boldItalicFontFilename;    //!< Bold-italic-styled font
+        AZStd::string m_fontFilename;              //!< Font used when no styling is applied.
+        AZStd::string m_boldFontFilename;          //!< Bold-styled font
+        AZStd::string m_italicFontFilename;        //!< Italic-styled font
+        AZStd::string m_boldItalicFontFilename;    //!< Bold-italic-styled font
     };
 
     //! Stores parsed font family XML data.
@@ -152,7 +152,7 @@ namespace
             return !m_fontFamilyName.empty();
         }
 
-        string m_fontFamilyName;                  //!< Value of the "name" font-family tag attribute
+        AZStd::string m_fontFamilyName;                  //!< Value of the "name" font-family tag attribute
         AZStd::list m_fontTagsXml;    //!< List of child  tag data.
     };
 
@@ -179,7 +179,7 @@ namespace
                 return false;
             }
 
-            string name;
+            AZStd::string name;
 
             for (int i = 0, count = node->getNumAttributes(); i < count; ++i)
             {
@@ -187,7 +187,7 @@ namespace
                 const char* value = "";
                 if (node->getAttributeByIndex(i, &key, &value))
                 {
-                    if (string(key) == "name")
+                    if (AZStd::string(key) == "name")
                     {
                         name = value;
                     }
@@ -199,7 +199,7 @@ namespace
                 }
             }
 
-            name.Trim();
+            AZ::StringFunc::TrimWhiteSpace(name, true, true);
             if (!name.empty())
             {
                 xmlData.m_fontFamilyName = name;
@@ -216,14 +216,14 @@ namespace
         {
             xmlData.m_fontTagsXml.push_back(FontTagXml());
 
-            string lang;
+            AZStd::string lang;
             for (int i = 0, count = node->getNumAttributes(); i < count; ++i)
             {
                 const char* key = "";
                 const char* value = "";
                 if (node->getAttributeByIndex(i, &key, &value))
                 {
-                    if (string(key) == "lang")
+                    if (AZStd::string(key) == "lang")
                     {
                         lang = value;
                     }
@@ -235,7 +235,7 @@ namespace
                 }
             }
 
-            lang.Trim();
+            AZ::StringFunc::TrimWhiteSpace(lang, true, true);
             if (!lang.empty())
             {
                 xmlData.m_fontTagsXml.back().m_lang = lang;
@@ -253,8 +253,8 @@ namespace
                 return false;
             }
 
-            string path;
-            string tags;
+            AZStd::string path;
+            AZStd::string tags;
 
             for (int i = 0, count = node->getNumAttributes(); i < count; ++i)
             {
@@ -262,11 +262,11 @@ namespace
                 const char* value = "";
                 if (node->getAttributeByIndex(i, &key, &value))
                 {
-                    if (string(key) == "path")
+                    if (AZStd::string(key) == "path")
                     {
                         path = value;
                     }
-                    else if (string(key) == "tags")
+                    else if (AZStd::string(key) == "tags")
                     {
                         tags = value;
                     }
@@ -278,7 +278,7 @@ namespace
                 }
             }
 
-            tags.Trim();
+            AZ::StringFunc::TrimWhiteSpace(tags, true, true);
             if (tags.empty())
             {
                 xmlData.m_fontTagsXml.back().m_fontFilename = path;
@@ -315,7 +315,7 @@ namespace
     //! when referencing font family names from font family XML files), and
     //! attempting to load the XML files directly via ISystem() methods can
     //! produce a lot of warning noise.
-    XmlNodeRef SafeLoadXmlFromFile(const string& xmlPath)
+    XmlNodeRef SafeLoadXmlFromFile(const AZStd::string& xmlPath)
     {
         if (gEnv->pCryPak->IsFileExist(xmlPath.c_str()))
         {
@@ -383,8 +383,8 @@ void AZ::AtomFont::Release()
 
 IFFont* AZ::AtomFont::NewFont(const char* fontName)
 {
-    string name = fontName;
-    name.MakeLower();
+    AZStd::string name = fontName;
+    AZStd::to_lower(name.begin(), name.end());
     AzFramework::FontId fontId = GetFontId(name.c_str());
 
     FontMapItor it = m_fonts.find(fontId);
@@ -404,7 +404,9 @@ IFFont* AZ::AtomFont::NewFont(const char* fontName)
 
 IFFont* AZ::AtomFont::GetFont(const char* fontName) const
 {
-    AzFramework::FontId fontId = GetFontId(string(fontName).MakeLower().c_str());
+    AZStd::string name = fontName;
+    AZStd::to_lower(name.begin(), name.end());
+    AzFramework::FontId fontId = GetFontId(name.c_str());
     FontMapConstItor it = m_fonts.find(fontId);
     return it != m_fonts.end() ? it->second : 0;
 }
@@ -423,8 +425,8 @@ AzFramework::FontDrawInterface* AZ::AtomFont::GetDefaultFontDrawInterface() cons
 FontFamilyPtr AZ::AtomFont::LoadFontFamily(const char* fontFamilyName)
 {
     FontFamilyPtr fontFamily(nullptr);
-    string fontFamilyPath;
-    string fontFamilyFullPath;
+    AZStd::string fontFamilyPath;
+    AZStd::string fontFamilyFullPath;
     
     XmlNodeRef root = LoadFontFamilyXml(fontFamilyName, fontFamilyPath, fontFamilyFullPath);
 
@@ -450,13 +452,13 @@ FontFamilyPtr AZ::AtomFont::LoadFontFamily(const char* fontFamilyName)
                 }
                 else
                 {
-                    int searchPos = 0;
-                    string langToken;
-
                     // "lang" font-tag attribute could be comma-separated
-                    while (!(langToken = fontTagXml.m_lang.Tokenize(",", searchPos)).empty())
+                    AZStd::vector tokens;
+                    AZ::StringFunc::Tokenize(fontTagXml.m_lang, tokens, ',');
+                    for(AZStd::string& langToken : tokens)
                     {
-                        if (langToken.Trim() == currentLanguage)
+                        AZ::StringFunc::TrimWhiteSpace(langToken, true, true);
+                        if (langToken == currentLanguage)
                         {
                             langSpecificFont = &fontTagXml;
                             break;
@@ -494,7 +496,7 @@ FontFamilyPtr AZ::AtomFont::LoadFontFamily(const char* fontFamilyName)
                     // Map the font family name both by path and by name defined
                     // within the Font Family XML itself. This allows font 
                     // families to also be referenced simply by name.
-                    if (!AddFontFamilyToMaps(fontFamilyFullPath, xmlData.m_fontFamilyName, fontFamily))
+                    if (!AddFontFamilyToMaps(fontFamilyFullPath.c_str(), xmlData.m_fontFamilyName.c_str(), fontFamily))
                     {
                         SAFE_RELEASE(normal);
                         SAFE_RELEASE(bold);
@@ -540,7 +542,7 @@ FontFamilyPtr AZ::AtomFont::LoadFontFamily(const char* fontFamilyName)
             // Use filepath as familyName so font loading/unloading doesn't break with duplicate file names
             fontFamily->familyName = fontFamilyName;
 
-            if (!AddFontFamilyToMaps(fontFamilyName, fontFamily->familyName, fontFamily))
+            if (!AddFontFamilyToMaps(fontFamilyName, fontFamily->familyName.c_str(), fontFamily))
             {
                 SAFE_RELEASE(font);
 
@@ -581,7 +583,9 @@ FontFamilyPtr AZ::AtomFont::GetFontFamily(const char* fontFamilyName)
     // or just the filename of a font itself. Fonts are mapped by font family
     // name or by filepath, so attempt lookup using the map first since it's
     // the fastest.
-    string loweredName = string(fontFamilyName).Trim().MakeLower();
+    AZStd::string loweredName = AZStd::string(fontFamilyName);
+    AZ::StringFunc::TrimWhiteSpace(loweredName, true, true);
+    AZStd::to_lower(loweredName.begin(), loweredName.end());
     auto it = m_fontFamilies.find(PathUtil::MakeGamePath(loweredName).c_str());
     if (it != m_fontFamilies.end())
     {
@@ -596,9 +600,9 @@ FontFamilyPtr AZ::AtomFont::GetFontFamily(const char* fontFamilyName)
         for (const auto& fontFamilyIter : m_fontFamilies)
         {
             const AZStd::string& mappedFontFamilyName = fontFamilyIter.first;
-            string mappedFilenameNoExtension = PathUtil::GetFileName(mappedFontFamilyName.c_str());
+            AZStd::string mappedFilenameNoExtension = PathUtil::GetFileName(mappedFontFamilyName.c_str());
 
-            string searchStringFilenameNoExtension = PathUtil::GetFileName(loweredName);
+            AZStd::string searchStringFilenameNoExtension = PathUtil::GetFileName(loweredName);
 
             if (mappedFilenameNoExtension == searchStringFilenameNoExtension)
             {
@@ -619,9 +623,9 @@ void AZ::AtomFont::AddCharsToFontTextures(FontFamilyPtr fontFamily, const char*
     fontFamily->boldItalic->AddCharsToFontTexture(chars, glyphSizeX, glyphSizeY);
 }
 
-string AZ::AtomFont::GetLoadedFontNames() const
+AZStd::string AZ::AtomFont::GetLoadedFontNames() const
 {
-    string ret;
+    AZStd::string ret;
     for (FontMapConstItor it = m_fonts.begin(), itEnd = m_fonts.end(); it != itEnd; ++it)
     {
         FFont* font = it->second;
@@ -678,7 +682,9 @@ void AZ::AtomFont::ReloadAllFonts()
 
 void AZ::AtomFont::UnregisterFont(const char* fontName)
 {
-    AzFramework::FontId fontId = GetFontId(string(fontName).MakeLower().c_str());
+    AZStd::string name(fontName);
+    AZStd::to_lower(name.begin(), name.end());
+    AzFramework::FontId fontId = GetFontId(name.c_str());
     FontMapItor it = m_fonts.find(fontId);
 
 #if defined(AZ_ENABLE_TRACING)
@@ -715,10 +721,10 @@ void AZ::AtomFont::UnregisterFont(const char* fontName)
 
 IFFont* AZ::AtomFont::LoadFont(const char* fontName)
 {
-    string fontNameLower = fontName;
-    fontNameLower.MakeLower();
+    AZStd::string fontNameLower = fontName;
+    AZStd::to_lower(fontNameLower.begin(), fontNameLower.end());
 
-    IFFont* font = GetFont(fontNameLower);
+    IFFont* font = GetFont(fontNameLower.c_str());
     if (font)
     {
         font->AddRef(); // use existing loaded font
@@ -726,10 +732,10 @@ IFFont* AZ::AtomFont::LoadFont(const char* fontName)
     else
     {
         // attempt to create and load a new font, use the font pathname as the font name
-        font = NewFont(fontNameLower);
+        font = NewFont(fontNameLower.c_str());
         if (!font)
         {
-            string errorMsg = "Error creating a new font named ";
+            AZStd::string errorMsg = "Error creating a new font named ";
             errorMsg += fontNameLower;
             errorMsg += ".";
             CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, errorMsg.c_str());
@@ -737,12 +743,12 @@ IFFont* AZ::AtomFont::LoadFont(const char* fontName)
         else
         {
             // creating font adds one to its refcount so no need for AddRef here
-            if (!font->Load(fontNameLower))
+            if (!font->Load(fontNameLower.c_str()))
             {
-                string errorMsg = "Error loading a font from ";
+                AZStd::string errorMsg = "Error loading a font from ";
                 errorMsg += fontNameLower;
                 errorMsg += ".";
-                CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, errorMsg);
+                CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, errorMsg.c_str());
                 font->Release();
                 font = nullptr;
             }
@@ -764,8 +770,9 @@ void AZ::AtomFont::ReleaseFontFamily(FontFamily* fontFamily)
     // Note that the FontFamily is mapped both by filename and by "family name"
     auto it = m_fontFamilyReverseLookup[fontFamily];
     m_fontFamilies.erase(it);
-    string familyName(fontFamily->familyName);
-    m_fontFamilies.erase(familyName.MakeLower().c_str());
+    AZStd::string familyName(fontFamily->familyName);
+    AZStd::to_lower(familyName.begin(), familyName.end());
+    m_fontFamilies.erase(familyName.c_str());
 
     // Reverse lookup is used to avoid needing to store filename path with
     // the font family, so we need to remove that entry also.
@@ -785,12 +792,11 @@ bool AZ::AtomFont::AddFontFamilyToMaps(const char* fontFamilyFilename, const cha
     }
 
     // We don't support "updating" mapped values. 
-    AZStd::string loweredFilename(PathUtil::MakeGamePath(string(fontFamilyFilename)).c_str());
+    AZStd::string loweredFilename(PathUtil::MakeGamePath(AZStd::string(fontFamilyFilename)).c_str());
     AZStd::to_lower(loweredFilename.begin(), loweredFilename.end());
     if (m_fontFamilies.find(loweredFilename) != m_fontFamilies.end())
     {
-        string warnMsg;
-        warnMsg.Format("Couldn't load Font Family '%s': already loaded", fontFamilyFilename);
+        AZStd::string warnMsg = AZStd::string::format("Couldn't load Font Family '%s': already loaded", fontFamilyFilename);
         CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, warnMsg.c_str());
         return false;
     }
@@ -801,8 +807,7 @@ bool AZ::AtomFont::AddFontFamilyToMaps(const char* fontFamilyFilename, const cha
     AZStd::to_lower(loweredFontFamilyName.begin(), loweredFontFamilyName.end());
     if (m_fontFamilies.find(loweredFontFamilyName) != m_fontFamilies.end())
     {
-        string warnMsg;
-        warnMsg.Format("Couldn't load Font Family '%s': already loaded", fontFamilyName);
+        AZStd::string warnMsg = AZStd::string::format("Couldn't load Font Family '%s': already loaded", fontFamilyName);
         CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, warnMsg.c_str());
         return false;
     }
@@ -819,7 +824,7 @@ bool AZ::AtomFont::AddFontFamilyToMaps(const char* fontFamilyFilename, const cha
     return true;
 }
 
-XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, string& outputDirectory, string& outputFullPath)
+XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, AZStd::string& outputDirectory, AZStd::string& outputFullPath)
 {
     outputFullPath = fontFamilyName;
     outputDirectory = PathUtil::GetPath(fontFamilyName);
@@ -829,8 +834,8 @@ XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, string& o
     // not a path, so we try to build a "best guess" path from the name.
     if (!root)
     {
-        string fileNoExtension(PathUtil::GetFileName(fontFamilyName));
-        string fileExtension(PathUtil::GetExt(fontFamilyName));
+        AZStd::string fileNoExtension(PathUtil::GetFileName(fontFamilyName));
+        AZStd::string fileExtension(PathUtil::GetExt(fontFamilyName));
 
         if (fileExtension.empty())
         {
@@ -838,14 +843,14 @@ XmlNodeRef AZ::AtomFont::LoadFontFamilyXml(const char* fontFamilyName, string& o
         }
 
         // Try: "fonts/fontName.fontfamily"
-        outputDirectory = string("fonts/");
+        outputDirectory = AZStd::string("fonts/");
         outputFullPath = outputDirectory + fileNoExtension + fileExtension;
         root = SafeLoadXmlFromFile(outputFullPath);
 
         // Finally, try: "fonts/fontName/fontName.fontfamily"
         if (!root)
         {
-            outputDirectory = string("fonts/") + fileNoExtension + "/";
+            outputDirectory = AZStd::string("fonts/") + fileNoExtension + "/";
             outputFullPath = outputDirectory + fileNoExtension + fileExtension;
             root = SafeLoadXmlFromFile(outputFullPath);
         }
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
index c07717945a..ddb2fa6292 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
@@ -126,7 +126,7 @@ bool AZ::FFont::Load(const char* fontFilePath, unsigned int width, unsigned int
 
     auto pPak = gEnv->pCryPak;
 
-    string fullFile;
+    AZStd::string fullFile;
     if (pPak->IsAbsPath(fontFilePath))
     {
         fullFile = fontFilePath;
@@ -1166,7 +1166,7 @@ size_t AZ::FFont::GetTextLength(const char* str, const bool asciiMultiLine) cons
     return len;
 }
 
-void AZ::FFont::WrapText(string& result, float maxWidth, const char* str, const TextDrawContext& ctx)
+void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str, const TextDrawContext& ctx)
 {
     result = str;
 
diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
index 98cbd22f71..ac55cd38e9 100644
--- a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
+++ b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
@@ -47,8 +47,7 @@ bool PropertyHandlerChar::ReadValuesIntoGUI(size_t index, AzToolsFramework::Prop
         // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
         // work for cases tested but may not in general.
         wchar_t wcharString[2] = { static_cast(instance), 0 };
-        AZStd::string val;
-        AZStd::to_string(val, AZStd::wstring(wcharString));
+        AZStd::string val(CryStringUtils::WStrToUTF8(wcharString));
         GUI->setValue(val);
     }
     GUI->blockSignals(false);
diff --git a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
index cbd0b2d6cb..7bcdc26712 100644
--- a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
+++ b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
@@ -9,7 +9,6 @@
 
 #include "UiClipboard.h"
 #include 
-#include 
 
 bool UiClipboard::SetText(const AZStd::string& text)
 {
@@ -20,8 +19,7 @@ bool UiClipboard::SetText(const AZStd::string& text)
         {
             if (text.length() > 0)
             {
-                AZStd::wstring wstr;
-                AZStd::to_wstring(wstr, text);
+                auto wstr = CryStringUtils::UTF8ToWStr(text.c_str());
                 const SIZE_T buffSize = (wstr.size() + 1) * sizeof(WCHAR);
                 if (HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, buffSize))
                 {
@@ -47,7 +45,7 @@ AZStd::string UiClipboard::GetText()
         if (HANDLE hText = GetClipboardData(CF_UNICODETEXT))
         {
             const WCHAR* text = static_cast(GlobalLock(hText));
-            AZStd::to_string(outText, AZStd::wstring(text));
+            outText = CryStringUtils::WStrToUTF8(text);
             GlobalUnlock(hText);
         }
         CloseClipboard();
diff --git a/Gems/LyShine/Code/Source/StringUtfUtils.h b/Gems/LyShine/Code/Source/StringUtfUtils.h
index e10e691a6f..74a27afe9f 100644
--- a/Gems/LyShine/Code/Source/StringUtfUtils.h
+++ b/Gems/LyShine/Code/Source/StringUtfUtils.h
@@ -36,8 +36,7 @@ namespace LyShine
         // In the long run it would be better to eliminate
         // this function and use Unicode::CIterator<>::Position instead.
         wchar_t wcharString[2] = { static_cast(multiByteChar), 0 };
-        AZStd::string utf8String;
-        AZStd::to_string(utf8String, AZStd::wstring(wcharString));
+        AZStd::string utf8String(CryStringUtils::WStrToUTF8(wcharString));
         int utf8Length = utf8String.length();
         return utf8Length;
     }
diff --git a/Gems/LyShine/Code/Source/UiButtonComponent.cpp b/Gems/LyShine/Code/Source/UiButtonComponent.cpp
index c6ba64848e..11bb088400 100644
--- a/Gems/LyShine/Code/Source/UiButtonComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiButtonComponent.cpp
@@ -222,7 +222,7 @@ bool UiButtonComponent::VersionConverter(AZ::SerializeContext& context,
     // - Need to convert Color to Color and Alpha
     // conversion from version 2 to 3:
     // - Need to convert CryString ActionName elements to AZStd::string
-    AZ_Assert(classElement.GetVersion() < 3, "Unsupported UiButtonComponent version: %d", classElement.GetVersion());
+    AZ_Assert(classElement.GetVersion() >= 3, "Unsupported UiButtonComponent version: %d", classElement.GetVersion());
 
     // conversion from version 3 to 4:
     // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference
diff --git a/Gems/LyShine/Code/Source/UiImageComponent.cpp b/Gems/LyShine/Code/Source/UiImageComponent.cpp
index 8f4145c07b..06996fbb48 100644
--- a/Gems/LyShine/Code/Source/UiImageComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiImageComponent.cpp
@@ -2663,7 +2663,7 @@ bool UiImageComponent::VersionConverter(AZ::SerializeContext& context,
     // conversion from version 1:
     // - Need to convert CryString elements to AZStd::string
     // - Need to convert Color to Color and Alpha
-    AZ_Assert(classElement.GetVersion() <= 1, "Unsupported UiImageComponent version: %d", classElement.GetVersion());
+    AZ_Assert(classElement.GetVersion() > 1, "Unsupported UiImageComponent version: %d", classElement.GetVersion());
 
     // conversion from version 1 or 2 to current:
     // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference
diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp
index 76a789c5cf..fadf09571f 100644
--- a/Gems/LyShine/Code/Source/UiTextComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp
@@ -4996,7 +4996,7 @@ bool UiTextComponent::VersionConverter(AZ::SerializeContext& context,
 {
     // conversion from version 1: Need to convert Color to Color and Alpha
     // conversion from version 1 or 2: Need to convert Text from CryString to AzString
-    AZ_Assert(classElement.GetVersion() <= 2, "Unsupported UiTextComponent version: %d", classElement.GetVersion());
+    AZ_Assert(classElement.GetVersion() > 2, "Unsupported UiTextComponent version: %d", classElement.GetVersion());
 
     // Versions prior to v4: Change default font
     if (classElement.GetVersion() <= 3)
diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
index c746d14095..c149c5a4d4 100644
--- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
@@ -1185,8 +1185,7 @@ void UiTextInputComponent::UpdateDisplayedTextFunction()
                 // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
                 // work for cases tested but may not in general.
                 wchar_t wcharString[2] = { static_cast(this->GetReplacementCharacter()), 0 };
-                AZStd::string replacementCharString;
-                AZStd::to_string(replacementCharString, AZStd::wstring(wcharString));
+                AZStd::string replacementCharString(CryStringUtils::WStrToUTF8(wcharString));
 
                 int numReplacementChars = LyShine::GetUtf8StringLength(originalText);
 
@@ -1478,7 +1477,7 @@ bool UiTextInputComponent::VersionConverter(AZ::SerializeContext& context,
     // - Need to convert Color to Color and Alpha
     // conversion from version 1 or 2 to current:
     // - Need to convert CryString ActionName elements to AZStd::string
-    AZ_Assert(classElement.GetVersion() <= 2, "Unsupported UiTextInputComponent version: %d", classElement.GetVersion());
+    AZ_Assert(classElement.GetVersion() > 2, "Unsupported UiTextInputComponent version: %d", classElement.GetVersion());
     
     // conversion from version 1, 2 or 3 to current:
     // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference

From 902bdeb6d6092d0b88066fbb873eaa043c3b788a Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 29 Jul 2021 16:50:50 -0700
Subject: [PATCH 023/205] Create RUN target as helpers for the project-centric
 workflow (#2520) (#2635)

* Create RUN target as helpers for the project-centric workflow

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>

* typo fix

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>

* rename target as ".Imported" and create "" as the metatarget that is used for debugging and building in o3de

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/CMakeLists.txt                 |  2 +
 cmake/Platform/Common/Install_common.cmake | 43 ++++++++++++++++++----
 cmake/SettingsRegistry.cmake               |  7 +---
 cmake/install/InstalledTarget.in           |  2 +
 4 files changed, 42 insertions(+), 12 deletions(-)

diff --git a/Code/Editor/CMakeLists.txt b/Code/Editor/CMakeLists.txt
index 5a846a267a..db6b8e958e 100644
--- a/Code/Editor/CMakeLists.txt
+++ b/Code/Editor/CMakeLists.txt
@@ -163,6 +163,8 @@ ly_add_target(
         editor_files.cmake
     PLATFORM_INCLUDE_FILES
         Platform/${PAL_PLATFORM_NAME}/editor_${PAL_PLATFORM_NAME_LOWERCASE}.cmake
+    TARGET_PROPERTIES
+        LY_INSTALL_GENERATE_RUN_TARGET TRUE
     BUILD_DEPENDENCIES
         PRIVATE
             3rdParty::Qt::Core
diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake
index 1ac59ee83f..8058fb5908 100644
--- a/cmake/Platform/Common/Install_common.cmake
+++ b/cmake/Platform/Common/Install_common.cmake
@@ -9,6 +9,15 @@ include(cmake/FileUtil.cmake)
 
 set(CMAKE_INSTALL_MESSAGE NEVER) # Simplify messages to reduce output noise
 
+define_property(TARGET PROPERTY LY_INSTALL_GENERATE_RUN_TARGET
+    BRIEF_DOCS "Defines if a \"RUN\" targets should be created when installing this target Gem"
+    FULL_DOCS [[
+        Property which is set on targets that should generate a "RUN"
+        target when installed. This \"RUN\" target helps to run the 
+        binary from the installed location directly from the IDE.
+    ]]
+)
+
 ly_set(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME Core)
 
 cmake_path(RELATIVE_PATH CMAKE_RUNTIME_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE runtime_output_directory)
@@ -105,15 +114,19 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
         set(NAMESPACE_PLACEHOLDER "")
         set(NAME_PLACEHOLDER ${TARGET_NAME})
     endif()
+    get_target_property(should_create_helper ${TARGET_NAME} LY_INSTALL_GENERATE_RUN_TARGET)
+    if(should_create_helper)
+        set(NAME_PLACEHOLDER ${NAME_PLACEHOLDER}.Imported)
+    endif()
 
     set(TARGET_TYPE_PLACEHOLDER "")
-    get_target_property(target_type ${NAME_PLACEHOLDER} TYPE)
+    get_target_property(target_type ${TARGET_NAME} TYPE)
     # Remove the _LIBRARY since we dont need to pass that to ly_add_targets
     string(REPLACE "_LIBRARY" "" TARGET_TYPE_PLACEHOLDER ${target_type})
     # For HEADER_ONLY libs we end up generating "INTERFACE" libraries, need to specify HEADERONLY instead
     string(REPLACE "INTERFACE" "HEADERONLY" TARGET_TYPE_PLACEHOLDER ${TARGET_TYPE_PLACEHOLDER})
     if(TARGET_TYPE_PLACEHOLDER STREQUAL "MODULE")
-        get_target_property(gem_module ${NAME_PLACEHOLDER} GEM_MODULE)
+        get_target_property(gem_module ${TARGET_NAME} GEM_MODULE)
         if(gem_module)
             set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE")
         endif()
@@ -146,7 +159,6 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
         unset(RUNTIME_DEPENDENCIES_PLACEHOLDER)
     endif()
 
-
     get_target_property(inteface_build_dependencies_props ${TARGET_NAME} INTERFACE_LINK_LIBRARIES)
     unset(INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER)
     if(inteface_build_dependencies_props)
@@ -170,6 +182,23 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
     list(REMOVE_DUPLICATES INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER)
     string(REPLACE ";" "\n" INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER "${INTERFACE_BUILD_DEPENDENCIES_PLACEHOLDER}")
 
+    # If the target is an executable/application, add a custom target so we can debug the target in project-centric workflow
+    if(should_create_helper)
+        string(REPLACE ".Imported" "" RUN_TARGET_NAME ${NAME_PLACEHOLDER})
+        set(target_types_with_debugging_helper EXECUTABLE APPLICATION)
+        if(NOT target_type IN_LIST target_types_with_debugging_helper)
+            message(FATAL_ERROR "Cannot generate a RUN target for ${TARGET_NAME}, type is ${target_type}")
+        endif()
+        set(TARGET_RUN_HELPER
+"add_custom_target(${RUN_TARGET_NAME})
+set_target_properties(${RUN_TARGET_NAME} PROPERTIES 
+    FOLDER \"CMakePredefinedTargets/SDK\"
+    VS_DEBUGGER_COMMAND \$>
+    VS_DEBUGGER_COMMAND_ARGUMENTS \"--project-path=\${LY_DEFAULT_PROJECT_PATH}\"
+)"
+)
+    endif()
+
     # Config file
     set(target_file_contents "# Generated by O3DE install\n\n")
     if(NOT target_type STREQUAL INTERFACE_LIBRARY)
@@ -182,13 +211,13 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
             set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$")
         elseif(target_type STREQUAL SHARED_LIBRARY)
             string(APPEND target_file_contents 
-"set_property(TARGET ${TARGET_NAME} 
+"set_property(TARGET ${NAME_PLACEHOLDER} 
     APPEND_STRING PROPERTY IMPORTED_IMPLIB
         $<$$:\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"$
 )
 ")
             string(APPEND target_file_contents 
-"set_property(TARGET ${TARGET_NAME} 
+"set_property(TARGET ${NAME_PLACEHOLDER} 
     PROPERTY IMPORTED_IMPLIB_$> 
         \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"
 )
@@ -200,11 +229,11 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar
 
         if(target_location)
             string(APPEND target_file_contents
-"set_property(TARGET ${TARGET_NAME}
+"set_property(TARGET ${NAME_PLACEHOLDER}
     APPEND_STRING PROPERTY IMPORTED_LOCATION
         $<$$:${target_location}$
 )
-set_property(TARGET ${TARGET_NAME}
+set_property(TARGET ${NAME_PLACEHOLDER}
     PROPERTY IMPORTED_LOCATION_$>
         ${target_location}
 )
diff --git a/cmake/SettingsRegistry.cmake b/cmake/SettingsRegistry.cmake
index 934bae4e30..a1e6de73f8 100644
--- a/cmake/SettingsRegistry.cmake
+++ b/cmake/SettingsRegistry.cmake
@@ -158,10 +158,6 @@ function(ly_delayed_generate_settings_registry)
                 message(FATAL_ERROR "Dependency ${gem_target} from ${target} does not exist")
             endif()
 
-            get_property(has_manually_added_dependencies TARGET ${gem_target} PROPERTY MANUALLY_ADDED_DEPENDENCIES SET)
-            get_target_property(target_type ${gem_target} TYPE)
-
-
             ly_get_gem_module_root(gem_module_root ${gem_target})
             file(RELATIVE_PATH gem_module_root_relative_to_engine_root ${LY_ROOT_FOLDER} ${gem_module_root})
 
@@ -179,7 +175,8 @@ function(ly_delayed_generate_settings_registry)
         list(JOIN target_gem_dependencies_names ",\n" target_gem_dependencies_names)
         string(CONFIGURE ${gems_json_template} gem_json @ONLY)
         get_target_property(is_imported ${target} IMPORTED)
-        if(is_imported)
+        get_target_property(target_type ${target} TYPE)
+        if(is_imported OR target_type STREQUAL UTILITY)
             unset(target_dir)
             foreach(conf IN LISTS CMAKE_CONFIGURATION_TYPES)
                 string(TOUPPER ${conf} UCONF)
diff --git a/cmake/install/InstalledTarget.in b/cmake/install/InstalledTarget.in
index 0503fd5f2b..a4f4fa4763 100644
--- a/cmake/install/InstalledTarget.in
+++ b/cmake/install/InstalledTarget.in
@@ -17,6 +17,8 @@ ly_add_target(
 @RUNTIME_DEPENDENCIES_PLACEHOLDER@
 )
 
+@TARGET_RUN_HELPER@
+
 set(configs @CMAKE_CONFIGURATION_TYPES@)
 foreach(config ${configs})
     include("@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL)

From 015424eb35cdb7b25abd07cdb4ee8ef77b47306e Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 11:51:21 -0700
Subject: [PATCH 024/205] Conversion to unicode, everything except
 StreamerConfiguration

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Framework/AzCore/AzCore/Debug/Trace.cpp  |  1 -
 Code/Framework/AzCore/AzCore/Debug/Trace.h    |  5 ++
 .../AzCore/AzCore/std/string/conversions.h    | 82 +++++++++++++++++++
 .../Common/Apple/AzCore/Debug/Trace_Apple.cpp |  1 +
 .../WinAPI/AzCore/Debug/Trace_WinAPI.cpp      | 19 +++--
 .../Linux/AzCore/Debug/Trace_Linux.cpp        |  4 +-
 .../Mac/AzCore/IPC/SharedMemory_Mac.cpp       |  2 +-
 .../Mac/AzCore/IPC/SharedMemory_Mac.h         |  1 -
 .../StreamerConfiguration_Windows.cpp         |  4 +-
 .../AzCore/IPC/SharedMemory_Windows.cpp       | 32 ++++----
 .../Windows/AzCore/IPC/SharedMemory_Windows.h |  3 -
 11 files changed, 121 insertions(+), 33 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/Debug/Trace.cpp b/Code/Framework/AzCore/AzCore/Debug/Trace.cpp
index 6d491c97b8..bd3b12a3b8 100644
--- a/Code/Framework/AzCore/AzCore/Debug/Trace.cpp
+++ b/Code/Framework/AzCore/AzCore/Debug/Trace.cpp
@@ -38,7 +38,6 @@ namespace AZ
             void DebugBreak();
 #endif
             void Terminate(int exitCode);
-            void OutputToDebugger(const char* window, const char* message);
         }
     }
 
diff --git a/Code/Framework/AzCore/AzCore/Debug/Trace.h b/Code/Framework/AzCore/AzCore/Debug/Trace.h
index a680cbdfed..bae074281c 100644
--- a/Code/Framework/AzCore/AzCore/Debug/Trace.h
+++ b/Code/Framework/AzCore/AzCore/Debug/Trace.h
@@ -15,6 +15,11 @@ namespace AZ
 {
     namespace Debug
     {
+        namespace Platform
+        {
+            void OutputToDebugger(const char* window, const char* message);
+        }
+    
         /// Global instance to the tracer.
         extern class Trace      g_tracer;
 
diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index 3e5a393cf8..4dc5bbd547 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -49,6 +49,25 @@ namespace AZStd
                 }
             }
 
+            template
+            static inline void to_string(AZStd::basic_fixed_string& dest, const wchar_t* first, const wchar_t* last)
+            {
+                if constexpr (Size == 2)
+                {
+                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest));
+                }
+                else if constexpr (Size == 4)
+                {
+                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest));
+                }
+                else
+                {
+                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
+                    using StringType = AZStd::basic_string;
+                    static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8");
+                }
+            }
+
             template
             static inline void to_wstring(AZStd::basic_string& dest, const char* first, const char* last)
             {
@@ -67,6 +86,25 @@ namespace AZStd
                     static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
                 }
             }
+
+            template
+            static inline void to_wstring(AZStd::basic_fixed_string& dest, const char* first, const char* last)
+            {
+                if constexpr (Size == 2)
+                {
+                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest));
+                }
+                else if constexpr (Size == 4)
+                {
+                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest));
+                }
+                else
+                {
+                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
+                    using StringType = AZStd::basic_string;
+                    static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
+                }
+            }
         };
     }
     // 21.5: numeric conversions
@@ -266,6 +304,28 @@ namespace AZStd
         return to_string(dest, src.c_str(), src.length());
     }
 
+    template
+    void to_string(AZStd::basic_fixed_string& dest, const wchar_t* str, size_t srcLen = 0)
+    {
+        dest.clear();
+
+        if (srcLen == 0)
+        {
+            srcLen = wcslen(str);
+        }
+
+        if (srcLen > 0)
+        {
+            Internal::WCharTPlatformConverter<>::to_string(dest, str, str + srcLen);
+        }
+    }
+
+    template
+    void to_string(AZStd::basic_fixed_string& dest, const AZStd::basic_fixed_string& src)
+    {
+        return to_string(dest, src.c_str(), src.length());
+    }
+
     template
     int stoi(const AZStd::basic_string& str, AZStd::size_t* idx = 0, int base = 10)
     {
@@ -384,6 +444,28 @@ namespace AZStd
         return to_wstring(dest, src.c_str(), src.length());
     }
 
+    template
+    void to_wstring(AZStd::basic_fixed_string& dest, const char* str, size_t strLen = 0)
+    {
+        dest.clear();
+
+        if (strLen == 0)
+        {
+            strLen = strlen(str);
+        }
+
+        if (strLen > 0)
+        {
+            Internal::WCharTPlatformConverter<>::to_wstring(dest, str, str + strLen);
+        }
+    }
+
+    template
+    void to_wstring(AZStd::basic_fixed_string& dest, const AZStd::basic_fixed_string& src)
+    {
+        return to_wstring(dest, src.c_str(), src.length());
+    }
+
     // Convert a range of chars to lower case
 #if defined(AZSTD_USE_OLD_RW_STL)
     template
diff --git a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp
index 62fe849c36..4ae25bfaf9 100644
--- a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp
+++ b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp
@@ -72,6 +72,7 @@ namespace AZ
 
             void OutputToDebugger(const char*, const char*)
             {
+                // std::cout << title << ": " << message;
             }
         }
     }
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp
index 143bd8f9d0..99ea10e4bc 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Debug/Trace_WinAPI.cpp
@@ -12,6 +12,8 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 
 #include 
 
@@ -22,7 +24,7 @@ namespace AZ
     LPTOP_LEVEL_EXCEPTION_FILTER g_previousExceptionHandler = nullptr;
 #endif
 
-    const int g_maxMessageLength = 4096;
+    constexpr int g_maxMessageLength = 4096;
 
     namespace Debug
     {
@@ -58,15 +60,18 @@ namespace AZ
                 TerminateProcess(GetCurrentProcess(), exitCode);
             }
 
-            void OutputToDebugger(const char* window, const char* message)
+            void OutputToDebugger([[maybe_unused]] const char* window, const char* message)
             {
-                AZ_UNUSED(window);
-                wchar_t messageW[g_maxMessageLength];
-                size_t numCharsConverted;
-                if (mbstowcs_s(&numCharsConverted, messageW, message, g_maxMessageLength - 1) == 0)
+                AZStd::fixed_wstring tmpW;
+                if(window)
                 {
-                    OutputDebugStringW(messageW);
+                    AZStd::to_wstring(tmpW, window);
+                    tmpW += L": ";
+                    OutputDebugStringW(tmpW.c_str());
+                    tmpW.clear();
                 }
+                AZStd::to_wstring(tmpW, message);
+                OutputDebugStringW(tmpW.c_str());
             }
         }
     }
diff --git a/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp b/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
index 3f9e475153..86c7e14ae6 100644
--- a/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
+++ b/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
@@ -7,6 +7,7 @@
  */
 
 #include 
+#include 
 
 namespace AZ
 {
@@ -14,8 +15,9 @@ namespace AZ
     {
         namespace Platform
         {
-            void OutputToDebugger(const char*, const char*)
+            void OutputToDebugger(const char* title, const char* message)
             {
+                // std::cout << title << ": " << message;
             }
         }
     }
diff --git a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
index 7f13ec442a..5555704040 100644
--- a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
+++ b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
@@ -29,7 +29,7 @@ namespace AZ
         return errno;
     }
 
-    void SharedMemory_Mac::ComposeMutexName(char* dest, size_t length, const char* name)
+    void ComposeMutexName(char* dest, size_t length, const char* name)
     {
         azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
 
diff --git a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.h b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.h
index 8e172d920f..c0d5d7c2e9 100644
--- a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.h
+++ b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.h
@@ -29,7 +29,6 @@ namespace AZ
 
         static int GetLastError();
 
-        void ComposeMutexName(char* dest, size_t length, const char* name);
         CreateResult Create(const char* name, unsigned int size, bool openIfCreated);
         bool Open(const char* name);
         void Close();
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp
index 35835c374c..0813d2d057 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp
@@ -290,7 +290,7 @@ namespace AZ::IO
     static bool CollectHardwareInfo(HardwareInformation& hardwareInfo, bool addAllDrives, bool reportHardware)
     {
         char drives[512];
-        if (::GetLogicalDriveStrings(sizeof(drives) - 1, drives))
+        if (::GetLogicalDriveStringsA(sizeof(drives) - 1, drives))
         {
             AZStd::unordered_map driveMappings;
             char* driveIt = drives;
@@ -318,7 +318,7 @@ namespace AZ::IO
                     deviceName += driveIt;
                     deviceName.erase(deviceName.length() - 1); // Erase the slash.
 
-                    HANDLE deviceHandle = ::CreateFile(
+                    HANDLE deviceHandle = ::CreateFileA(
                         deviceName.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
                     if (deviceHandle != INVALID_HANDLE_VALUE)
                     {
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
index 21b2a76ba0..20c126f7a8 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
@@ -11,6 +11,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace AZ
 {
@@ -21,16 +22,17 @@ namespace AZ
     {
     }
 
-    void SharedMemory_Windows::ComposeMutexName(char* dest, size_t length, const char* name)
+    void ComposeName(AZStd::fixed_wstring<256>& dest, const char* name, const wchar_t* suffix)
     {
-        azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
-        azsnprintf(dest, length, "%s_Mutex", name);
+        AZStd::to_wstring(dest, name);
+        dest += L"_";
+        dest += suffix;
     }
 
     SharedMemory_Common::CreateResult SharedMemory_Windows::Create(const char* name, unsigned int size, bool openIfCreated)
     {
-        char fullName[256];
-        ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name);
+        AZStd::fixed_wstring<256> fullName;
+        ComposeName(fullName, name, L"Mutex");
 
         // Security attributes
         SECURITY_ATTRIBUTES secAttr;
@@ -42,9 +44,7 @@ namespace AZ
         SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE);
 
         // Obtain global mutex
-        AZStd::wstring fullNameW;
-        AZStd::to_wstring(fullNameW, fullName);
-        m_globalMutex = CreateMutexW(&secAttr, FALSE, fullNameW.c_str());
+        m_globalMutex = CreateMutexW(&secAttr, FALSE, fullName.c_str());
         DWORD error = GetLastError();
         if (m_globalMutex == NULL || (error == ERROR_ALREADY_EXISTS && openIfCreated == false))
         {
@@ -53,8 +53,8 @@ namespace AZ
         }
 
         // Create the file mapping.
-        azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name);
-        m_mapHandle = CreateFileMappingW(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, size, fullNameW.c_str());
+        ComposeName(fullName, name, L"Data");
+        m_mapHandle = CreateFileMappingW(INVALID_HANDLE_VALUE, &secAttr, PAGE_READWRITE, 0, size, fullName.c_str());
         error = GetLastError();
         if (m_mapHandle == NULL || (error == ERROR_ALREADY_EXISTS && openIfCreated == false))
         {
@@ -67,12 +67,10 @@ namespace AZ
 
     bool SharedMemory_Windows::Open(const char* name)
     {
-        char fullName[256];
-        ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name);
-        AZStd::wstring fullNameW;
-        AZStd::to_wstring(fullNameW, fullName);
+        AZStd::fixed_wstring<256> fullName;
+        ComposeName(fullName, name, L"Mutex");
 
-        m_globalMutex = OpenMutex(SYNCHRONIZE, TRUE, fullNameW.c_str());
+        m_globalMutex = OpenMutex(SYNCHRONIZE, TRUE, fullName.c_str());
         AZ_Warning("AZSystem", m_globalMutex != NULL, "Failed to open OS mutex [%s]\n", m_name);
         if (m_globalMutex == NULL)
         {
@@ -80,8 +78,8 @@ namespace AZ
             return false;
         }
 
-        azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name);
-        m_mapHandle = OpenFileMapping(FILE_MAP_WRITE, false, fullNameW.c_str());
+        ComposeName(fullName, name, L"Data");
+        m_mapHandle = OpenFileMapping(FILE_MAP_WRITE, false, fullName.c_str());
         if (m_mapHandle == NULL)
         {
             AZ_TracePrintf("AZSystem", "OpenFileMapping %s failed with error %d\n", m_name, GetLastError());
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.h b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.h
index 7f206f5413..7b10b9163e 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.h
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.h
@@ -41,9 +41,6 @@ namespace AZ
         HANDLE m_mapHandle;
         HANDLE m_globalMutex;
         int m_lastLockResult;
-
-    private:
-        void ComposeMutexName(char* dest, size_t length, const char* name);
     };
 
     using SharedMemory_Platform = SharedMemory_Windows;

From 0ea11294abfcd69123143e7c48eef1fd23ba1ebe Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 12:29:06 -0700
Subject: [PATCH 025/205] fixes for crcfix

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Framework/Crcfix/crcfix.cpp | 87 +++++++++++++++++---------------
 1 file changed, 45 insertions(+), 42 deletions(-)

diff --git a/Code/Framework/Crcfix/crcfix.cpp b/Code/Framework/Crcfix/crcfix.cpp
index ce599e9a63..778b9e2185 100644
--- a/Code/Framework/Crcfix/crcfix.cpp
+++ b/Code/Framework/Crcfix/crcfix.cpp
@@ -12,6 +12,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -23,11 +24,11 @@ int g_longestFixTimeMs = 0;
 
 class Filename
 {
-    char    fullpath[MAX_PATH];
-    char    drive[_MAX_DRIVE];
-    char    dir[_MAX_DIR];
-    char    fname[_MAX_FNAME];
-    char    ext[_MAX_EXT];
+    wchar_t    fullpath[MAX_PATH];
+    wchar_t    drive[_MAX_DRIVE];
+    wchar_t    dir[_MAX_DIR];
+    wchar_t    fname[_MAX_FNAME];
+    wchar_t    ext[_MAX_EXT];
 
 public:
     Filename()
@@ -35,21 +36,21 @@ public:
         fullpath[0] = drive[0] = dir[0] = fname[0] = ext[0] = 0;
     }
 
-    Filename(const AZStd::string& filename)
+    Filename(const AZStd::wstring& filename)
     {
-        _splitpath(filename.c_str(), drive, dir, fname, ext);
-        strcpy(fullpath, filename.c_str());
+        _wsplitpath(filename.c_str(), drive, dir, fname, ext);
+        wcscpy(fullpath, filename.c_str());
     }
 
-    void        SetExt(const char* pExt)        { strcpy(ext, pExt); _makepath(fullpath, drive, dir, fname, pExt); }
-    const char* GetFullPath() const             { return fullpath; }
-    bool        Exists() const                  { return _access(fullpath, 0) == 0; }
-    bool        IsReadOnly() const              { return _access(fullpath, 6) == -1; }
-    bool        SetReadOnly() const             { return _chmod(fullpath, _S_IREAD) == 0; }
-    bool        SetWritable() const             { return _chmod(fullpath, _S_IREAD | _S_IWRITE) == 0; }
-    bool        Delete() const                  { return remove(fullpath) == 0; }
-    bool        Rename(const char* fn2) const   { return MoveFileEx(fullpath, fn2, MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING) == 0; }
-    bool        Copy(const char* dest) const    { return ::CopyFileA(fullpath, dest, FALSE) == TRUE; }
+    void        SetExt(const wchar_t* pExt)     { wcscpy(ext, pExt); _wmakepath(fullpath, drive, dir, fname, pExt); }
+    const wchar_t* GetFullPath() const          { return fullpath; }
+    bool        Exists() const                  { return _waccess(fullpath, 0) == 0; }
+    bool        IsReadOnly() const              { return _waccess(fullpath, 6) == -1; }
+    bool        SetReadOnly() const             { return _wchmod(fullpath, _S_IREAD) == 0; }
+    bool        SetWritable() const             { return _wchmod(fullpath, _S_IREAD | _S_IWRITE) == 0; }
+    bool        Delete() const                  { return _wremove(fullpath) == 0; }
+    bool        Rename(const wchar_t* fn2) const{ return MoveFileEx(fullpath, fn2, MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING) == 0; }
+    bool        Copy(const wchar_t* dest) const { return ::CopyFile(fullpath, dest, FALSE) == TRUE; }
 };
 
 class CRCfix
@@ -64,7 +65,7 @@ public:
     int     Fix(Filename srce);
 };
 
-void FixFiles(const AZStd::string& dir, const AZStd::string& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed)
+void FixFiles(const AZStd::wstring& dir, const AZStd::wstring& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed)
 {
     CRCfix fixer;
     WIN32_FIND_DATA wfd;
@@ -78,14 +79,14 @@ void FixFiles(const AZStd::string& dir, const AZStd::string& files, FILETIME* pL
             {
                 if (verbose)
                 {
-                    AZ_TracePrintf("CrcFix", "\tProcessing %s ...", wfd.cFileName);
+                    AZ_TracePrintf("CrcFix", "\tProcessing %ls ...", wfd.cFileName);
                 }
                 nFound++;
 
                 int n = 0;
                 if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0 && (!pLastRun || CompareFileTime(pLastRun, &wfd.ftLastWriteTime) <= 0))
                 {
-                    n = fixer.Fix(Filename(dir + "\\" + wfd.cFileName));
+                    n = fixer.Fix(Filename(dir + L"\\" + wfd.cFileName));
                     nProcessed++;
                 }
                 if (n < 0)
@@ -110,11 +111,11 @@ void FixFiles(const AZStd::string& dir, const AZStd::string& files, FILETIME* pL
     FindClose(hFind);
 }
 
-void FixDirectories(const AZStd::string& dirs, const AZStd::string& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed)
+void FixDirectories(const AZStd::wstring& dirs, const AZStd::wstring& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed)
 {
     if (verbose)
     {
-        AZ_TracePrintf("CrcFix", "Processing %s ...\n", dirs.c_str());
+        AZ_TracePrintf("CrcFix", "Processing %ls ...\n", dirs.c_str());
     }
 
     // do files
@@ -123,7 +124,7 @@ void FixDirectories(const AZStd::string& dirs, const AZStd::string& files, FILET
     // do folders
     WIN32_FIND_DATA wfd;
     HANDLE hFind;
-    hFind = FindFirstFile((dirs + "\\*").c_str(), &wfd);
+    hFind = FindFirstFile((dirs + L"\\*").c_str(), &wfd);
     if (hFind != INVALID_HANDLE_VALUE)
     {
         do
@@ -134,7 +135,7 @@ void FixDirectories(const AZStd::string& dirs, const AZStd::string& files, FILET
                 {
                     continue;
                 }
-                FixDirectories(AZStd::string(dirs + "\\" + wfd.cFileName), files, pLastRun, verbose, nFound, nProcessed, nFixed, nFailed);
+                FixDirectories(AZStd::wstring(dirs + L"\\" + wfd.cFileName), files, pLastRun, verbose, nFound, nProcessed, nFixed, nFailed);
             }
         } while (FindNextFile(hFind, &wfd));
     }
@@ -161,9 +162,9 @@ int main(int argc, char* argv[])
         char root[MAX_PATH];
         AZ::Utils::GetExecutableDirectory(root, MAX_PATH);
 
-        AZStd::vector entries;
+        AZStd::vector entries;
 
-        const char* logfilename = NULL;
+        AZStd::wstring logfilename;
         FILETIME    lastRun;
         FILETIME* pLastRun = NULL;
 
@@ -176,10 +177,12 @@ int main(int argc, char* argv[])
             {
                 continue;
             }
+            AZStd::wstring pArgW;
+            AZStd::to_wstring(pArgW, pArg);
             if (_strnicmp(pArg, "-log:", 5) == 0)
             {
-                logfilename = pArg + 5;
-                HANDLE hFile = CreateFile(logfilename, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
+                logfilename.assign(pArgW.begin() + 5, pArgW.end());
+                HANDLE hFile = CreateFile(logfilename.data(), 0, 0, NULL, OPEN_EXISTING, 0, NULL);
                 if (hFile != INVALID_HANDLE_VALUE)
                 {
                     pLastRun = &lastRun;
@@ -193,7 +196,7 @@ int main(int argc, char* argv[])
             }
             else
             {
-                entries.push_back(AZStd::string(pArg));
+                entries.emplace_back(AZStd::move(pArgW));
             }
         }
 
@@ -202,10 +205,10 @@ int main(int argc, char* argv[])
         int nProcessed = 0;
         int nFixed = 0;
         int nFailed = 0;
-        for (AZStd::vector::const_iterator iEntry = entries.begin(); iEntry != entries.end(); ++iEntry)
+        for (AZStd::vector::const_iterator iEntry = entries.begin(); iEntry != entries.end(); ++iEntry)
         {
-            AZStd::string entry = (iEntry->at(0) == '\\' || iEntry->find(":") != iEntry->npos) ? *iEntry : AZStd::string(root) + "\\" + *iEntry;
-            AZStd::string::size_type split = entry.find("*\\");
+            AZStd::wstring entry = (iEntry->at(0) == L'\\' || iEntry->find(L":") != iEntry->npos) ? *iEntry : AZStd::wstring(root) + L"\\" + *iEntry;
+            AZStd::wstring::size_type split = entry.find(L"*\\");
             bool doSubdirs = split != entry.npos;
             if (doSubdirs)
             {
@@ -213,7 +216,7 @@ int main(int argc, char* argv[])
             }
             else
             {
-                split = entry.rfind("\\");
+                split = entry.rfind(L"\\");
                 if (split == entry.npos)
                 {
                     split = 0;
@@ -223,9 +226,9 @@ int main(int argc, char* argv[])
         }
 
         // update timestamp
-        if (logfilename)
+        if (!logfilename.empty())
         {
-            HANDLE      hFile = CreateFile(logfilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
+            HANDLE      hFile = CreateFile(logfilename.data(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
             GetSystemTimeAsFileTime(&lastRun);
             SetFileTime(hFile, NULL, NULL, &lastRun);
             char log[1024];
@@ -383,12 +386,12 @@ int CRCfix::Fix(Filename srce)
 
     bool        changed = false;
     Filename    dest(srce);
-    dest.SetExt("xxx");
+    dest.SetExt(L"xxx");
 
     linenum = 0;
 
-    FILE* infile = fopen(srce.GetFullPath(), "r");
-    FILE* outfile = fopen(dest.GetFullPath(), "w");
+    FILE* infile = _wfopen(srce.GetFullPath(), L"r");
+    FILE* outfile = _wfopen(dest.GetFullPath(), L"w");
 
     if (!infile || !outfile)
     {
@@ -475,7 +478,7 @@ int CRCfix::Fix(Filename srce)
     if (changed)
     {
         Filename    backup(srce);
-        backup.SetExt("crcfix_old");
+        backup.SetExt(L"crcfix_old");
 
         if (backup.Exists())
         {
@@ -486,7 +489,7 @@ int CRCfix::Fix(Filename srce)
 
         if (!srce.Copy(backup.GetFullPath()))
         {
-            AZ_TracePrintf("CrcFix", "Failed to copy %s to %s\n", srce, backup);
+            AZ_TracePrintf("CrcFix", "Failed to copy %ls to %ls\n", srce, backup);
 
             int dt = static_cast(AZStd::chrono::milliseconds(AZStd::chrono::system_clock::now() - startTime).count());
             g_totalFixTimeMs += dt;
@@ -500,7 +503,7 @@ int CRCfix::Fix(Filename srce)
 
         if (!dest.Rename(srce.GetFullPath()))
         {
-            AZ_TracePrintf("CrcFix", "Failed to rename %s to %s\n", dest, srce);
+            AZ_TracePrintf("CrcFix", "Failed to rename %ls to %ls\n", dest, srce);
 
             int dt = static_cast(AZStd::chrono::milliseconds(AZStd::chrono::system_clock::now() - startTime).count());
             g_totalFixTimeMs += dt;
@@ -514,7 +517,7 @@ int CRCfix::Fix(Filename srce)
 
         if (!backup.Delete())
         {
-            AZ_TracePrintf("CrcFix", "Failed to delete %s\n", backup);
+            AZ_TracePrintf("CrcFix", "Failed to delete %ls\n", backup);
         }
     }
     else

From c5dcef180c38317bcb39ef1859ca33d299d62107 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:30:11 -0700
Subject: [PATCH 026/205] fixes/improvements to AzCore

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzCore/AzCore/std/string/conversions.h    | 47 +++++++++--
 .../AzCore/AzCore/std/string/utf8/unchecked.h | 79 +++++++++++++------
 .../WinAPI/AzCore/Utils/Utils_WinAPI.cpp      |  9 ++-
 Code/Framework/AzCore/Tests/AZStd/String.cpp  |  9 ---
 4 files changed, 104 insertions(+), 40 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index 4dc5bbd547..cb90881933 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -35,11 +35,11 @@ namespace AZStd
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else
                 {
@@ -54,11 +54,29 @@ namespace AZStd
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size());
+                }
+                else
+                {
+                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
+                    using StringType = AZStd::basic_string;
+                    static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8");
+                }
+            }
+
+            static inline void to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last)
+            {
+                if constexpr (Size == 2)
+                {
+                    Utf8::Unchecked::utf16to8(first, last, dest, destSize);
+                }
+                else if constexpr (Size == 4)
+                {
+                    Utf8::Unchecked::utf32to8(first, last, dest, destSize);
                 }
                 else
                 {
@@ -73,11 +91,11 @@ namespace AZStd
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else
                 {
@@ -92,11 +110,11 @@ namespace AZStd
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest));
+                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
                 else
                 {
@@ -326,6 +344,19 @@ namespace AZStd
         return to_string(dest, src.c_str(), src.length());
     }
 
+    inline void to_string(char* dest, size_t destSize, const wchar_t* str, size_t srcLen = 0)
+    {
+        if (srcLen == 0)
+        {
+            srcLen = wcslen(str) + 1;
+        }
+
+        if (srcLen > 0)
+        {
+            Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen + 1); // copy null terminator
+        }
+    }
+
     template
     int stoi(const AZStd::basic_string& str, AZStd::size_t* idx = 0, int base = 10)
     {
diff --git a/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h b/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
index 9608ff897b..cfc917ddc4 100644
--- a/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
+++ b/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
@@ -92,33 +92,58 @@ namespace Utf8::Unchecked
             return temp;
         }
 
-        static Iterator to_utf8_sequence(AZ::u32 cp, Iterator result)
+        static Iterator to_utf8_sequence(AZ::u32 cp, Iterator& result, size_t& resultMaxSize)
         {
             if (cp < 0x80)
             {
                 // one octet
+                resultMaxSize -= 1; // no need to check the calling function will exit the loop
                 *(result++) = static_cast(cp);
             }
             else if (cp < 0x800)
             {
                 // two octets
-                *(result++) = static_cast((cp >> 6) | 0xc0);
-                *(result++) = static_cast((cp & 0x3f) | 0x80);
+                if (resultMaxSize >= 2)
+                {
+                    *(result++) = static_cast((cp >> 6) | 0xc0);
+                    *(result++) = static_cast((cp & 0x3f) | 0x80);
+                    resultMaxSize -= 2;
+                }
+                else
+                {
+                    resultMaxSize = 0;
+                }
             }
             else if (cp < 0x10000)
             {
                 // three octets
-                *(result++) = static_cast((cp >> 12) | 0xe0);
-                *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80);
-                *(result++) = static_cast((cp & 0x3f) | 0x80);
+                if (resultMaxSize >= 3)
+                {
+                    *(result++) = static_cast((cp >> 12) | 0xe0);
+                    *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80);
+                    *(result++) = static_cast((cp & 0x3f) | 0x80);
+                    resultMaxSize -= 3;
+                }
+                else
+                {
+                    resultMaxSize = 0;
+                }
             }
             else
             {
                 // four octets
-                *(result++) = static_cast((cp >> 18) | 0xf0);
-                *(result++) = static_cast(((cp >> 12) & 0x3f) | 0x80);
-                *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80);
-                *(result++) = static_cast((cp & 0x3f) | 0x80);
+                if (resultMaxSize >= 4)
+                {
+                    *(result++) = static_cast((cp >> 18) | 0xf0);
+                    *(result++) = static_cast(((cp >> 12) & 0x3f) | 0x80);
+                    *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80);
+                    *(result++) = static_cast((cp & 0x3f) | 0x80);
+                    resultMaxSize -= 4;
+                }
+                else
+                {
+                    resultMaxSize = 0;
+                }
             }
             return result;
         }
@@ -155,9 +180,9 @@ namespace Utf8::Unchecked
     };
 
     template 
-    Utf8Iterator utf16to8(u16bit_iterator start, u16bit_iterator end, Utf8Iterator result)
+    Utf8Iterator utf16to8(u16bit_iterator start, u16bit_iterator end, Utf8Iterator result, size_t resultMaxSize)
     {
-        while (start != end)
+        while (start != end && resultMaxSize > 0)
         {
             AZ::u32 cp = Utf8::Internal::mask16(*start++);
             // Take care of surrogate pairs first
@@ -166,52 +191,62 @@ namespace Utf8::Unchecked
                 AZ::u32 trail_surrogate = Utf8::Internal::mask16(*start++);
                 cp = (cp << 10) + trail_surrogate + Internal::SURROGATE_OFFSET;
             }
-            octet_iterator::to_utf8_sequence(cp, result);
+            octet_iterator::to_utf8_sequence(cp, result, resultMaxSize);
         }
         return result;
     }
 
     template 
-    u16bit_iterator utf8to16(Utf8Iterator start, Utf8Iterator end, u16bit_iterator result)
+    u16bit_iterator utf8to16(Utf8Iterator start, Utf8Iterator end, u16bit_iterator result, size_t resultMaxSize)
     {
         octet_iterator utf8Start(start);
         octet_iterator utf8Last(end);
-        while (utf8Start != utf8Last)
+        while (utf8Start != utf8Last && resultMaxSize > 0)
         {
             AZ::u32 cp = *utf8Start++;
             if (cp > 0xffff)
             {
                 //make a surrogate pair
-                *result++ = static_cast((cp >> 10) + Internal::LEAD_OFFSET);
-                *result++ = static_cast((cp & 0x3ff) + Internal::TRAIL_SURROGATE_MIN);
+                if (resultMaxSize >= 2)
+                {
+                    *result++ = static_cast((cp >> 10) + Internal::LEAD_OFFSET);
+                    *result++ = static_cast((cp & 0x3ff) + Internal::TRAIL_SURROGATE_MIN);
+                    resultMaxSize -= 2;
+                }
+                else
+                {
+                    resultMaxSize = 0;
+                }
             }
             else
             {
                 *result++ = static_cast(cp);
+                resultMaxSize -= 1;
             }
         }
         return result;
     }
 
     template 
-    Utf8Iterator utf32to8(u32bit_iterator start, u32bit_iterator end, Utf8Iterator result)
+    Utf8Iterator utf32to8(u32bit_iterator start, u32bit_iterator end, Utf8Iterator result, size_t resultMaxSize)
     {
-        while (start != end)
+        while (start != end && resultMaxSize > 0)
         {
-            octet_iterator::to_utf8_sequence(*start++, result);
+            octet_iterator::to_utf8_sequence(*start++, result, resultMaxSize);
         }
 
         return result;
     }
 
     template 
-    u32bit_iterator utf8to32(Utf8Iterator start, Utf8Iterator end, u32bit_iterator result)
+    u32bit_iterator utf8to32(Utf8Iterator start, Utf8Iterator end, u32bit_iterator result, size_t resultMaxSize)
     {
         octet_iterator utf8Start(start);
         octet_iterator utf8Last(end);
-        while (utf8Start != utf8Last)
+        while (utf8Start != utf8Last && resultMaxSize > 0)
         {
             *result++ = *utf8Start++;
+            --resultMaxSize;
         }
 
         return result;
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
index 66257735b4..c57f2b31f6 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
@@ -11,6 +11,7 @@
 #include 
 #include 
 #include 
+#include 
 
 #include 
 
@@ -29,7 +30,9 @@ namespace AZ
             result.m_pathIncludesFilename = true;
             // Platform specific get exe path: http://stackoverflow.com/a/1024937
             // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
-            const DWORD pathLen = GetModuleFileNameA(nullptr, exeStorageBuffer, static_cast(exeStorageSize));
+            AZStd::wstring pathBuffer;
+            pathBuffer.resize(exeStorageSize);
+            const DWORD pathLen = GetModuleFileName(nullptr, pathBuffer.data(), static_cast(exeStorageSize));
             const DWORD errorCode = GetLastError();
             if (pathLen == exeStorageSize && errorCode == ERROR_INSUFFICIENT_BUFFER)
             {
@@ -39,6 +42,10 @@ namespace AZ
             {
                 result.m_pathStored = ExecutablePathResult::GeneralError;
             }
+            else
+            {
+                AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBuffer.c_str());
+            }
 
             return result;
         }
diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp
index 0e6ea4727c..2d2602e456 100644
--- a/Code/Framework/AzCore/Tests/AZStd/String.cpp
+++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp
@@ -628,10 +628,6 @@ namespace UnitTest
         }
     }
 
-#if defined(AZ_COMPILER_MSVC)
-#   pragma warning(push)
-#   pragma warning( disable: 4428 )   // universal-character-name encountered in source
-#endif // AZ_COMPILER_MSVC
     TEST_F(String, Algorithms)
     {
         string str = string::format("%s %d", "BlaBla", 5);
@@ -1114,11 +1110,6 @@ namespace UnitTest
         EXPECT_FALSE(other2.Valid());
     }
 
-    // StringAlgorithmTest-End
-#if defined(AZ_COMPILER_MSVC)
-#   pragma warning(pop)
-#endif // AZ_COMPILER_MSVC
-
     TEST_F(String, ConstString)
     {
         string_view cstr1;

From 63445e107a0da2584475b16539d2499f54153909 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:33:50 -0700
Subject: [PATCH 027/205] fxies for AzFramework

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Network/AssetProcessorConnection.cpp      |  2 +-
 .../Android/platform_android_files.cmake      |  1 -
 .../AssetProcessorConnection_Default.cpp      | 24 ------------------
 .../AzFramework/IO/LocalFileIO_WinAPI.cpp     | 17 ++++++++-----
 .../AssetProcessorConnection_WinAPI.cpp       | 25 -------------------
 .../Platform/Linux/platform_linux_files.cmake |  1 -
 .../Platform/Mac/platform_mac_files.cmake     |  1 -
 .../AssetSystemComponentHelper_Windows.cpp    | 12 ++++++---
 .../TargetManagementComponent_Windows.cpp     |  9 ++++---
 .../Windowing/NativeWindow_Windows.cpp        | 17 ++++++++-----
 .../Windows/platform_windows_files.cmake      |  1 -
 .../Platform/iOS/platform_ios_files.cmake     |  1 -
 12 files changed, 36 insertions(+), 75 deletions(-)
 delete mode 100644 Code/Framework/AzFramework/Platform/Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
 delete mode 100644 Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp

diff --git a/Code/Framework/AzFramework/AzFramework/Network/AssetProcessorConnection.cpp b/Code/Framework/AzFramework/AzFramework/Network/AssetProcessorConnection.cpp
index a65a3079a0..ebea29c2d9 100644
--- a/Code/Framework/AzFramework/AzFramework/Network/AssetProcessorConnection.cpp
+++ b/Code/Framework/AzFramework/AzFramework/Network/AssetProcessorConnection.cpp
@@ -136,7 +136,7 @@ namespace AzFramework
             AZStd::array buffer;
             azsnprintf(buffer.data(), buffer.size(), "(%p/%#" PRIxPTR "): %s\n", this, numericThreadId, msg.data());
 
-            Platform::DebugOutput(buffer.data());
+            AZ::Debug::Platform::OutputToDebugger("AssetProcessorConnection", buffer.data());
 #else // ASSETPROCESORCONNECTION_VERBOSE_LOGGING is not defined
             (void)format;
 #endif
diff --git a/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake b/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake
index 35b5a10151..c220bc1154 100644
--- a/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake
+++ b/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake
@@ -14,7 +14,6 @@ set(FILES
     AzFramework/Application/Application_Android.cpp
     ../Common/Unimplemented/AzFramework/Asset/AssetSystemComponentHelper_Unimplemented.cpp
     AzFramework/IO/LocalFileIO_Android.cpp
-    ../Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     ../Common/Default/AzFramework/TargetManagement/TargetManagementComponent_Default.cpp
     AzFramework/Windowing/NativeWindow_Android.cpp
diff --git a/Code/Framework/AzFramework/Platform/Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp b/Code/Framework/AzFramework/Platform/Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
deleted file mode 100644
index 5bc020a1d6..0000000000
--- a/Code/Framework/AzFramework/Platform/Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-#include 
-
-namespace AzFramework
-{
-    namespace AssetSystem
-    {
-        namespace Platform
-        {
-            void DebugOutput(const char* message)
-            {
-                fputs("AssetProcessorConnection:", stdout);
-                fputs(message, stdout);
-            }
-        }
-    }
-}
diff --git a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
index 4c7d84b511..58afebfb90 100644
--- a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
+++ b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
@@ -9,6 +9,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace AZ
 {
@@ -33,7 +34,7 @@ namespace AZ
             char resolvedPath[AZ_MAX_PATH_LEN];
             ResolvePath(filePath, resolvedPath, AZ_MAX_PATH_LEN);
 
-            AZ::OSString searchPattern;
+            AZStd::string searchPattern;
             if ((resolvedPath[0] == 0) || (resolvedPath[1] == 0))
             {
                 return ResultCode::Error; // not a valid path.
@@ -54,7 +55,9 @@ namespace AZ
             searchPattern += "\\*.*"; // use our own filtering function!
 
             WIN32_FIND_DATA findData;
-            HANDLE hFind = FindFirstFile(searchPattern.c_str(), &findData);
+            AZStd::wstring searchPatternW;
+            AZStd::to_wstring(searchPatternW, searchPattern.c_str());
+            HANDLE hFind = FindFirstFileW(searchPatternW.c_str(), &findData);
 
             if (hFind != INVALID_HANDLE_VALUE)
             {
@@ -63,15 +66,17 @@ namespace AZ
                 char tempBuffer[AZ_MAX_PATH_LEN];
                 do
                 {
-                    AZStd::string_view filenameView = findData.cFileName;
+                    AZStd::string fileName;
+                    AZStd::to_string(fileName, findData.cFileName);
+                    AZStd::string_view filenameView = fileName;
                     // Skip over the current directory and parent directory paths to prevent infinite recursion
-                    if (filenameView == "." || filenameView == ".." || !NameMatchesFilter(findData.cFileName, filter))
+                    if (filenameView == "." || filenameView == ".." || !NameMatchesFilter(fileName.c_str(), filter))
                     {
                         continue;
                     }
 
-                    AZ::OSString foundFilePath = CheckForTrailingSlash(resolvedPath);
-                    foundFilePath += findData.cFileName;
+                    AZStd::string foundFilePath = CheckForTrailingSlash(resolvedPath);
+                    foundFilePath += fileName;
                     AZStd::replace(foundFilePath.begin(), foundFilePath.end(), '\\', '/');
 
                     // if aliased, de-alias!
diff --git a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp
deleted file mode 100644
index a02e697df6..0000000000
--- a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-#include 
-#include 
-
-namespace AzFramework
-{
-    namespace AssetSystem
-    {
-        namespace Platform
-        {
-            void DebugOutput(const char* message)
-            {
-                OutputDebugString("AssetProcessorConnection:");
-                OutputDebugString(message);
-            }
-        }
-    }
-}
diff --git a/Code/Framework/AzFramework/Platform/Linux/platform_linux_files.cmake b/Code/Framework/AzFramework/Platform/Linux/platform_linux_files.cmake
index 60b16938a1..21201d954d 100644
--- a/Code/Framework/AzFramework/Platform/Linux/platform_linux_files.cmake
+++ b/Code/Framework/AzFramework/Platform/Linux/platform_linux_files.cmake
@@ -17,7 +17,6 @@ set(FILES
     AzFramework/Process/ProcessCommon.h
     AzFramework/Process/ProcessCommunicator_Linux.cpp
     ../Common/UnixLike/AzFramework/IO/LocalFileIO_UnixLike.cpp
-    ../Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     ../Common/Default/AzFramework/TargetManagement/TargetManagementComponent_Default.cpp
     AzFramework/Windowing/NativeWindow_Linux.cpp
diff --git a/Code/Framework/AzFramework/Platform/Mac/platform_mac_files.cmake b/Code/Framework/AzFramework/Platform/Mac/platform_mac_files.cmake
index c428160892..78f11a65da 100644
--- a/Code/Framework/AzFramework/Platform/Mac/platform_mac_files.cmake
+++ b/Code/Framework/AzFramework/Platform/Mac/platform_mac_files.cmake
@@ -17,7 +17,6 @@ set(FILES
     AzFramework/Process/ProcessCommon.h
     AzFramework/Process/ProcessCommunicator_Mac.cpp
     ../Common/UnixLike/AzFramework/IO/LocalFileIO_UnixLike.cpp
-    ../Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     AzFramework/TargetManagement/TargetManagementComponent_Mac.cpp
     AzFramework/Windowing/NativeWindow_Mac.mm
diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp
index 4b685b25a3..a3782ae081 100644
--- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp
+++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Asset/AssetSystemComponentHelper_Windows.cpp
@@ -48,10 +48,10 @@ namespace AzFramework::AssetSystem::Platform
                     // Get the first module, because that will be the executable
                     if (EnumProcessModules(processHandle, &moduleHandle, sizeof(moduleHandle), &bytesNeededForAllProcessModules))
                     {
-                        char processName[4096] = TEXT("");
-                        if (GetModuleBaseNameA(processHandle, moduleHandle, processName, AZ_ARRAY_SIZE(processName)) > 0)
+                        wchar_t processName[4096] = L"";
+                        if (GetModuleBaseName(processHandle, moduleHandle, processName, AZ_ARRAY_SIZE(processName)) > 0)
                         {
-                            if (azstricmp(processName, "AssetProcessor") == 0)
+                            if (azwcsicmp(processName, L"AssetProcessor") == 0)
                             {
                                 AllowSetForegroundWindow(processId);
                             }
@@ -126,7 +126,11 @@ namespace AzFramework::AssetSystem::Platform
         si.wShowWindow = SW_MINIMIZE;
         PROCESS_INFORMATION pi;
 
-        bool createResult = ::CreateProcessA(nullptr, fullLaunchCommand.data(), nullptr, nullptr, FALSE, 0, nullptr, AZ::IO::FixedMaxPathString{ executableDirectory }.c_str(), &si, &pi) != 0;
+        AZStd::wstring fullLaunchCommandW;
+        AZStd::to_wstring(fullLaunchCommandW, fullLaunchCommand.c_str());
+        AZStd::wstring execututableDirectoryW;
+        AZStd::to_wstring(execututableDirectoryW, executableDirectory.data());
+        bool createResult = ::CreateProcessW(nullptr, fullLaunchCommandW.data(), nullptr, nullptr, FALSE, 0, nullptr, execututableDirectoryW.c_str(), &si, &pi) != 0;
 
         if (ap_tether_lifetime && apJob && createResult)
         {
diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp
index fbfb3778cb..e168968278 100644
--- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp
+++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp
@@ -10,6 +10,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace AzFramework
 {
@@ -35,12 +36,12 @@ namespace AzFramework
         AZStd::string GetNeighborhoodName()
         {
             AZStd::string neighborhoodName;
-            
-            char localhost[MAX_COMPUTERNAME_LENGTH + 1];
+
+            wchar_t localhost[MAX_COMPUTERNAME_LENGTH + 1];
             DWORD len = AZ_ARRAY_SIZE(localhost);
-            if (GetComputerName(localhost, &len))
+            if (GetComputerNameW(localhost, &len))
             {
-                neighborhoodName = localhost;
+                AZStd::to_string(neighborhoodName, localhost);
             }
 
             return neighborhoodName;
diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp
index 0047929120..22a293891c 100644
--- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp
+++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp
@@ -11,6 +11,7 @@
 
 #include 
 #include 
+#include 
 
 namespace AzFramework
 {
@@ -41,7 +42,7 @@ namespace AzFramework
         static DWORD ConvertToWin32WindowStyleMask(const WindowStyleMasks& styleMasks);
         static LRESULT CALLBACK WindowCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
 
-        static const char* s_defaultClassName;
+        static const wchar_t* s_defaultClassName;
 
         void WindowSizeChanged(const uint32_t width, const uint32_t height);
 
@@ -57,7 +58,7 @@ namespace AzFramework
         GetDpiForWindowType* m_getDpiFunction = nullptr;
     };
 
-    const char* NativeWindowImpl_Win32::s_defaultClassName = "O3DEWin32Class";
+    const wchar_t* NativeWindowImpl_Win32::s_defaultClassName = L"O3DEWin32Class";
 
     NativeWindow::Implementation* NativeWindow::Implementation::Create()
     {
@@ -88,7 +89,7 @@ namespace AzFramework
 
         // register window class if it does not exist
         WNDCLASSEX windowClass;
-        if (GetClassInfoEx(hInstance, s_defaultClassName, &windowClass) == false)
+        if (GetClassInfoExW(hInstance, s_defaultClassName, &windowClass) == false)
         {
             windowClass.cbSize = sizeof(WNDCLASSEX);
             windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
@@ -127,8 +128,10 @@ namespace AzFramework
         m_height = geometry.m_height;
 
         // create main window
-        m_win32Handle = CreateWindow(
-            s_defaultClassName, title.c_str(),
+        AZStd::wstring titleW;
+        AZStd::to_wstring(titleW, title);
+        m_win32Handle = CreateWindowW(
+            s_defaultClassName, titleW.c_str(),
             windowStyle,
             geometry.m_posX, geometry.m_posY, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top,
             NULL, NULL, hInstance, NULL);
@@ -175,7 +178,9 @@ namespace AzFramework
 
     void NativeWindowImpl_Win32::SetWindowTitle(const AZStd::string& title)
     {
-        SetWindowText(m_win32Handle, title.c_str());
+        AZStd::wstring titleW;
+        AZStd::to_wstring(titleW, title);
+        SetWindowTextW(m_win32Handle, titleW.c_str());
     }
 
     DWORD NativeWindowImpl_Win32::ConvertToWin32WindowStyleMask(const WindowStyleMasks& styleMasks)
diff --git a/Code/Framework/AzFramework/Platform/Windows/platform_windows_files.cmake b/Code/Framework/AzFramework/Platform/Windows/platform_windows_files.cmake
index af43234bd0..b8f5b5f841 100644
--- a/Code/Framework/AzFramework/Platform/Windows/platform_windows_files.cmake
+++ b/Code/Framework/AzFramework/Platform/Windows/platform_windows_files.cmake
@@ -18,7 +18,6 @@ set(FILES
     AzFramework/Process/ProcessCommunicator_Win.cpp
     ../Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
     AzFramework/IO/LocalFileIO_Windows.cpp
-    ../Common/WinAPI/AzFramework/Network/AssetProcessorConnection_WinAPI.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     AzFramework/TargetManagement/TargetManagementComponent_Windows.cpp
     AzFramework/Windowing/NativeWindow_Windows.cpp
diff --git a/Code/Framework/AzFramework/Platform/iOS/platform_ios_files.cmake b/Code/Framework/AzFramework/Platform/iOS/platform_ios_files.cmake
index f47eb136be..7745f43ec9 100644
--- a/Code/Framework/AzFramework/Platform/iOS/platform_ios_files.cmake
+++ b/Code/Framework/AzFramework/Platform/iOS/platform_ios_files.cmake
@@ -14,7 +14,6 @@ set(FILES
     AzFramework/Application/Application_iOS.mm
     ../Common/Unimplemented/AzFramework/Asset/AssetSystemComponentHelper_Unimplemented.cpp
     ../Common/UnixLike/AzFramework/IO/LocalFileIO_UnixLike.cpp
-    ../Common/Default/AzFramework/Network/AssetProcessorConnection_Default.cpp
     ../Common/Unimplemented/AzFramework/StreamingInstall/StreamingInstall_Unimplemented.cpp
     ../Common/Default/AzFramework/TargetManagement/TargetManagementComponent_Default.cpp
     AzFramework/Windowing/NativeWindow_ios.mm

From 3f6335dc324d0b80ec730af155026fbf97d2f8a4 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:34:14 -0700
Subject: [PATCH 028/205] Fixes for AzQtComponents

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzQtComponents/AzQtComponents/Gallery/main.cpp       | 9 ++-------
 1 file changed, 2 insertions(+), 7 deletions(-)

diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
index 51ca2b349f..2a4a29ffe6 100644
--- a/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
+++ b/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp
@@ -40,13 +40,8 @@ const QString g_ui_1_0_SettingKey = QStringLiteral("useUI_1_0");
 
 static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message)
 {
-#ifdef Q_OS_WIN
-    OutputDebugStringW(L"Qt: ");
-    OutputDebugStringW(reinterpret_cast(message.utf16()));
-    OutputDebugStringW(L"\n");
-#else
-    std::wcerr << L"Qt: " << message.toStdWString() << std::endl;
-#endif
+    AZ::Debug::Platform::OutputToDebugger("Qt", message.toStdString().c_str());
+    AZ::Debug::Platform::OutputToDebugger(nullptr, "\n");
 }
 
 /*

From 1b4c06d03dbe44243cbf1dc03005aad85b0e36f0 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:38:46 -0700
Subject: [PATCH 029/205] other Framework fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzTest/AzTest/Platform/Windows/Platform_Windows.cpp        | 3 ++-
 .../Platform/Windows/GridMate/Session/LANSession_Windows.cpp   | 2 +-
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/Code/Framework/AzTest/AzTest/Platform/Windows/Platform_Windows.cpp b/Code/Framework/AzTest/AzTest/Platform/Windows/Platform_Windows.cpp
index 08e86fdc16..777ba66c6d 100644
--- a/Code/Framework/AzTest/AzTest/Platform/Windows/Platform_Windows.cpp
+++ b/Code/Framework/AzTest/AzTest/Platform/Windows/Platform_Windows.cpp
@@ -9,6 +9,7 @@
 #include 
 #include 
 #include 
+#include 
 
 //-------------------------------------------------------------------------------------------------
 class ModuleHandle
@@ -151,7 +152,7 @@ namespace AZ
             va_start(mark, format);
             azvsnprintf(message, MAX_PRINT_MSG, format, mark);
             va_end(mark);
-            OutputDebugString(message);
+            AZ::Debug::Platform::OutputToDebugger(nullptr, message);
         }
 
         AZ::EnvironmentInstance Platform::GetTestRunnerEnvironment()
diff --git a/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp b/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
index 4bf038a2cf..59a1c65781 100644
--- a/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
+++ b/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
@@ -21,7 +21,7 @@ namespace GridMate
 
             char procPath[256];
             char procName[256];
-            DWORD ret = GetModuleFileName(NULL, procPath, 256);
+            DWORD ret = GetModuleFileNameA(NULL, procPath, 256);
             if (ret > 0)
             {
                 ::_splitpath_s(procPath, 0, 0, 0, 0, procName, 256, 0, 0);

From 41ad6d7b7a9326f23c29abf6cef8fb3e442f1d05 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 17:39:02 -0700
Subject: [PATCH 030/205] Code/Legacy cleanup

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Legacy/CryCommon/platform_impl.cpp       |  38 ++--
 Code/Legacy/CrySystem/ConsoleHelpGen.cpp      |   6 +-
 Code/Legacy/CrySystem/DebugCallStack.cpp      |  19 +-
 Code/Legacy/CrySystem/IDebugCallStack.cpp     |   2 +-
 .../CrySystem/LocalizedStringManager.cpp      |  31 ++-
 Code/Legacy/CrySystem/Log.cpp                 |  21 +--
 Code/Legacy/CrySystem/System.cpp              |  18 +-
 Code/Legacy/CrySystem/SystemCFG.cpp           |  42 +++--
 Code/Legacy/CrySystem/SystemCFG.h             |   6 -
 Code/Legacy/CrySystem/SystemInit.cpp          |  57 +++---
 Code/Legacy/CrySystem/SystemWin32.cpp         |  40 ++--
 .../CrySystem/WindowsErrorReporting.cpp       |   4 +-
 Code/Legacy/CrySystem/XConsole.cpp            | 177 ++++++++----------
 Code/Legacy/CrySystem/XConsole.h              |  18 +-
 Code/Legacy/CrySystem/XConsoleVariable.cpp    |  32 ++--
 Code/Legacy/CrySystem/XConsoleVariable.h      |  52 +++--
 16 files changed, 267 insertions(+), 296 deletions(-)

diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp
index 54bf38aaa0..6badd2fe1e 100644
--- a/Code/Legacy/CryCommon/platform_impl.cpp
+++ b/Code/Legacy/CryCommon/platform_impl.cpp
@@ -10,13 +10,14 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 
 #include 
 #include 
 #include 
 #include 
+#include 
+#include 
 
 // Section dictionary
 #if defined(AZ_RESTRICTED_PLATFORM)
@@ -245,18 +246,23 @@ int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const ch
     {
         return 0;
     }
-    return MessageBox(NULL, lpText, lpCaption, uType);
+    AZStd::wstring lpTextW;
+    AZStd::to_wstring(lpTextW, lpText);
+    AZStd::wstring lpCaptionW;
+    AZStd::to_wstring(lpCaptionW, lpCaption);
+    return MessageBoxW(NULL, lpTextW.c_str(), lpCaptionW.c_str(), uType);
 #else
     return 0;
 #endif
 }
 
 // Initializes root folder of the game, optionally returns exe and path name.
-void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], [[maybe_unused]] uint nRootSize)
+void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], uint nRootSize)
 {
-    WCHAR szPath[_MAX_PATH];
-    size_t nLen = GetModuleFileNameW(GetModuleHandle(NULL), szPath, _MAX_PATH);
-    assert(nLen < _MAX_PATH && "The path to the current executable exceeds the expected length");
+    char szPath[_MAX_PATH];
+    AZ::Utils::GetExecutablePathReturnType ret = AZ::Utils::GetExecutablePath(szPath, _MAX_PATH);
+    AZ_Assert(ret.m_pathStored == AZ::Utils::ExecutablePathResult::Success, "The path to the current executable exceeds the expected length");
+    const size_t nLen = strnlen(szPath, _MAX_PATH);
 
     // Find path above exe name and deepest folder.
     bool firstIteration = true;
@@ -271,25 +277,27 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], [[ma
                 // Return exe path
                 if (szExeRootName)
                 {
-                    Unicode::Convert(szExeRootName, n+1, szPath);
+                    azstrncpy(szExeRootName, nRootSize, szPath + n + 1, nLen - n - 1);
                 }
 
                 // Return exe name
                 if (szExeFileName)
                 {
-                    Unicode::Convert(szExeFileName, nExeSize, szPath + n);
+                    azstrncpy(szExeFileName, nExeSize, szPath + n, nLen - n);
                 }
                 firstIteration = false;
             }
             // Check if the engineroot exists
-            wcscat_s(szPath, L"\\engine.json");
+            azstrcat(szPath, "\\engine.json");
             WIN32_FILE_ATTRIBUTE_DATA data;
-            BOOL res = GetFileAttributesExW(szPath, GetFileExInfoStandard, &data);
+            AZStd::wstring szPathW;
+            AZStd::to_wstring(szPathW, szPath);
+            BOOL res = GetFileAttributesExW(szPathW.c_str(), GetFileExInfoStandard, &data);
             if (res != 0 && data.dwFileAttributes != INVALID_FILE_ATTRIBUTES)
             {
                 // Found file
                 szPath[n] = 0;
-                SetCurrentDirectoryW(szPath);
+                SetCurrentDirectoryW(szPathW.c_str());
                 break;
             }
         }
@@ -423,7 +431,9 @@ uint32 CryGetFileAttributes(const char* lpFileName)
 #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
 #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
 #else
-    res = GetFileAttributesEx(lpFileName, GetFileExInfoStandard, &data);
+    AZStd::wstring lpFileNameW;
+    AZStd::to_wstring(lpFileNameW, lpFileName);
+    res = GetFileAttributesExW(lpFileNameW.c_str(), GetFileExInfoStandard, &data);
 #endif
     return res ? data.dwFileAttributes : -1;
 }
@@ -438,7 +448,9 @@ bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes)
 #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
 #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
 #else
-    return SetFileAttributes(lpFileName, dwFileAttributes) != 0;
+    AZStd::wstring lpFileNameW;
+    AZStd::to_wstring(lpFileNameW, lpFileName);
+    return SetFileAttributes(lpFileNameW.c_str(), dwFileAttributes) != 0;
 #endif
 }
 
diff --git a/Code/Legacy/CrySystem/ConsoleHelpGen.cpp b/Code/Legacy/CrySystem/ConsoleHelpGen.cpp
index ff86577258..661487a299 100644
--- a/Code/Legacy/CrySystem/ConsoleHelpGen.cpp
+++ b/Code/Legacy/CrySystem/ConsoleHelpGen.cpp
@@ -6,13 +6,13 @@
  *
  */
 
+#if defined(WIN32) || defined(WIN64)
 
 #include "CrySystem_precompiled.h"
 
-#if defined(WIN32) || defined(WIN64)
-
 #include "ConsoleHelpGen.h"
 #include "System.h"
+#include 
 
 
 
@@ -132,7 +132,7 @@ void CConsoleHelpGen::LogVersion(FILE* f) const
     char s[1024];
 
     {
-        GetModuleFileName(NULL, s, sizeof(s));
+        AZ::Utils::GetExecutablePath(s, 1024);
 
         char fdir[_MAX_PATH];
         char fdrive[_MAX_PATH];
diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp
index c5d932429c..289d4070ff 100644
--- a/Code/Legacy/CrySystem/DebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/DebugCallStack.cpp
@@ -18,6 +18,7 @@
 
 #include 
 #include 
+#include 
 
 #define VS_VERSION_INFO                 1
 #define IDD_CRITICAL_ERROR              101
@@ -400,7 +401,11 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
             timeStamp = tempBuffer;
 
             AZStd::string backupFileName = backupPath + timeStamp + " error.log";
-            CopyFile(fileName.c_str(), backupFileName.c_str(), true);
+            AZStd::wstring fileNameW;
+            AZStd::to_wstring(fileNameW, fileName.c_str());
+            AZStd::wstring backupFileNameW;
+            AZStd::to_wstring(backupFileNameW, backupFileName.c_str());
+            CopyFileW(fileNameW.c_str(), backupFileNameW.c_str(), true);
         }
     }
 
@@ -594,7 +599,11 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
                 }
 
                 AZStd::string backupFileName = backupPath + timeStamp + " error.dmp";
-                CopyFile(fileName.c_str(), backupFileName.c_str(), true);
+                AZStd::wstring fileNameW;
+                AZStd::to_wstring(fileNameW, fileName.c_str());
+                AZStd::wstring backupFileNameW;
+                AZStd::to_wstring(backupFileNameW, backupFileName.c_str());
+                CopyFileW(fileNameW.c_str(), backupFileNameW.c_str(), true);
             }
 
             CryEngineExceptionFilterMiniDump(pex, fileName.c_str(), mdumpValue);
@@ -635,11 +644,11 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         {
             if (SaveCurrentLevel())
             {
-                MessageBox(NULL, "Level has been successfully saved!\r\nPress Ok to terminate Editor.", "Save", MB_OK);
+                MessageBoxW(NULL, L"Level has been successfully saved!\r\nPress Ok to terminate Editor.", L"Save", MB_OK);
             }
             else
             {
-                MessageBox(NULL, "Error saving level.\r\nPress Ok to terminate Editor.", "Save", MB_OK | MB_ICONWARNING);
+                MessageBoxW(NULL, L"Error saving level.\r\nPress Ok to terminate Editor.", L"Save", MB_OK | MB_ICONWARNING);
             }
         }
     }
@@ -855,7 +864,7 @@ void DebugCallStack::GetProcNameForAddr(void* addr, AZStd::string& procName, voi
 AZStd::string DebugCallStack::GetCurrentFilename()
 {
     char fullpath[MAX_PATH_LENGTH + 1];
-    GetModuleFileName(NULL, fullpath, MAX_PATH_LENGTH);
+    AZ::Utils::GetExecutablePath(fullpath, MAX_PATH_LENGTH);
     return fullpath;
 }
 
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp
index ff43f6e56f..bee43b237b 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp
@@ -187,7 +187,7 @@ AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option")
     azstrcat(str, length, "\n");
 
 #if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_APPEND_MODULENAME
-    GetModuleFileNameA(NULL, s, sizeof(s));
+    AZ::Utils::GetExecutablePath(s, sizeof(s));
     
     // Log EXE filename only if possible (not full EXE path which could contain sensitive info)
     AZStd::string exeName;
diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
index e3ccb22f88..42bdb3afef 100644
--- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp
+++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
@@ -25,6 +25,7 @@
 
 #include 
 #include 
+#include 
 
 #define MAX_CELL_COUNT 32
 
@@ -2329,12 +2330,11 @@ bool CLocalizedStringsManager::GetSubtitle(const char* sKeyOrLabel, AZStd::strin
     }
 }
 
-template
-void InternalFormatStringMessage(StringClass& outString, const StringClass& sString, const CharType** sParams, int nParams)
+void InternalFormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char** sParams, int nParams)
 {
-    static const CharType token = (CharType) '%';
-    static const CharType tokens1[2] = { token, (CharType) '\0' };
-    static const CharType tokens2[3] = { token, token, (CharType) '\0' };
+    static const char token = '%';
+    static const char tokens1[2] = { token, '\0' };
+    static const char tokens2[3] = { token, token, '\0' };
 
     int maxArgUsed = 0;
     int lastPos = 0;
@@ -2342,8 +2342,8 @@ void InternalFormatStringMessage(StringClass& outString, const StringClass& sStr
     const int sourceLen = sString.length();
     while (true)
     {
-        int foundPos = sString.find(token, curPos);
-        if (foundPos != string::npos)
+        auto foundPos = sString.find(token, curPos);
+        if (foundPos != AZStd::string::npos)
         {
             if (foundPos + 1 < sourceLen)
             {
@@ -2360,8 +2360,8 @@ void InternalFormatStringMessage(StringClass& outString, const StringClass& sStr
                     }
                     else
                     {
-                        StringClass tmp (sString);
-                        tmp.replace(tokens1, tokens2);
+                        AZStd::string tmp(sString);
+                        AZ::StringFunc::Replace(tmp, tokens1, tokens2);
                         if constexpr (sizeof(*tmp.c_str()) == sizeof(char))
                         {
                             CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Parameter for argument %d is missing. [%s]", nArg + 1, (const char*)tmp.c_str());
@@ -2391,11 +2391,10 @@ void InternalFormatStringMessage(StringClass& outString, const StringClass& sStr
     }
 }
 
-template
-void InternalFormatStringMessage(StringClass& outString, const StringClass& sString, const CharType* param1, const CharType* param2 = 0, const CharType* param3 = 0, const CharType* param4 = 0)
+void InternalFormatStringMessage(AZStd::string& outString, const AZStd::string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0)
 {
     static const int MAX_PARAMS = 4;
-    const CharType* params[MAX_PARAMS] = { param1, param2, param3, param4 };
+    const char* params[MAX_PARAMS] = { param1, param2, param3, param4 };
     int nParams = 0;
     while (nParams < MAX_PARAMS && params[nParams])
     {
@@ -2677,7 +2676,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
         localtime_s(&thetime, &t);
         t = gEnv->pTimer->DateToSecondsUTC(thetime);
     }
-    outTimeString.resize(0);
+    outTimeString.clear();
     LCID lcID = g_currentLanguageID.lcID ? g_currentLanguageID.lcID : LOCALE_USER_DEFAULT;
     DWORD flags = bShowSeconds == false ? TIME_NOSECONDS : 0;
     SYSTEMTIME systemTime;
@@ -2689,7 +2688,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
         AZStd::fixed_wstring<256> tmpString;
         tmpString.resize(len);
         ::GetTimeFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len);
-        Unicode::Convert(outTimeString, tmpString);
+        AZStd::to_string(outTimeString, tmpString.data());
     }
 }
 
@@ -2719,7 +2718,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
             tmpString.resize(len);
             ::GetDateFormatW(lcID, 0, &systemTime, L"ddd", (wchar_t*) tmpString.c_str(), len);
             AZStd::string utf8;
-            Unicode::Convert(utf8, tmpString);
+            AZStd::to_string(utf8, tmpString.data());
             outDateString.append(utf8);
             outDateString.append(" ");
         }
@@ -2732,7 +2731,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
         tmpString.resize(len);
         ::GetDateFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len);
         AZStd::string utf8;
-        Unicode::Convert(utf8, tmpString);
+        AZStd::to_string(utf8, tmpString.data());
         outDateString.append(utf8);
     }
 }
diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp
index c23ed6e264..6ee6af6c22 100644
--- a/Code/Legacy/CrySystem/Log.cpp
+++ b/Code/Legacy/CrySystem/Log.cpp
@@ -18,7 +18,6 @@
 #include 
 #include "System.h"
 #include "CryPath.h"                    // PathUtil::ReplaceExtension()
-#include "UnicodeFunctions.h"
 
 #include 
 #include 
@@ -1052,13 +1051,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
 #if !defined(_RELEASE)
     if (queueState == MessageQueueState::NotQueued)
     {
-        // Note: OutputDebugString(A) only accepts current ANSI code-page, and the W variant will call the A variant internally.
-        // Here we replace non-ASCII characters with '?', which is the same as OutputDebugStringW will do for non-ANSI.
-        // Thus, we discard slightly more characters (ie, those inside the current ANSI code-page, but outside ASCII).
-        // In exchange, we save double-converting that would have happened otherwise (UTF-8 -> UTF-16 -> ANSI).
-        LogStringType asciiString;
-        Unicode::ConvertSafe(asciiString, tempString);
-        OutputDebugString(asciiString.c_str());
+        AZ::Debug::Platform::OutputToDebugger(nullptr, tempString.c_str());
     }
 
     if (!bIsMainThread)
@@ -1224,8 +1217,8 @@ void CLog::CreateBackupFile() const
     AZStd::string sFileWithoutExt = PathUtil::GetFileName(m_szFilename);
 
     {
-        assert(::strstr(sFileWithoutExt, ":") == 0);
-        assert(::strstr(sFileWithoutExt, "\\") == 0);
+        assert(::strstr(sFileWithoutExt.c_str(), ":") == 0);
+        assert(::strstr(sFileWithoutExt.c_str(), "\\") == 0);
     }
 
     PathUtil::RemoveExtension(sFileWithoutExt);
@@ -1255,11 +1248,9 @@ void CLog::CreateBackupFile() const
 
                     if (sName.find("BackupNameAttachment=") == AZStd::string::npos)
                     {
-#ifdef WIN32
-                        OutputDebugString("Log::CreateBackupFile ERROR '");
-                        OutputDebugString(sName.c_str());
-                        OutputDebugString("' not recognized \n");
-#endif
+                        AZ::Debug::Platform::OutputToDebugger("CrySystem Log", "Log::CreateBackupFile ERROR '");
+                        AZ::Debug::Platform::OutputToDebugger(nullptr, sName.c_str());
+                        AZ::Debug::Platform::OutputToDebugger(nullptr, "' not recognized \n");
                         assert(0);      // broken log file? - first line should include this name - written by LogVersion()
                         return;
                     }
diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp
index 9c2e1b1129..8c42c4a027 100644
--- a/Code/Legacy/CrySystem/System.cpp
+++ b/Code/Legacy/CrySystem/System.cpp
@@ -1148,7 +1148,7 @@ void CSystem::WarningV(EValidatorModule module, EValidatorSeverity severity, int
     if (sModuleFilter && *sModuleFilter != 0)
     {
         const char* sModule = ValidatorModuleToString(module);
-        if (strlen(sModule) > 1 || CryStringUtils::stristr(sModule, sModuleFilter) == 0)
+        if (strlen(sModule) > 1 || AZ::StringFunc::Find(sModule, sModuleFilter) == AZStd::string::npos)
         {
             // Filter out warnings from other modules.
             return;
@@ -1215,13 +1215,13 @@ void CSystem::GetLocalizedPath(const char* sLanguage, AZStd::string& sLocalizedP
     }
     else
     {
-    if (sLocalizationFolder.compareNoCase("Languages") != 0)
-    {
-        sLocalizedPath = sLocalizationFolder + "/" + sLanguage + "_xml.pak";
-    }
-    else
-    {
-        sLocalizedPath = AZStd::string("Localized/") + sLanguage + "_xml.pak";
+        if (AZ::StringFunc::Equal(sLocalizationFolder, "Languages", false))
+        {
+            sLocalizedPath = sLocalizationFolder + "/" + sLanguage + "_xml.pak";
+        }
+        else
+        {
+            sLocalizedPath = AZStd::string("Localized/") + sLanguage + "_xml.pak";
         }
     }
 }
@@ -1233,7 +1233,7 @@ void CSystem::GetLocalizedAudioPath(const char* sLanguage, AZStd::string& sLocal
     AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
     sLocalizationFolder.pop_back();
 
-    if (sLocalizationFolder.compareNoCase("Languages") != 0)
+    if (AZ::StringFunc::Equal(sLocalizationFolder, "Languages", false))
     {
         sLocalizedPath = sLocalizationFolder + "/" + sLanguage + ".pak";
     }
diff --git a/Code/Legacy/CrySystem/SystemCFG.cpp b/Code/Legacy/CrySystem/SystemCFG.cpp
index 062713c015..4d193c72a5 100644
--- a/Code/Legacy/CrySystem/SystemCFG.cpp
+++ b/Code/Legacy/CrySystem/SystemCFG.cpp
@@ -114,20 +114,22 @@ void CSystem::QueryVersionInfo()
 
     char ver[1024 * 8];
 
-    GetModuleFileName(NULL, moduleName, _MAX_PATH);  //retrieves the PATH for the current module
+    AZ::Utils::GetExecutablePath(moduleName, _MAX_PATH);  //retrieves the PATH for the current module
 
 #ifdef AZ_MONOLITHIC_BUILD
-    GetModuleFileName(NULL, moduleName, _MAX_PATH);  //retrieves the PATH for the current module
+    AZ::Utils::GetExecutablePath(moduleName, _MAX_PATH);  //retrieves the PATH for the current module
 #else // AZ_MONOLITHIC_BUILD
     azstrcpy(moduleName, AZ_ARRAY_SIZE(moduleName), "CrySystem.dll"); // we want to version from the system dll
 #endif // AZ_MONOLITHIC_BUILD
 
-    int verSize = GetFileVersionInfoSize(moduleName, &dwHandle);
+    AZStd::wstring moduleNameW;
+    AZStd::to_wstring(moduleNameW, moduleName);
+    int verSize = GetFileVersionInfoSizeW(moduleNameW.c_str(), &dwHandle);
     if (verSize > 0)
     {
-        GetFileVersionInfo(moduleName, dwHandle, 1024 * 8, ver);
+        GetFileVersionInfoW(moduleNameW.c_str(), dwHandle, 1024 * 8, ver);
         VS_FIXEDFILEINFO* vinfo;
-        VerQueryValue(ver, "\\", (void**)&vinfo, &len);
+        VerQueryValueW(ver, L"\\", (void**)&vinfo, &len);
 
         const uint32 verIndices[4] = {0, 1, 2, 3};
         m_fileVersion.v[verIndices[0]] = m_productVersion.v[verIndices[0]] = vinfo->dwFileVersionLS & 0xFFFF;
@@ -143,14 +145,14 @@ void CSystem::QueryVersionInfo()
         }* lpTranslate;
 
         UINT count = 0;
-        char path[256];
+        wchar_t path[256];
         char* version = NULL;
 
-        VerQueryValue(ver, "\\VarFileInfo\\Translation", (LPVOID*)&lpTranslate, &count);
+        VerQueryValueW(ver, L"\\VarFileInfo\\Translation", (LPVOID*)&lpTranslate, &count);
         if (lpTranslate != NULL)
         {
-            azsnprintf(path, sizeof(path), "\\StringFileInfo\\%04x%04x\\InternalName", lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
-            VerQueryValue(ver, path, (LPVOID*)&version, &count);
+            azsnwprintf(path, sizeof(path), L"\\StringFileInfo\\%04x%04x\\InternalName", lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
+            VerQueryValueW(ver, path, (LPVOID*)&version, &count);
             if (version)
             {
                 m_buildVersion.Set(version);
@@ -211,7 +213,7 @@ void CSystem::LogVersion()
     CryLogAlways("Running 64 bit Mac version");
 #endif
 #if AZ_LEGACY_CRYSYSTEM_TRAIT_SYSTEMCFG_MODULENAME
-    GetModuleFileName(NULL, s, sizeof(s));
+    AZ::Utils::GetExecutablePath(s, sizeof(s));
 
     // Log EXE filename only if possible (not full EXE path which could contain sensitive info)
     AZStd::string exeName;
@@ -448,25 +450,24 @@ bool CSystemConfiguration::ParseSystemConfig()
         }
 
         AZStd::string strLine = s;
+        AZ::StringFunc::TrimWhiteSpace(strLine, true, true);
 
         // detect groups e.g. "[General]"   should set strGroup="General"
         {
-            AZStd::string strTrimmedLine(RemoveWhiteSpaces(strLine));
-            size_t size = strTrimmedLine.size();
+            size_t size = strLine.size();
 
             if (size >= 3)
             {
-                if (strTrimmedLine[0] == '[' && strTrimmedLine[size - 1] == ']')       // currently no comments are allowed to be behind groups
+                if (strLine[0] == '[' && strLine[size - 1] == ']')  // currently no comments are allowed to be behind groups
                 {
-                    strGroup = &strTrimmedLine[1];
-                    strGroup.resize(size - 2);                                  // remove [ and ]
+                    strGroup = &strLine[1];
+                    strGroup.resize(size - 2);                      // remove [ and ]
                     continue;                                       // next line
                 }
             }
         }
 
         //trim all whitespace characters at the beginning and the end of the current line and store its size
-        AZ::StringFunc::TrimWhiteSpace(strLine, true, true);
         size_t strLineSize = strLine.size();
 
         //skip comments, comments start with ";" or "--" but may have preceding whitespace characters
@@ -491,8 +492,9 @@ bool CSystemConfiguration::ParseSystemConfig()
         AZStd::string::size_type posEq(strLine.find("=", 0));
         if (AZStd::string::npos != posEq)
         {
-            AZStd::string stemp(strLine, 0, posEq);
-            AZStd::string strKey(RemoveWhiteSpaces(stemp));
+            AZStd::string stemp;
+            AZStd::string strKey(strLine, 0, posEq);
+            AZ::StringFunc::TrimWhiteSpace(strKey, true, true);
 
             {
                 // extract value
@@ -507,8 +509,8 @@ bool CSystemConfiguration::ParseSystemConfig()
                 }
                 else
                 {
-                    AZStd::string strTmp(strLine, posEq + 1, strLine.size() - (posEq + 1));
-                    strValue = RemoveWhiteSpaces(strTmp);
+                    strValue = AZStd::string(strLine, posEq + 1, strLine.size() - (posEq + 1));
+                    AZ::StringFunc::TrimWhiteSpace(strValue, true, true);
                 }
 
                 {
diff --git a/Code/Legacy/CrySystem/SystemCFG.h b/Code/Legacy/CrySystem/SystemCFG.h
index cfaefd2e45..7ec6f1231b 100644
--- a/Code/Legacy/CrySystem/SystemCFG.h
+++ b/Code/Legacy/CrySystem/SystemCFG.h
@@ -25,12 +25,6 @@ public:
     CSystemConfiguration(const AZStd::string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing = true);
     ~CSystemConfiguration();
 
-    AZStd::string RemoveWhiteSpaces(AZStd::string& s)
-    {
-        s.Trim();
-        return s;
-    }
-
     bool IsError() const { return m_bError; }
 
 private: // ----------------------------------------
diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp
index ae177a9974..0c1411e649 100644
--- a/Code/Legacy/CrySystem/SystemInit.cpp
+++ b/Code/Legacy/CrySystem/SystemInit.cpp
@@ -451,7 +451,7 @@ AZStd::unique_ptr CSystem::LoadDLL(const char* dllName)
     //////////////////////////////////////////////////////////////////////////
     // After loading DLL initialize it by calling ModuleInitISystem
     //////////////////////////////////////////////////////////////////////////
-    string moduleName = PathUtil::GetFileName(dllName);
+    AZStd::string moduleName = PathUtil::GetFileName(dllName);
 
     typedef void*(*PtrFunc_ModuleInitISystem)(ISystem* pSystem, const char* moduleName);
     PtrFunc_ModuleInitISystem pfnModuleInitISystem = handle->GetFunction(DLL_MODULE_INIT_ISYSTEM);
@@ -523,7 +523,7 @@ void CSystem::ShutdownModuleLibraries()
 /////////////////////////////////////////////////////////////////////////////////
 
 #if defined(WIN32) || defined(WIN64)
-wstring GetErrorStringUnsupportedGPU(const char* gpuName, unsigned int gpuVendorId, unsigned int gpuDeviceId)
+AZStd::wstring GetErrorStringUnsupportedGPU(const char* gpuName, unsigned int gpuVendorId, unsigned int gpuDeviceId)
 {
     const size_t fullLangID = (size_t) GetKeyboardLayout(0);
     const size_t primLangID = fullLangID & 0x3FF;
@@ -877,19 +877,19 @@ void CSystem::InitLocalization()
         languageID = ILocalizationManager::EPlatformIndependentLanguageID::ePILID_English_US;
     }
 
-    string language = m_pLocalizationManager->LangNameFromPILID(languageID);
+    AZStd::string language = m_pLocalizationManager->LangNameFromPILID(languageID);
     m_pLocalizationManager->SetLanguage(language.c_str());
     if (m_pLocalizationManager->GetLocalizationFormat() == 1)
     {
-        string translationsListXML = LOCALIZATION_TRANSLATIONS_LIST_FILE_NAME;
-        m_pLocalizationManager->InitLocalizationData(translationsListXML);
+        AZStd::string translationsListXML = LOCALIZATION_TRANSLATIONS_LIST_FILE_NAME;
+        m_pLocalizationManager->InitLocalizationData(translationsListXML.c_str());
 
         m_pLocalizationManager->LoadAllLocalizationData();
     }
     else
     {
         // if the language value cannot be found, let's default to the english pak
-        OpenLanguagePak(language);
+        OpenLanguagePak(language.c_str());
     }
 
     if (auto console = AZ::Interface::Get(); console != nullptr)
@@ -907,7 +907,7 @@ void CSystem::InitLocalization()
             }
         }
     }
-    OpenLanguageAudioPak(language);
+    OpenLanguageAudioPak(language.c_str());
 }
 
 void CSystem::OpenBasicPaks()
@@ -971,10 +971,10 @@ void CSystem::OpenLanguagePak(const char* sLanguage)
     // Initialize languages.
 
     // Omit the trailing slash!
-    string sLocalizationFolder = PathUtil::GetLocalizationFolder();
+    AZStd::string sLocalizationFolder = PathUtil::GetLocalizationFolder();
 
     // load xml pak with full filenames to perform wildcard searches.
-    string sLocalizedPath;
+    AZStd::string sLocalizedPath;
     GetLocalizedPath(sLanguage, sLocalizedPath);
     if (!m_env.pCryPak->OpenPacks({ sLocalizationFolder.c_str(), sLocalizationFolder.size() }, { sLocalizedPath.c_str(), sLocalizedPath.size() }, 0))
     {
@@ -1001,15 +1001,15 @@ void CSystem::OpenLanguageAudioPak([[maybe_unused]] const char* sLanguage)
     int nPakFlags = 0;
 
     // Omit the trailing slash!
-    string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1));
+    AZStd::string sLocalizationFolder(AZStd::string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1));
 
-    if (sLocalizationFolder.compareNoCase("Languages") == 0)
+    if (!AZ::StringFunc::Equal(sLocalizationFolder, "Languages", false))
     {
         sLocalizationFolder = "@assets@";
     }
 
     // load localized pak with crc32 filenames on consoles to save memory.
-    string sLocalizedPath = "loc.pak";
+    AZStd::string sLocalizedPath = "loc.pak";
 
     if (!m_env.pCryPak->OpenPacks(sLocalizationFolder.c_str(), sLocalizedPath.c_str(), nPakFlags))
     {
@@ -1019,10 +1019,10 @@ void CSystem::OpenLanguageAudioPak([[maybe_unused]] const char* sLanguage)
 }
 
 
-string GetUniqueLogFileName(string logFileName)
+AZStd::string GetUniqueLogFileName(AZStd::string logFileName)
 {
-    string logFileNamePrefix = logFileName;
-    if ((logFileNamePrefix[0] != '@') && (AzFramework::StringFunc::Path::IsRelative(logFileNamePrefix)))
+    AZStd::string logFileNamePrefix = logFileName;
+    if ((logFileNamePrefix[0] != '@') && (AzFramework::StringFunc::Path::IsRelative(logFileNamePrefix.c_str())))
     {
         logFileNamePrefix = "@log@/";
         logFileNamePrefix += logFileName;
@@ -1038,9 +1038,9 @@ string GetUniqueLogFileName(string logFileName)
         return logFileNamePrefix;
     }
 
-    string logFileExtension;
+    AZStd::string logFileExtension;
     size_t extensionIndex = logFileName.find_last_of('.');
-    if (extensionIndex != string::npos)
+    if (extensionIndex != AZStd::string::npos)
     {
         logFileExtension = logFileName.substr(extensionIndex, logFileName.length() - extensionIndex);
         logFileNamePrefix = logFileName.substr(0, extensionIndex);
@@ -1214,7 +1214,7 @@ bool CSystem::Init(const SSystemInitParams& startupParams)
 
         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
 AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option")
-        GetVersionExA(&osvi);
+        GetVersionExW(&osvi);
 AZ_POP_DISABLE_WARNING
 
         bool bIsWindowsXPorLater = osvi.dwMajorVersion > 5 || (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion >= 1);
@@ -1309,7 +1309,7 @@ AZ_POP_DISABLE_WARNING
             }
             else if (startupParams.sLogFileName)    //otherwise see if the startup params has a log file name, if so use it
             {
-                const string sUniqueLogFileName = GetUniqueLogFileName(startupParams.sLogFileName);
+                const AZStd::string sUniqueLogFileName = GetUniqueLogFileName(startupParams.sLogFileName);
                 m_env.pLog->SetFileName(sUniqueLogFileName.c_str(), startupParams.autoBackupLogs);
             }
             else//use the default log name
@@ -1657,20 +1657,20 @@ static void LoadConfigurationCmd(IConsoleCmdArgs* pParams)
         return;
     }
 
-    GetISystem()->LoadConfiguration(string("Config/") + pParams->GetArg(1));
+    GetISystem()->LoadConfiguration((AZStd::string("Config/") + pParams->GetArg(1)).c_str());
 }
 
 
 // --------------------------------------------------------------------------------------------------------------------------
 
-static string ConcatPath(const char* szPart1, const char* szPart2)
+static AZStd::string ConcatPath(const char* szPart1, const char* szPart2)
 {
     if (szPart1[0] == 0)
     {
         return szPart2;
     }
 
-    string ret;
+    AZStd::string ret;
 
     ret.reserve(strlen(szPart1) + 1 + strlen(szPart2));
 
@@ -2134,12 +2134,12 @@ void CSystem::CreateAudioVars()
 }
 
 /////////////////////////////////////////////////////////////////////
-void CSystem::AddCVarGroupDirectory(const string& sPath)
+void CSystem::AddCVarGroupDirectory(const AZStd::string& sPath)
 {
     CryLog("creating CVarGroups from directory '%s' ...", sPath.c_str());
     INDENT_LOG_DURING_SCOPE();
 
-    AZ::IO::ArchiveFileIterator handle = gEnv->pCryPak->FindFirst(ConcatPath(sPath, "*.cfg").c_str());
+    AZ::IO::ArchiveFileIterator handle = gEnv->pCryPak->FindFirst(ConcatPath(sPath.c_str(), "*.cfg").c_str());
 
     if (!handle)
     {
@@ -2152,16 +2152,9 @@ void CSystem::AddCVarGroupDirectory(const string& sPath)
         {
             if (handle.m_filename != "." && handle.m_filename != "..")
             {
-                AddCVarGroupDirectory(ConcatPath(sPath, handle.m_filename.data()));
+                AddCVarGroupDirectory(ConcatPath(sPath.c_str(), handle.m_filename.data()));
             }
         }
-        else
-        {
-            string sFilePath = ConcatPath(sPath, handle.m_filename.data());
-
-            string sCVarName = sFilePath;
-            PathUtil::RemoveExtension(sCVarName);
-        }
     } while (handle = gEnv->pCryPak->FindNext(handle));
 
     gEnv->pCryPak->FindClose(handle);
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index a4be0e5054..9fd01f1905 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -15,7 +15,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 #include  // for AZ_MAX_PATH_LEN
 #include 
@@ -127,7 +126,7 @@ const char* CSystem::GetUserName()
     DWORD dwSize = iNameBufferSize;
     wchar_t nameW[iNameBufferSize];
     ::GetUserNameW(nameW, &dwSize);
-    azstrcpy(szNameBuffer, CryStringUtils::WStrToUTF8(nameW));
+    AZStd::to_string(szNameBuffer, iNameBufferSize, nameW, dwSize);
     return szNameBuffer;
 #else
 #if defined(LINUX)
@@ -171,12 +170,12 @@ int CSystem::GetApplicationInstance()
     // this code below essentially "locks" an instance of the USER folder to a specific running application
     if (m_iApplicationInstance == -1)
     {
-        string suffix;
+        AZStd::wstring suffix;
         for (int instance = 0;; ++instance)
         {
-            suffix.Format("(%d)", instance);
+            suffix = AZStd::wstring::format(L"LumberyardApplication(%d)", instance);
 
-            CreateMutex(NULL, TRUE, "LumberyardApplication" + suffix);
+            CreateMutexW(NULL, TRUE, suffix.c_str());
             // search for duplicates
             if (GetLastError() != ERROR_ALREADY_EXISTS)
             {
@@ -195,13 +194,13 @@ int CSystem::GetApplicationInstance()
 int CSystem::GetApplicationLogInstance([[maybe_unused]] const char* logFilePath)
 {
 #if AZ_TRAIT_OS_USE_WINDOWS_MUTEX
-    string suffix;
+    AZStd::wstring suffix;
     int instance = 0;
     for (;; ++instance)
     {
-        suffix.Format("(%d)", instance);
+        suffix = AZStd::wstring::format(L"%s(%d)", logFilePath, instance);
 
-        CreateMutex(NULL, TRUE, logFilePath + suffix);
+        CreateMutexW(NULL, TRUE, suffix.c_str());
         if (GetLastError() != ERROR_ALREADY_EXISTS)
         {
             break;
@@ -218,7 +217,7 @@ struct CryDbgModule
 {
     HANDLE heap;
     WIN_HMODULE handle;
-    string name;
+    AZStd::string name;
     DWORD dwSize;
 };
 
@@ -343,12 +342,15 @@ void CSystem::FatalError(const char* format, ...)
     assert(szBuffer[0] >= ' ');
     //  strcpy(szBuffer,szBuffer+1);    // remove verbosity tag since it is not supported by ::MessageBox
 
-    OutputDebugString(szBuffer);
+    AZ::Debug::Platform::OutputToDebugger("CrySystem", szBuffer);
+
 #ifdef WIN32
     OnFatalError(szBuffer);
     if (!g_cvars.sys_no_crash_dialog)
     {
-        ::MessageBox(NULL, szBuffer, "Open 3D Engine Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
+        AZStd::wstring szBufferW;
+        AZStd::to_wstring(szBufferW, szBuffer);
+        ::MessageBoxW(NULL, szBufferW.c_str(), L"Open 3D Engine Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
     }
 
     // Dump callstack.
@@ -461,20 +463,20 @@ bool CSystem::ReLaunchMediaCenter()
     }
 
     // Get the path to Media Center
-    char szExpandedPath[AZ_MAX_PATH_LEN];
-    if (!ExpandEnvironmentStrings("%SystemRoot%\\ehome\\ehshell.exe", szExpandedPath, AZ_MAX_PATH_LEN))
+    wchar_t szExpandedPath[AZ_MAX_PATH_LEN];
+    if (!ExpandEnvironmentStringsW(L"%SystemRoot%\\ehome\\ehshell.exe", szExpandedPath, AZ_MAX_PATH_LEN))
     {
         return false;
     }
 
     // Skip if ehshell.exe doesn't exist
-    if (GetFileAttributes(szExpandedPath) == 0xFFFFFFFF)
+    if (GetFileAttributesW(szExpandedPath) == 0xFFFFFFFF)
     {
         return false;
     }
 
     // Launch ehshell.exe
-    INT_PTR result = (INT_PTR)ShellExecute(NULL, TEXT("open"), szExpandedPath, NULL, NULL, SW_SHOWNORMAL);
+    INT_PTR result = (INT_PTR)ShellExecuteW(NULL, TEXT("open"), szExpandedPath, NULL, NULL, SW_SHOWNORMAL);
     return (result > 32);
 }
 #else
@@ -491,7 +493,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
     bool bSucceeded  = false;
     // check Vista and later OS first
 
-    HMODULE shell32 = LoadLibraryA("Shell32.dll");
+    HMODULE shell32 = LoadLibraryW(L"Shell32.dll");
     if (shell32)
     {
         typedef long (__stdcall * T_SHGetKnownFolderPath)(REFKNOWNFOLDERID rfid, unsigned long dwFlags, void* hToken, wchar_t** ppszPath);
@@ -505,7 +507,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
             if (bSucceeded)
             {
                 // Convert from UNICODE to UTF-8
-                azstrcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath));
+                AZStd::to_string(szMyDocumentsPath, maxPathSize, wMyDocumentsPath);
                 CoTaskMemFree(wMyDocumentsPath);
             }
         }
@@ -519,7 +521,7 @@ bool CSystem::GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize)
         bSucceeded = SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, wMyDocumentsPath));
         if (bSucceeded)
         {
-            azstrcpy(szMyDocumentsPath, maxPathSize, CryStringUtils::WStrToUTF8(wMyDocumentsPath));
+            AZStd::to_string(szMyDocumentsPath, maxPathSize, wMyDocumentsPath);
         }
     }
 
@@ -547,7 +549,7 @@ void CSystem::DetectGameFolderAccessRights()
     BOOL bAccessStatus = FALSE;
 
     // Get a pointer to the existing DACL.
-    dwRes = GetNamedSecurityInfo(".", SE_FILE_OBJECT,
+    dwRes = GetNamedSecurityInfoW(L".", SE_FILE_OBJECT,
             DACL_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION,
             NULL, NULL, &pDACL, NULL, &pSD);
 
diff --git a/Code/Legacy/CrySystem/WindowsErrorReporting.cpp b/Code/Legacy/CrySystem/WindowsErrorReporting.cpp
index a02f55b69e..d467923c74 100644
--- a/Code/Legacy/CrySystem/WindowsErrorReporting.cpp
+++ b/Code/Legacy/CrySystem/WindowsErrorReporting.cpp
@@ -66,7 +66,9 @@ LONG WINAPI CryEngineExceptionFilterMiniDump(struct _EXCEPTION_POINTERS* pExcept
         return EXCEPTION_CONTINUE_SEARCH;
     }
 
-    HANDLE hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+    AZStd::wstring szDumpPathW;
+    AZStd::to_wstring(szDumpPathW, szDumpPath);
+    HANDLE hFile = ::CreateFileW(szDumpPathW.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
     if (hFile == INVALID_HANDLE_VALUE)
     {
         CryLogAlways("Failed to record DMP file: could not open file '%s' for writing - error code: %d", szDumpPath, GetLastError());
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index a69d86e8b7..f5e946be43 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -15,9 +15,6 @@
 #include "XConsoleVariable.h"
 #include "System.h"
 #include "ConsoleBatchFile.h"
-#include "StringUtils.h"
-#include "UnicodeFunctions.h"
-#include "UnicodeIterator.h"
 
 #include 
 #include 
@@ -88,11 +85,13 @@ inline int GetCharPrio(char x)
     }
 }
 // case sensitive
-inline bool less_CVar(const char* left, const char* right)
+inline bool less_CVar(const AZStd::string& left, const AZStd::string& right)
 {
+    AZStd::string_view leftView(left);
+    AZStd::string_view rightView(right);
     for (;; )
     {
-        uint32 l = GetCharPrio(*left), r = GetCharPrio(*right);
+        uint32 l = GetCharPrio(leftView.front()), r = GetCharPrio(rightView.front());
 
         if (l < r)
         {
@@ -103,13 +102,13 @@ inline bool less_CVar(const char* left, const char* right)
             return false;
         }
 
-        if (*left == 0 || *right == 0)
+        if (leftView.front() == 0 || rightView.front() == 0)
         {
             break;
         }
 
-        ++left;
-        ++right;
+        leftView.remove_prefix(1);
+        rightView.remove_prefix(1);
     }
 
     return false;
@@ -149,7 +148,7 @@ void Bind(IConsoleCmdArgs* cmdArgs)
 {
     if (cmdArgs->GetArgCount() >= 3)
     {
-        string arg;
+        AZStd::string arg;
         for (int i = 2; i < cmdArgs->GetArgCount(); ++i)
         {
             arg += cmdArgs->GetArg(i);
@@ -414,9 +413,7 @@ void CXConsole::Init(ISystem* pSystem)
 void CXConsole::LogChangeMessage(const char* name, const bool isConst, const bool isCheat, const bool isReadOnly, const bool isDeprecated,
     const char* oldValue, const char* newValue, [[maybe_unused]] const bool isProcessingGroup, const bool allowChange)
 {
-    string logMessage;
-
-    logMessage.Format
+    AZStd::string logMessage = AZStd::string::format
         ("[CVARS]: [%s] variable [%s] from [%s] to [%s]%s; Marked as%s%s%s%s",
         (allowChange) ? "CHANGED" : "IGNORED CHANGE",
         name,
@@ -452,7 +449,7 @@ void CXConsole::RegisterVar(ICVar* pCVar, ConsoleVarFunc pChangeFunc)
     bool isReadOnly = ((pCVar->GetFlags() & VF_READONLY) != 0);
     bool isDeprecated = ((pCVar->GetFlags() & VF_DEPRECATED) != 0);
 
-    ConfigVars::iterator it = m_configVars.find(CONST_TEMP_STRING(pCVar->GetName()));
+    ConfigVars::iterator it = m_configVars.find(pCVar->GetName());
     if (it != m_configVars.end())
     {
         SConfigVar& var = it->second;
@@ -906,7 +903,7 @@ void CXConsole::DumpKeyBinds(IKeyBindDumpSink* pCallback)
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 const char* CXConsole::FindKeyBind(const char* sCmd) const
 {
-    ConsoleBindsMap::const_iterator it = m_mapBinds.find(CONST_TEMP_STRING(sCmd));
+    ConsoleBindsMap::const_iterator it = m_mapBinds.find(sCmd);
 
     if (it != m_mapBinds.end())
     {
@@ -1263,9 +1260,7 @@ bool CXConsole::ProcessInput(const AzFramework::InputChannel& inputChannel)
         if (m_nCursorPos)
         {
             const char* pCursor = m_sInputBuffer.c_str() + m_nCursorPos;
-            Unicode::CIterator pUnicode(pCursor);
-            --pUnicode; // Note: This moves back one UCS code-point, but doesn't necessarily match one displayed character (ie, combining diacritics)
-            pCursor = pUnicode.GetPosition();
+            pCursor -= Utf8::Internal::sequence_length(pCursor); // Note: This moves back one UCS code-point, but doesn't necessarily match one displayed character (ie, combining diacritics)
             m_nCursorPos = pCursor - m_sInputBuffer.c_str();
         }
         return true;
@@ -1275,9 +1270,7 @@ bool CXConsole::ProcessInput(const AzFramework::InputChannel& inputChannel)
         if (m_nCursorPos < (int)(m_sInputBuffer.length()))
         {
             const char* pCursor = m_sInputBuffer.c_str() + m_nCursorPos;
-            Unicode::CIterator pUnicode(pCursor);
-            ++pUnicode; // Note: This moves forward one UCS code-point, but doesn't necessarily match one displayed character (ie, combining diacritics)
-            pCursor = pUnicode.GetPosition();
+            pCursor += Utf8::Internal::sequence_length(pCursor); // Note: This moves forward one UCS code-point, but doesn't necessarily match one displayed character (ie, combining diacritics)
             m_nCursorPos = pCursor - m_sInputBuffer.c_str();
         }
         return true;
@@ -1446,7 +1439,7 @@ bool CXConsole::GetLineNo(const int indwLineNo, char* outszBuffer, const int ind
     {
         buf++;                          // to jump over verbosity level character
     }
-    cry_strcpy(outszBuffer, indwBufferSize, buf);
+    azstrcpy(outszBuffer, indwBufferSize, buf);
 
     return true;
 }
@@ -1558,27 +1551,27 @@ const char* CXConsole::GetFlagsString(const uint32 dwFlags)
 
     if (dwFlags & VF_READONLY)
     {
-        cry_strcat(sFlags, "READONLY, ");
+        azstrcat(sFlags, "READONLY, ");
     }
     if (dwFlags & VF_DEPRECATED)
     {
-        cry_strcat(sFlags, "DEPRECATED, ");
+        azstrcat(sFlags, "DEPRECATED, ");
     }
     if (dwFlags & VF_DUMPTODISK)
     {
-        cry_strcat(sFlags, "DUMPTODISK, ");
+        azstrcat(sFlags, "DUMPTODISK, ");
     }
     if (dwFlags & VF_REQUIRE_LEVEL_RELOAD)
     {
-        cry_strcat(sFlags, "REQUIRE_LEVEL_RELOAD, ");
+        azstrcat(sFlags, "REQUIRE_LEVEL_RELOAD, ");
     }
     if (dwFlags & VF_REQUIRE_APP_RESTART)
     {
-        cry_strcat(sFlags, "REQUIRE_APP_RESTART, ");
+        azstrcat(sFlags, "REQUIRE_APP_RESTART, ");
     }
     if (dwFlags & VF_RESTRICTEDMODE)
     {
-        cry_strcat(sFlags, "RESTRICTEDMODE, ");
+        azstrcat(sFlags, "RESTRICTEDMODE, ");
     }
 
     if (sFlags[0] != 0)
@@ -1794,7 +1787,7 @@ void CXConsole::DisplayHelp(const char* help, const char* name)
         char* start, * pos;
         for (pos = strstr((char*)help, "\n"), start = (char*)help; pos; start = ++pos)
         {
-            string s = start;
+            AZStd::string s = start;
             s.resize(pos - start);
             ConsoleLogInputResponse("    $3%s", s.c_str());
             pos = strstr(pos, "\n");
@@ -1816,11 +1809,12 @@ void CXConsole::ExecuteString(const char* command, const bool bSilentMode, const
 
     // Store the string commands into a list and defer the execution for later.
     // The commands will be processed in CXConsole::Update()
-    string str(command);
-    str.TrimLeft();
+    AZStd::string str(command);
+    AZ::StringFunc::TrimWhiteSpace(str, true, false);
 
     // Unroll the exec command
-    bool unroll = (0 == str.Left(strlen("exec")).compareNoCase("exec"));
+    
+    bool unroll = (0 == AZ::StringFunc::Find(str, "exec", 0, false, false));
 
     if (unroll)
     {
@@ -1858,10 +1852,10 @@ void CXConsole::ResetCVarsToDefaults()
 
 }
 
-void CXConsole::SplitCommands(const char* line, std::list& split)
+void CXConsole::SplitCommands(const char* line, std::list& split)
 {
     const char* start = line;
-    string working;
+    AZStd::string working;
 
     while (true)
     {
@@ -1881,7 +1875,7 @@ void CXConsole::SplitCommands(const char* line, std::list& split)
         case '\0':
         {
             working.assign(start, line - 1);
-            working.Trim();
+            AZ::StringFunc::TrimWhiteSpace(working, true, true);
 
             if (!working.empty())
             {
@@ -1931,15 +1925,15 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
     ConsoleCommandsMapItor itrCmd;
     ConsoleVariablesMapItor itrVar;
 
-    std::list lineCommands;
+    std::list lineCommands;
     SplitCommands(command, lineCommands);
 
-    string sTemp;
-    string sCommand, sLineCommand;
+    AZStd::string sTemp;
+    AZStd::string sCommand, sLineCommand;
 
     while (!lineCommands.empty())
     {
-        string::size_type nPos;
+        AZStd::string::size_type nPos;
 
         {
             sTemp = lineCommands.front();
@@ -1951,17 +1945,17 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
             {
                 if (GetStatus())
                 {
-                    AddLine(sTemp);
+                    AddLine(sTemp.c_str());
                 }
             }
 
             nPos = sTemp.find_first_of('=');
 
-            if (nPos != string::npos)
+            if (nPos != AZStd::string::npos)
             {
                 sCommand = sTemp.substr(0, nPos);
             }
-            else if ((nPos = sTemp.find_first_of(' ')) != string::npos)
+            else if ((nPos = sTemp.find_first_of(' ')) != AZStd::string::npos)
             {
                 sCommand = sTemp.substr(0, nPos);
             }
@@ -1970,7 +1964,7 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
                 sCommand = sTemp;
             }
 
-            sCommand.Trim();
+            AZ::StringFunc::TrimWhiteSpace(sCommand, true, true);
 
             //////////////////////////////////////////
             // Search for CVars
@@ -2005,7 +1999,7 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
 
         //////////////////////////////////////////
         //Check  if is a variable
-        itrVar = m_mapVariables.find(sCommand);
+        itrVar = m_mapVariables.find(sCommand.c_str());
         if (itrVar != m_mapVariables.end())
         {
             ICVar* pCVar = itrVar->second;
@@ -2017,10 +2011,10 @@ void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConso
                     m_blockCounter++;
                 }
 
-                if (nPos != string::npos)
+                if (nPos != AZStd::string::npos)
                 {
                     sTemp = sTemp.substr(nPos + 1);     // remove the command from sTemp
-                    sTemp.Trim(" \t\r\n\"\'");
+                    AZ::StringFunc::StripEnds(sTemp, " \t\r\n\"\'");
 
                     if (sTemp == "?")
                     {
@@ -2094,12 +2088,12 @@ void CXConsole::ExecuteDeferredCommands()
 }
 
 //////////////////////////////////////////////////////////////////////////
-void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDevMode)
+void CXConsole::ExecuteCommand(CConsoleCommand& cmd, AZStd::string& str, bool bIgnoreDevMode)
 {
     CryLog ("[CONSOLE] Executing console command '%s'", str.c_str());
     INDENT_LOG_DURING_SCOPE();
 
-    std::vector args;
+    std::vector args;
     size_t t;
 
     {
@@ -2118,7 +2112,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
                 {
                     ;
                 }
-                args.push_back(string(start + 1, commandLine - 1));
+                args.push_back(AZStd::string(start + 1, commandLine - 1));
                 start = commandLine;
                 break;
             }
@@ -2129,7 +2123,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
             {
                 if ((*commandLine == ' ') || !*commandLine)
                 {
-                    args.push_back(string(start, commandLine));
+                    args.push_back(AZStd::string(start, commandLine));
                     start = commandLine + 1;
                 }
             }
@@ -2139,7 +2133,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
 
         if (args.size() >= 2 && args[1] == "?")
         {
-            DisplayHelp(cmd.m_sHelp, cmd.m_sName.c_str());
+            DisplayHelp(cmd.m_sHelp.c_str(), cmd.m_sName.c_str());
             return;
         }
 
@@ -2166,13 +2160,13 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
         return;
     }
 
-    string buf;
+    AZStd::string buf;
     {
         // only do this for commands with script implementation
         for (;; )
         {
             t = str.find_first_of("\\", t);
-            if (t == string::npos)
+            if (t == AZStd::string::npos)
             {
                 break;
             }
@@ -2183,7 +2177,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
         for (t = 1;; )
         {
             t = str.find_first_of("\"", t);
-            if (t == string::npos)
+            if (t == AZStd::string::npos)
             {
                 break;
             }
@@ -2194,9 +2188,9 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
         buf = cmd.m_sCommand;
 
         size_t pp = buf.find("%%");
-        if (pp != string::npos)
+        if (pp != AZStd::string::npos)
         {
-            string list = "";
+            AZStd::string list = "";
             for (unsigned int i = 1; i < args.size(); i++)
             {
                 list += "\"" + args[i] + "\"";
@@ -2207,9 +2201,9 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
             }
             buf.replace(pp, 2, list);
         }
-        else if ((pp = buf.find("%line")) != string::npos)
+        else if ((pp = buf.find("%line")) != AZStd::string::npos)
         {
-            string tmp = "\"" + str.substr(str.find(" ") + 1) + "\"";
+            AZStd::string tmp = "\"" + str.substr(str.find(" ") + 1) + "\"";
             if (args.size() > 1)
             {
                 buf.replace(pp, 5, tmp);
@@ -2226,7 +2220,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
                 char pat[10];
                 azsprintf(pat, "%%%d", i);
                 size_t pos = buf.find(pat);
-                if (pos == string::npos)
+                if (pos == AZStd::string::npos)
                 {
                     if (i != args.size())
                     {
@@ -2241,7 +2235,7 @@ void CXConsole::ExecuteCommand(CConsoleCommand& cmd, string& str, bool bIgnoreDe
                         ConsoleWarning("Not enough arguments for: %s", cmd.m_sName.c_str());
                         return;
                     }
-                    string arg = "\"" + args[i] + "\"";
+                    AZStd::string arg = "\"" + args[i] + "\"";
                     buf.replace(pos, strlen(pat), arg);
                 }
             }
@@ -2340,15 +2334,15 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
     }
     //try to search in command list
     bool bArgumentAutoComplete = false;
-    std::vector matches;
+    std::vector matches;
 
-    if (m_sPrevTab.find(' ') != string::npos)
+    if (m_sPrevTab.find(' ') != AZStd::string::npos)
     {
         bool bProcessAutoCompl = true;
 
         // Find command.
-        string sVar = m_sPrevTab.substr(0, m_sPrevTab.find(' '));
-        ICVar* pCVar = GetCVar(sVar);
+        AZStd::string sVar = m_sPrevTab.substr(0, m_sPrevTab.find(' '));
+        ICVar* pCVar = GetCVar(sVar.c_str());
         if (pCVar)
         {
             if (!(pCVar->GetFlags() & VF_RESTRICTEDMODE) && con_restricted)            // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
@@ -2376,7 +2370,7 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
                 int nMatches = pArgumentAutoComplete->GetCount();
                 for (int i = 0; i < nMatches; i++)
                 {
-                    string cmd = string(sVar) + " " + pArgumentAutoComplete->GetValue(i);
+                    AZStd::string cmd = AZStd::string(sVar) + " " + pArgumentAutoComplete->GetValue(i);
                     if (_strnicmp(m_sPrevTab.c_str(), cmd.c_str(), m_sPrevTab.length()) == 0)
                     {
                         {
@@ -2436,10 +2430,10 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
     {
         ConsoleLogInput(" ");       // empty line before auto completion
 
-        for (std::vector::iterator i = matches.begin(); i != matches.end(); ++i)
+        for (std::vector::iterator i = matches.begin(); i != matches.end(); ++i)
         {
             // List matching variables
-            const char* sVar = *i;
+            const char* sVar = i->c_str();
             ICVar* pVar = GetCVar(sVar);
 
             if (pVar)
@@ -2453,7 +2447,7 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
         }
     }
 
-    for (std::vector::iterator i = matches.begin(); i != matches.end(); ++i)
+    for (std::vector::iterator i = matches.begin(); i != matches.end(); ++i)
     {
         if (m_nTabCount <= nMatch)
         {
@@ -2485,8 +2479,8 @@ void CXConsole::DisplayVarValue(ICVar* pVar)
 
     const char* sFlagsString = GetFlagsString(pVar->GetFlags());
 
-    string sValue = (pVar->GetFlags() & VF_INVISIBLE) ? "" : pVar->GetString();
-    string sVar = pVar->GetName();
+    AZStd::string sValue = (pVar->GetFlags() & VF_INVISIBLE) ? "" : pVar->GetString();
+    AZStd::string sVar = pVar->GetName();
 
     char szRealState[40] = "";
 
@@ -2623,12 +2617,8 @@ void CXConsole::AddLine(const char* inputStr)
 
 void CXConsole::PostLine(const char* lineOfText, size_t len)
 {
-    string line;
-
-    {
-        line = string(lineOfText, len);
-        m_dqConsoleBuffer.push_back(line);
-    }
+    AZStd::string line = AZStd::string(lineOfText, len);
+    m_dqConsoleBuffer.push_back(line);
 
     int nBufferSize = con_line_buffer_size;
 
@@ -2701,7 +2691,7 @@ void CXConsole::RemoveOutputPrintSink(IOutputPrintSink* inpSink)
 //////////////////////////////////////////////////////////////////////////
 void CXConsole::AddLinePlus(const char* inputStr)
 {
-    string str, tmpStr;
+    AZStd::string str, tmpStr;
 
     {
         if (!m_dqConsoleBuffer.size())
@@ -2717,13 +2707,13 @@ void CXConsole::AddLinePlus(const char* inputStr)
             str.resize(str.size() - 1);
         }
 
-        string::size_type nPos;
-        while ((nPos = str.find('\n')) != string::npos)
+        AZStd::string::size_type nPos;
+        while ((nPos = str.find('\n')) != AZStd::string::npos)
         {
             str.replace(nPos, 1, 1, ' ');
         }
 
-        while ((nPos = str.find('\r')) != string::npos)
+        while ((nPos = str.find('\r')) != AZStd::string::npos)
         {
             str.replace(nPos, 1, 1, ' ');
         }
@@ -2783,7 +2773,7 @@ void CXConsole::AddInputUTF8(const AZStd::string& textUTF8)
 //////////////////////////////////////////////////////////////////////////
 void CXConsole::ExecuteInputBuffer()
 {
-    string sTemp = m_sInputBuffer;
+    AZStd::string sTemp = m_sInputBuffer;
     if (m_sInputBuffer.empty())
     {
         return;
@@ -2814,9 +2804,7 @@ void CXConsole::RemoveInputChar(bool bBackSpace)
             const char* const pBase = m_sInputBuffer.c_str();
             const char* pCursor = pBase + m_nCursorPos;
             const char* const pEnd = pCursor;
-            Unicode::CIterator pUnicode(pCursor);
-            pUnicode--; // Remove one UCS code-point, doesn't account for combining diacritics
-            pCursor = pUnicode.GetPosition();
+            pCursor -= Utf8::Internal::sequence_length(pCursor); // Remove one UCS code-point, doesn't account for combining diacritics
             size_t length = pEnd - pCursor;
             m_sInputBuffer.erase(pCursor - pBase, length);
             m_nCursorPos -= length;
@@ -2829,9 +2817,7 @@ void CXConsole::RemoveInputChar(bool bBackSpace)
             const char* const pBase = m_sInputBuffer.c_str();
             const char* pCursor = pBase + m_nCursorPos;
             const char* const pBegin = pCursor;
-            Unicode::CIterator pUnicode(pCursor);
-            pUnicode--; // Remove one UCS code-point, doesn't account for combining diacritics
-            pCursor = pUnicode.GetPosition();
+            pCursor -= Utf8::Internal::sequence_length(pCursor); // Remove one UCS code-point, doesn't account for combining diacritics
             size_t length = pCursor - pBegin;
             m_sInputBuffer.erase(pBegin - pBase, length);
         }
@@ -2905,28 +2891,29 @@ void CXConsole::Paste()
 #if defined(AZ_PLATFORM_WINDOWS)
     if (OpenClipboard(NULL) != 0)
     {
-        wstring data;
+        AZStd::string data;
         const HANDLE wideData = GetClipboardData(CF_UNICODETEXT);
         if (wideData)
         {
             const LPCWSTR pWideData = (LPCWSTR)GlobalLock(wideData);
             if (pWideData)
             {
-                // Note: This conversion is just to make sure we discard malicious or malformed data
-                Unicode::ConvertSafe(data, pWideData);
+                AZStd::to_string(data, pWideData);
                 GlobalUnlock(wideData);
             }
         }
         CloseClipboard();
 
-        for (Unicode::CIterator it(data.begin(), data.end()); it != data.end(); ++it)
+        Utf8::Unchecked::octet_iterator end(data.end());
+        for (Utf8::Unchecked::octet_iterator it(data.begin()); it != end; ++it)
         {
             const uint32 cp = *it;
             if (cp != '\r')
             {
                 // Convert UCS code-point into UTF-8 string
-                char utf8_buf[5];
-                Unicode::Convert(utf8_buf, cp);
+                char utf8_buf[5] = {0};
+                size_t size = 5;
+                it.to_utf8_sequence(cp, utf8_buf, size);
                 AddInputUTF8(utf8_buf);
             }
         }
@@ -3030,7 +3017,7 @@ void CXConsole::AddCVarsToHash(ConsoleVariablesVector::const_iterator begin, Con
     {
         // add name & variable to string. We add both since adding only the value could cause
         // many collisions with variables all having value 0 or all 1.
-        string hashStr = it->first;
+        AZStd::string hashStr = it->first;
 
         runningNameCrc32.Add(hashStr.c_str(), hashStr.length());
         hashStr += it->second->GetDataProbeString();
@@ -3281,7 +3268,7 @@ void CXConsole::FindVar(const char* substr)
 
     for (size_t i = 0; i < cmdCount; i++)
     {
-        if (CryStringUtils::stristr(cmds[i], substr))
+        if (AZ::StringFunc::Find(cmds[i], substr) != AZStd::string::npos)
         {
             ICVar* pCvar = gEnv->pConsole->GetCVar(cmds[i]);
             if (pCvar)
@@ -3399,7 +3386,7 @@ const char* CXConsole::AutoCompletePrev(const char* substr)
 }
 
 //////////////////////////////////////////////////////////////////////////
-inline size_t sizeOf (const string& str)
+inline size_t sizeOf (const AZStd::string& str)
 {
     return str.capacity() + 1;
 }
diff --git a/Code/Legacy/CrySystem/XConsole.h b/Code/Legacy/CrySystem/XConsole.h
index f09c8e5ad7..b141a88e52 100644
--- a/Code/Legacy/CrySystem/XConsole.h
+++ b/Code/Legacy/CrySystem/XConsole.h
@@ -95,26 +95,12 @@ private:
 
 struct string_nocase_lt
 {
-    bool operator()(const char* s1, const char* s2) const
+    bool operator()(const AZStd::string& s1, const AZStd::string& s2) const
     {
-        return azstricmp(s1, s2) < 0;
+        return azstricmp(s1.c_str(), s2.c_str()) < 0;
     }
 };
 
-/* - very dangerous to use with STL containers
-struct string_nocase_lt
-{
-    bool operator()( const char *s1,const char *s2 ) const
-    {
-        return _stricmp(s1,s2) < 0;
-    }
-    bool operator()( const string &s1,const string &s2 ) const
-    {
-        return _stricmp(s1.c_str(),s2.c_str()) < 0;
-    }
-};
-*/
-
 //forward declarations
 class ITexture;
 struct IRenderer;
diff --git a/Code/Legacy/CrySystem/XConsoleVariable.cpp b/Code/Legacy/CrySystem/XConsoleVariable.cpp
index 370931088f..ab6ed0b078 100644
--- a/Code/Legacy/CrySystem/XConsoleVariable.cpp
+++ b/Code/Legacy/CrySystem/XConsoleVariable.cpp
@@ -286,7 +286,7 @@ void CXConsoleVariableCVarGroup::OnLoadConfigurationEntry_End()
 {
     if (!m_sDefaultValue.empty())
     {
-        gEnv->pConsole->LoadConfigVar(GetName(), m_sDefaultValue);
+        gEnv->pConsole->LoadConfigVar(GetName(), m_sDefaultValue.c_str());
         m_sDefaultValue.clear();
     }
 }
@@ -299,9 +299,9 @@ CXConsoleVariableCVarGroup::CXConsoleVariableCVarGroup(CXConsole* pConsole, cons
 }
 
 
-string CXConsoleVariableCVarGroup::GetDetailedInfo() const
+AZStd::string CXConsoleVariableCVarGroup::GetDetailedInfo() const
 {
-    string sRet = GetName();
+    AZStd::string sRet = GetName();
 
     sRet += " [";
 
@@ -326,11 +326,11 @@ string CXConsoleVariableCVarGroup::GetDetailedInfo() const
     sRet += "/default] [current]:\n";
 
 
-    std::map::const_iterator it, end = m_CVarGroupDefault.m_KeyValuePair.end();
+    std::map::const_iterator it, end = m_CVarGroupDefault.m_KeyValuePair.end();
 
     for (it = m_CVarGroupDefault.m_KeyValuePair.begin(); it != end; ++it)
     {
-        const string& rKey = it->first;
+        const AZStd::string& rKey = it->first;
 
         sRet += " ... ";
         sRet += rKey;
@@ -344,7 +344,7 @@ string CXConsoleVariableCVarGroup::GetDetailedInfo() const
             sRet += "/";
         }
         sRet += GetValueSpec(rKey);
-        ICVar* pCVar = gEnv->pConsole->GetCVar(rKey);
+        ICVar* pCVar = gEnv->pConsole->GetCVar(rKey.c_str());
         if (pCVar)
         {
             sRet += " [";
@@ -369,7 +369,7 @@ const char* CXConsoleVariableCVarGroup::GetHelp()
     }
 
     // create help on demand
-    string sRet = "Console variable group to apply settings to multiple variables\n\n";
+    AZStd::string sRet = "Console variable group to apply settings to multiple variables\n\n";
 
     sRet += GetDetailedInfo();
 
@@ -545,12 +545,12 @@ bool CXConsoleVariableCVarGroup::TestCVars(const SCVarGroup* pGroup, const ICVar
 bool CXConsoleVariableCVarGroup::TestCVars(const SCVarGroup& rGroup, const ICVar::EConsoleLogMode mode, const SCVarGroup* pExclude) const
 {
     bool bRet = true;
-    std::map::const_iterator it, end = rGroup.m_KeyValuePair.end();
+    std::map::const_iterator it, end = rGroup.m_KeyValuePair.end();
 
     for (it = rGroup.m_KeyValuePair.begin(); it != end; ++it)
     {
-        const string& rKey = it->first;
-        const string& rValue = it->second;
+        const AZStd::string& rKey = it->first;
+        const AZStd::string& rValue = it->second;
 
         if (pExclude)
         {
@@ -674,7 +674,7 @@ bool CXConsoleVariableCVarGroup::TestCVars(const SCVarGroup& rGroup, const ICVar
 
 
 
-string CXConsoleVariableCVarGroup::GetValueSpec(const string& sKey, const int* pSpec) const
+AZStd::string CXConsoleVariableCVarGroup::GetValueSpec(const AZStd::string& sKey, const int* pSpec) const
 {
     if (pSpec)
     {
@@ -685,7 +685,7 @@ string CXConsoleVariableCVarGroup::GetValueSpec(const string& sKey, const int* p
             const SCVarGroup* pGrp = itGrp->second;
 
             // check in spec
-            std::map::const_iterator it = pGrp->m_KeyValuePair.find(sKey);
+            std::map::const_iterator it = pGrp->m_KeyValuePair.find(sKey);
 
             if (it != pGrp->m_KeyValuePair.end())
             {
@@ -695,7 +695,7 @@ string CXConsoleVariableCVarGroup::GetValueSpec(const string& sKey, const int* p
     }
 
     // check in default
-    std::map::const_iterator it = m_CVarGroupDefault.m_KeyValuePair.find(sKey);
+    std::map::const_iterator it = m_CVarGroupDefault.m_KeyValuePair.find(sKey);
 
     if (it != m_CVarGroupDefault.m_KeyValuePair.end())
     {
@@ -708,14 +708,14 @@ string CXConsoleVariableCVarGroup::GetValueSpec(const string& sKey, const int* p
 
 void CXConsoleVariableCVarGroup::ApplyCVars(const SCVarGroup& rGroup, const SCVarGroup* pExclude)
 {
-    std::map::const_iterator it, end = rGroup.m_KeyValuePair.end();
+    std::map::const_iterator it, end = rGroup.m_KeyValuePair.end();
 
     bool wasProcessingGroup = m_pConsole->GetIsProcessingGroup();
     m_pConsole->SetProcessingGroup(true);
 
     for (it = rGroup.m_KeyValuePair.begin(); it != end; ++it)
     {
-        const string& rKey = it->first;
+        const AZStd::string& rKey = it->first;
 
         if (pExclude)
         {
@@ -728,7 +728,7 @@ void CXConsoleVariableCVarGroup::ApplyCVars(const SCVarGroup& rGroup, const SCVa
         // Useful for debugging cvar groups
         //CryLogAlways("[CVARS]: [APPLY] ([%s]) [%s] = [%s]", GetName(), rKey.c_str(), it->second.c_str());
 
-        m_pConsole->LoadConfigVar(rKey, it->second);
+        m_pConsole->LoadConfigVar(rKey.c_str(), it->second.c_str());
     }
 
     m_pConsole->SetProcessingGroup(wasProcessingGroup);
diff --git a/Code/Legacy/CrySystem/XConsoleVariable.h b/Code/Legacy/CrySystem/XConsoleVariable.h
index 0dd05cdb07..e4f9c14355 100644
--- a/Code/Legacy/CrySystem/XConsoleVariable.h
+++ b/Code/Legacy/CrySystem/XConsoleVariable.h
@@ -16,6 +16,7 @@
 #include "SFunctor.h"
 
 class CXConsole;
+typedef AZStd::fixed_string<512> stack_string;
 
 inline int64 TextToInt64(const char* s, int64 nCurrent, bool bBitfield)
 {
@@ -184,13 +185,13 @@ public:
 
     // interface ICVar --------------------------------------------------------------------------------------
 
-    virtual int GetIVal() const { return atoi(m_sValue); }
-    virtual int64 GetI64Val() const { return _atoi64(m_sValue); }
-    virtual float GetFVal() const { return (float)atof(m_sValue); }
-    virtual const char* GetString() const { return m_sValue; }
+    virtual int GetIVal() const { return atoi(m_sValue.c_str()); }
+    virtual int64 GetI64Val() const { return _atoi64(m_sValue.c_str()); }
+    virtual float GetFVal() const { return (float)atof(m_sValue.c_str()); }
+    virtual const char* GetString() const { return m_sValue.c_str(); }
     virtual void ResetImpl()
     {
-        Set(m_sDefault);
+        Set(m_sDefault.c_str());
     }
     virtual void Set(const char* s)
     {
@@ -219,8 +220,7 @@ public:
 
     virtual void Set(float f)
     {
-        stack_string s;
-        s.Format("%g", f);
+        stack_string s = stack_string::format("%g", f);
 
         if ((m_sValue == s.c_str()) && (m_nFlags & VF_ALWAYSONCHANGE) == 0)
         {
@@ -233,8 +233,7 @@ public:
 
     virtual void Set(int i)
     {
-        stack_string s;
-        s.Format("%d", i);
+        stack_string s = stack_string::format("%d", i);
 
         if ((m_sValue == s.c_str()) && (m_nFlags & VF_ALWAYSONCHANGE) == 0)
         {
@@ -248,8 +247,8 @@ public:
 
     virtual void GetMemoryUsage(class ICrySizer* pSizer) const { pSizer->AddObject(this, sizeof(*this)); }
 private: // --------------------------------------------------------------------------------------------
-    string m_sValue;                                            
-    string m_sDefault;                                                                              //!<
+    AZStd::string m_sValue;                                            
+    AZStd::string m_sDefault;                                                                              //!<
 };
 
 
@@ -296,8 +295,7 @@ public:
             return;
         }
 
-        stack_string s;
-        s.Format("%d", i);
+        stack_string s = stack_string::format("%d", i);
 
         if (m_pConsole->OnBeforeVarChange(this, s.c_str()))
         {
@@ -364,8 +362,7 @@ public:
             return;
         }
 
-        stack_string s;
-        s.Format("%lld", i);
+        stack_string s = stack_string::format("%lld", i);
 
         if (m_pConsole->OnBeforeVarChange(this, s.c_str()))
         {
@@ -442,8 +439,7 @@ public:
             return;
         }
 
-        stack_string s;
-        s.Format("%g", f);
+        stack_string s = stack_string::format("%g", f);
 
         if (m_pConsole->OnBeforeVarChange(this, s.c_str()))
         {
@@ -718,7 +714,7 @@ public:
     {
         return m_sValue.c_str();
     }
-    virtual void ResetImpl() { Set(m_sDefault); }
+    virtual void ResetImpl() { Set(m_sDefault.c_str()); }
     virtual void Set(const char* s)
     {
         if ((m_sValue == s) && (m_nFlags & VF_ALWAYSONCHANGE) == 0)
@@ -740,14 +736,12 @@ public:
     }
     virtual void Set(float f)
     {
-        stack_string s;
-        s.Format("%g", f);
+        stack_string s = stack_string::format("%g", f);
         Set(s.c_str());
     }
     virtual void Set(int i)
     {
-        stack_string s;
-        s.Format("%d", i);
+        stack_string s = stack_string::format("%d", i);
         Set(s.c_str());
     }
     virtual int GetType() { return CVAR_STRING; }
@@ -755,8 +749,8 @@ public:
     virtual void GetMemoryUsage(class ICrySizer* pSizer) const { pSizer->AddObject(this, sizeof(*this)); }
 private: // --------------------------------------------------------------------------------------------
 
-    string m_sValue;
-    string m_sDefault;
+    AZStd::string m_sValue;
+    AZStd::string m_sDefault;
     const char*& m_userPtr;                                         //!<
 };
 
@@ -778,7 +772,7 @@ public:
 
     // Returns:
     //   part of the help string - useful to log out detailed description without additional help text
-    string GetDetailedInfo() const;
+    AZStd::string GetDetailedInfo() const;
 
     // interface ICVar -----------------------------------------------------------------------------------
 
@@ -809,7 +803,7 @@ private: // --------------------------------------------------------------------
 
     struct SCVarGroup
     {
-        std::map                         m_KeyValuePair;                 // e.g. m_KeyValuePair["r_fullscreen"]="0"
+        std::map                      m_KeyValuePair;                 // e.g. m_KeyValuePair["r_fullscreen"]="0"
         void GetMemoryUsage(class ICrySizer* pSizer) const
         {
             pSizer->AddObject(m_KeyValuePair);
@@ -818,15 +812,15 @@ private: // --------------------------------------------------------------------
 
     SCVarGroup                                                      m_CVarGroupDefault;
     typedef std::map      TCVarGroupStateMap;
-    TCVarGroupStateMap                                      m_CVarGroupStates;
-    string                                                              m_sDefaultValue;                // used by OnLoadConfigurationEntry_End()
+    TCVarGroupStateMap                                              m_CVarGroupStates;
+    AZStd::string                                                   m_sDefaultValue;                // used by OnLoadConfigurationEntry_End()
 
     void ApplyCVars(const SCVarGroup& rGroup, const SCVarGroup* pExclude = 0);
 
     // Arguments:
     //   sKey - must exist, at least in default
     //   pSpec - can be 0
-    string GetValueSpec(const string& sKey, const int* pSpec = 0) const;
+    AZStd::string GetValueSpec(const AZStd::string& sKey, const int* pSpec = 0) const;
 
     // should only be used by TestCVars()
     // Returns:

From f665f572f3790324e9d498902c00887f09a53438 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 30 Jul 2021 18:53:50 -0700
Subject: [PATCH 031/205] Gems/Atom builds

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/BaseLibrary.cpp                   |   3 +-
 Code/Editor/Core/QtEditorApplication.cpp      |   7 +-
 Code/Editor/IEditorImpl.cpp                   |   2 +-
 Code/Editor/Include/IFileUtil.h               |   1 -
 Code/Editor/QtUtil.h                          |  24 ----
 Code/Editor/Util/FileUtil.h                   |   1 -
 Code/Editor/Util/PathUtil.cpp                 |  37 +++---
 Code/Editor/Util/PathUtil.h                   |  16 +--
 .../AzCore/AzCore/std/string/conversions.h    |  35 +++++-
 Code/Legacy/CryCommon/IStatObj.h              |  12 +-
 Code/Legacy/CryCommon/IXml.h                  |   8 +-
 .../Support/platform/win/CrashSupport_win.cpp |   5 +-
 Code/Tools/GridHub/GridHub/gridhub.cpp        |   8 +-
 Code/Tools/GridHub/GridHub/main.cpp           | 106 +++++++++---------
 .../Code/Source/LuxCore/LuxCoreRenderer.cpp   |   2 +-
 .../Windows/LaunchLuxCoreUI_Windows.cpp       |  12 +-
 .../Windows/RHI/PhysicalDevice_Windows.cpp    |   2 +-
 .../Windows/RHI/WindowsVersionQuery.cpp       |   4 +-
 Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp  |   8 +-
 Gems/CrashReporting/Code/CMakeLists.txt       |   1 +
 .../Code/Tests/AnimGraphCopyPasteTests.cpp    |   2 +-
 Gems/Maestro/Code/Source/Cinematics/Movie.cpp |   4 +-
 Gems/Maestro/Code/Source/Cinematics/Movie.h   |   2 +-
 .../SaveData_SystemComponent_Windows.cpp      |   3 +-
 24 files changed, 159 insertions(+), 146 deletions(-)

diff --git a/Code/Editor/BaseLibrary.cpp b/Code/Editor/BaseLibrary.cpp
index ee1c85756d..3c3ccfe13d 100644
--- a/Code/Editor/BaseLibrary.cpp
+++ b/Code/Editor/BaseLibrary.cpp
@@ -258,9 +258,8 @@ bool CBaseLibrary::SaveLibrary(const char* name, bool saveEmptyLibrary)
     }
     if (!bRes)
     {
-        string strMessage;
         QByteArray filenameUtf8 = fileName.toUtf8();
-        strMessage.Format("The file %s is read-only and the save of the library couldn't be performed. Try to remove the \"read-only\" flag or check-out the file and then try again.", filenameUtf8.data());
+        AZStd::string strMessage = AZStd::string::format("The file %s is read-only and the save of the library couldn't be performed. Try to remove the \"read-only\" flag or check-out the file and then try again.", filenameUtf8.data());
         CryMessageBox(strMessage.c_str(), "Saving Error", MB_OK | MB_ICONWARNING);
     }
     return bRes;
diff --git a/Code/Editor/Core/QtEditorApplication.cpp b/Code/Editor/Core/QtEditorApplication.cpp
index 46e789cd7c..9ec3b57e29 100644
--- a/Code/Editor/Core/QtEditorApplication.cpp
+++ b/Code/Editor/Core/QtEditorApplication.cpp
@@ -206,11 +206,8 @@ namespace
 
     static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message)
     {
-#if defined(WIN32) || defined(WIN64)
-        OutputDebugStringW(L"Qt: ");
-        OutputDebugStringW(reinterpret_cast(message.utf16()));
-        OutputDebugStringW(L"\n");
-#endif
+        AZ::Debug::Platform::OutputToDebugger("Qt", message.utf8());
+        AZ::Debug::Platform::OutputToDebugger(nullptr, "\n");
     }
 }
 
diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp
index c09c0a8e62..2e755bd36a 100644
--- a/Code/Editor/IEditorImpl.cpp
+++ b/Code/Editor/IEditorImpl.cpp
@@ -1109,7 +1109,7 @@ void CEditorImpl::DetectVersion()
 
     char ver[1024 * 8];
 
-    GetModuleFileName(NULL, exe, _MAX_PATH);
+    AZ::Utils::GetExecutablePath(exe, _MAX_PATH);
 
     int verSize = GetFileVersionInfoSize(exe, &dwHandle);
     if (verSize > 0)
diff --git a/Code/Editor/Include/IFileUtil.h b/Code/Editor/Include/IFileUtil.h
index f402786e67..8cb86b812e 100644
--- a/Code/Editor/Include/IFileUtil.h
+++ b/Code/Editor/Include/IFileUtil.h
@@ -8,7 +8,6 @@
 
 #pragma once
 
-#include "StringUtils.h"
 #include "../Include/SandboxAPI.h"
 
 class QWidget;
diff --git a/Code/Editor/QtUtil.h b/Code/Editor/QtUtil.h
index bb1f8ba427..a9aaadc491 100644
--- a/Code/Editor/QtUtil.h
+++ b/Code/Editor/QtUtil.h
@@ -10,8 +10,6 @@
 #pragma once
 
 #include 
-#include 
-#include "UnicodeFunctions.h"
 
 #include 
 #include 
@@ -36,28 +34,6 @@ public:
 
 namespace QtUtil
 {
-    // From QString to CryString
-    inline CryStringT ToString(const QString& str)
-    {
-        return Unicode::Convert >(str);
-    }
-
-    // From CryString to QString
-    inline QString ToQString(const CryStringT& str)
-    {
-        return Unicode::Convert(str);
-    }
-
-    // From const char * to QString
-    inline QString ToQString(const char* str, size_t len = -1)
-    {
-        if (len == -1)
-        {
-            len = strlen(str);
-        }
-        return Unicode::Convert(str, str + len);
-    }
-
     // Replacement for CString::trimRight()
     inline QString trimRight(const QString& str)
     {
diff --git a/Code/Editor/Util/FileUtil.h b/Code/Editor/Util/FileUtil.h
index 000215e98d..06cceaaafc 100644
--- a/Code/Editor/Util/FileUtil.h
+++ b/Code/Editor/Util/FileUtil.h
@@ -10,7 +10,6 @@
 #pragma once
 
 #include "CryThread.h"
-#include "StringUtils.h"
 #include "../Include/SandboxAPI.h"
 #include 
 #include 
diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp
index 4bb5c20ece..e91d85e4d2 100644
--- a/Code/Editor/Util/PathUtil.cpp
+++ b/Code/Editor/Util/PathUtil.cpp
@@ -15,24 +15,20 @@
 #include  // for ebus events
 #include 
 #include 
+#include 
 
 #include 
 
-namespace
-{
-    string g_currentModName; // folder name only!
-}
-
 namespace Path
 {
     //////////////////////////////////////////////////////////////////////////
     void SplitPath(const QString& rstrFullPathFilename, QString& rstrDriveLetter, QString& rstrDirectory, QString& rstrFilename, QString& rstrExtension)
     {
-        string          strFullPathString(rstrFullPathFilename.toUtf8().data());
-        string          strDriveLetter;
-        string          strDirectory;
-        string          strFilename;
-        string          strExtension;
+        AZStd::string   strFullPathString(rstrFullPathFilename.toUtf8().data());
+        AZStd::string   strDriveLetter;
+        AZStd::string   strDirectory;
+        AZStd::string   strFilename;
+        AZStd::string   strExtension;
 
         char*           szPath((char*)strFullPathString.c_str());
         char*           pchLastPosition(szPath);
@@ -81,16 +77,16 @@ namespace Path
             strFilename.assign(pchLastPosition, pchCurrentPosition);
         }
 
-        rstrDriveLetter = strDriveLetter;
-        rstrDirectory = strDirectory;
-        rstrFilename = strFilename;
-        rstrExtension = strExtension;
+        rstrDriveLetter = strDriveLetter.c_str();
+        rstrDirectory = strDirectory.c_str();
+        rstrFilename = strFilename.c_str();
+        rstrExtension = strExtension.c_str();
     }
     //////////////////////////////////////////////////////////////////////////
     void GetDirectoryQueue(const QString& rstrSourceDirectory, QStringList& rcstrDirectoryTree)
     {
-        string                      strCurrentDirectoryName;
-        string                      strSourceDirectory(rstrSourceDirectory.toUtf8().data());
+        AZStd::string           strCurrentDirectoryName;
+        AZStd::string           strSourceDirectory(rstrSourceDirectory.toUtf8().data());
         const char*             szSourceDirectory(strSourceDirectory.c_str());
         const char*             pchCurrentPosition(szSourceDirectory);
         const char*             pchLastPosition(szSourceDirectory);
@@ -207,7 +203,9 @@ namespace Path
 
     bool IsFolder(const char* pPath)
     {
-        DWORD attrs = GetFileAttributes(pPath);
+        AZStd::wstring pPathW;
+        AZStd::to_wstring(pPathW, pPath);
+        DWORD attrs = GetFileAttributes(pPathW.c_str());
 
         if (attrs == FILE_ATTRIBUTE_DIRECTORY)
         {
@@ -255,16 +253,17 @@ namespace Path
     /// Get the data folder
     AZStd::string GetEditingGameDataFolder()
     {
+        static AZStd::string s_currentModName;
         // query the editor root.  The bus exists in case we want tools to be able to override this.
 
 
-        if (g_currentModName.empty())
+        if (s_currentModName.empty())
         {
             return GetGameAssetsFolder();
         }
         AZStd::string str(GetGameAssetsFolder());
         str += "Mods\\";
-        str += g_currentModName;
+        str += s_currentModName;
         return str;
     }
 
diff --git a/Code/Editor/Util/PathUtil.h b/Code/Editor/Util/PathUtil.h
index 98f484ec94..30887e698b 100644
--- a/Code/Editor/Util/PathUtil.h
+++ b/Code/Editor/Util/PathUtil.h
@@ -93,7 +93,7 @@ namespace Path
 #endif
         file = path_buffer;
     }
-    inline void Split(const string& filepath, string& path, string& file)
+    inline void Split(const AZStd::string& filepath, AZStd::string& path, AZStd::string& file)
     {
         char path_buffer[_MAX_PATH];
         char drive[_MAX_DRIVE];
@@ -101,7 +101,7 @@ namespace Path
         char fname[_MAX_FNAME];
         char ext[_MAX_EXT];
 #ifdef AZ_COMPILER_MSVC
-        _splitpath_s(filepath, drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), 0, 0, 0, 0);
+        _splitpath_s(filepath.c_str(), drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), 0, 0, 0, 0);
         _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), drive, dir, 0, 0);
         path = path_buffer;
         _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), 0, 0, fname, ext);
@@ -137,7 +137,7 @@ namespace Path
         filename = fname;
         fext = ext;
     }
-    inline void Split(const string& filepath, string& path, string& filename, string& fext)
+    inline void Split(const AZStd::string& filepath, AZStd::string& path, AZStd::string& filename, AZStd::string& fext)
     {
         char path_buffer[_MAX_PATH];
         char drive[_MAX_DRIVE];
@@ -145,7 +145,7 @@ namespace Path
         char fname[_MAX_FNAME];
         char ext[_MAX_EXT];
 #ifdef AZ_COMPILER_MSVC
-        _splitpath_s(filepath, drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), fname, AZ_ARRAY_SIZE(fname), ext, AZ_ARRAY_SIZE(ext));
+        _splitpath_s(filepath.c_str(), drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), fname, AZ_ARRAY_SIZE(fname), ext, AZ_ARRAY_SIZE(ext));
         _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), drive, dir, 0, 0);
 #else
         _splitpath(filepath, drive, dir, fname, ext);
@@ -271,7 +271,7 @@ namespace Path
     }
 
     template
-    inline void AddBackslash(AZstd::fixed_string* path)
+    inline void AddBackslash(AZStd::fixed_string* path)
     {
         if (path->empty())
         {
@@ -284,7 +284,7 @@ namespace Path
     }
 
     template
-    inline void AddSlash(AZstd::fixed_string* path)
+    inline void AddSlash(AZStd::fixed_string* path)
     {
         if (path->empty())
         {
@@ -357,7 +357,7 @@ namespace Path
     {
         return CaselessPaths(GetRelativePath(path, true));
     }
-    inline string FullPathToGamePath(const char* path)
+    inline AZStd::string FullPathToGamePath(const char* path)
     {
         return CaselessPaths(GetRelativePath(path, true)).toUtf8().data();
     }
@@ -394,7 +394,7 @@ namespace Path
     inline QString GetAudioLocalizationFolder(bool returnAbsolutePath)
     {
         // Omit the trailing slash!
-        QString sLocalizationFolder(QString(PathUtil::GetLocalizationFolder()).left(static_cast(PathUtil::GetLocalizationFolder().size()) - 1));
+        QString sLocalizationFolder(QString(PathUtil::GetLocalizationFolder().c_str()).left(static_cast(PathUtil::GetLocalizationFolder().size()) - 1));
 
         if (!sLocalizationFolder.isEmpty())
         {
diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index cb90881933..fcfe82ba5f 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -80,9 +80,7 @@ namespace AZStd
                 }
                 else
                 {
-                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
-                    using StringType = AZStd::basic_string;
-                    static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8");
+                    static_assert(false, "only wchar_t types of size 2 or 4 can be converted to utf8");
                 }
             }
 
@@ -123,6 +121,22 @@ namespace AZStd
                     static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
                 }
             }
+
+            static inline void to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last)
+            {
+                if constexpr (Size == 2)
+                {
+                    Utf8::Unchecked::utf8to16(first, last, dest, destSize);
+                }
+                else if constexpr (Size == 4)
+                {
+                    Utf8::Unchecked::utf8to32(first, last, dest, destSize);
+                }
+                else
+                {
+                    static_assert(false, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
+                }
+            }
         };
     }
     // 21.5: numeric conversions
@@ -348,7 +362,7 @@ namespace AZStd
     {
         if (srcLen == 0)
         {
-            srcLen = wcslen(str) + 1;
+            srcLen = wcslen(str);
         }
 
         if (srcLen > 0)
@@ -497,6 +511,19 @@ namespace AZStd
         return to_wstring(dest, src.c_str(), src.length());
     }
 
+    inline void to_wstring(wchar_t* dest, size_t destSize, const char* str, size_t srcLen = 0)
+    {
+        if (srcLen == 0)
+        {
+            srcLen = strlen(str) + 1;
+        }
+
+        if (srcLen > 0)
+        {
+            Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen + 1); // copy null terminator
+        }
+    }
+
     // Convert a range of chars to lower case
 #if defined(AZSTD_USE_OLD_RW_STL)
     template
diff --git a/Code/Legacy/CryCommon/IStatObj.h b/Code/Legacy/CryCommon/IStatObj.h
index ff3bbc41e3..4921ab3a25 100644
--- a/Code/Legacy/CryCommon/IStatObj.h
+++ b/Code/Legacy/CryCommon/IStatObj.h
@@ -201,7 +201,7 @@ struct IStreamable
     virtual void StartStreaming(bool bFinishNow, IReadStream_AutoPtr* ppStream) = 0;
     virtual int GetStreamableContentMemoryUsage(bool bJustForDebug = false) = 0;
     virtual void ReleaseStreamableContent() = 0;
-    virtual void GetStreamableName(string& sName) = 0;
+    virtual void GetStreamableName(AZStd::string& sName) = 0;
     virtual uint32 GetLastDrawMainFrameId() = 0;
     virtual bool IsUnloadable() const = 0;
 
@@ -239,8 +239,8 @@ struct IStatObj
         SSubObject() { bShadowProxy = 0; }
 
         EStaticSubObjectType nType;
-        string name;
-        string properties;
+        AZStd::string name;
+        AZStd::string properties;
         int nParent;          // Index of the parent sub object, if there`s hierarchy between them.
         Matrix34 tm;          // Transformation matrix.
         Matrix34 localTM;     // Local transformation matrix, relative to parent.
@@ -510,10 +510,10 @@ struct IStatObj
     virtual bool IsUnloadable() const = 0;
     virtual void SetCanUnload(bool value) = 0;
 
-    virtual string& GetFileName() = 0;
-    virtual const string& GetFileName() const = 0;
+    virtual AZStd::string& GetFileName() = 0;
+    virtual const AZStd::string& GetFileName() const = 0;
 
-    virtual const string& GetCGFNodeName() const = 0;
+    virtual const AZStd::string& GetCGFNodeName() const = 0;
 
     // Summary:
     //     Returns the filename of the object
diff --git a/Code/Legacy/CryCommon/IXml.h b/Code/Legacy/CryCommon/IXml.h
index a380ce167b..80c2415f9c 100644
--- a/Code/Legacy/CryCommon/IXml.h
+++ b/Code/Legacy/CryCommon/IXml.h
@@ -101,7 +101,13 @@ public:
     XmlString(const char* str)
         : AZStd::string(str) {};
 
-    operator const char*() const {
+    size_t GetAllocatedMemory() const
+    {
+        return sizeof(XmlString) + capacity() * sizeof(AZStd::string::value_type);
+    }
+
+    operator const char*() const
+    {
         return c_str();
     }
 };
diff --git a/Code/Tools/CrashHandler/Support/platform/win/CrashSupport_win.cpp b/Code/Tools/CrashHandler/Support/platform/win/CrashSupport_win.cpp
index 3933b5ea91..6010ac8e17 100644
--- a/Code/Tools/CrashHandler/Support/platform/win/CrashSupport_win.cpp
+++ b/Code/Tools/CrashHandler/Support/platform/win/CrashSupport_win.cpp
@@ -10,13 +10,14 @@
 #include 
 
 #include 
+#include 
 #include 
 
 namespace CrashHandler
 {
-    void GetExecutablePathA(char* pathBuffer, int& bufferSize)
+    void GetExecutablePath(char* pathBuffer, int& bufferSize)
     {
-        GetModuleFileNameA(nullptr, pathBuffer, bufferSize);
+        AZ::Utils::GetExecutablePath(pathBuffer, bufferSize);
     }
 
     void GetExecutablePathW(wchar_t* pathBuffer, int& bufferSize)
diff --git a/Code/Tools/GridHub/GridHub/gridhub.cpp b/Code/Tools/GridHub/GridHub/gridhub.cpp
index 3dbecf681f..978589ab74 100644
--- a/Code/Tools/GridHub/GridHub/gridhub.cpp
+++ b/Code/Tools/GridHub/GridHub/gridhub.cpp
@@ -358,13 +358,11 @@ GridHubComponent::GridHubComponent()
     m_isLogToFile = false;
     
 #ifdef AZ_PLATFORM_WINDOWS
-    TCHAR name[MAX_COMPUTERNAME_LENGTH + 1];
+    wchar_t name[MAX_COMPUTERNAME_LENGTH + 1];
     DWORD dwCompNameLen = AZ_ARRAY_SIZE(name);
-    if ( GetComputerName(name, &dwCompNameLen) != 0 ) 
+    if (GetComputerName(name, &dwCompNameLen) != 0) 
     {
-        char c[MAX_COMPUTERNAME_LENGTH + 1];
-        wcstombs(c, name, AZ_ARRAY_SIZE(c));
-        m_hubName = c;
+        AZStd::to_string(m_hubName, name);
     }
     else
 #endif
diff --git a/Code/Tools/GridHub/GridHub/main.cpp b/Code/Tools/GridHub/GridHub/main.cpp
index f02906e0d4..670367bf06 100644
--- a/Code/Tools/GridHub/GridHub/main.cpp
+++ b/Code/Tools/GridHub/GridHub/main.cpp
@@ -16,7 +16,6 @@
 #include 
 #include 
 #include 
-#include 
 #endif
 
 #include "gridhub.hxx"
@@ -39,6 +38,7 @@ AZ_POP_DISABLE_WARNING
 #include 
 #include 
 #include 
+#include 
 
 #ifdef AZ_PLATFORM_WINDOWS
 #include 
@@ -53,9 +53,9 @@ AZ_POP_DISABLE_WARNING
 #endif
 
 #ifdef AZ_PLATFORM_WINDOWS
-#define GRIDHUB_TSR_SUFFIX _T("_copyapp_")
-#define GRIDHUB_TSR_NAME _T("GridHub_copyapp_.exe")
-#define GRIDHUB_IMAGE_NAME _T("GridHub.exe")
+#define GRIDHUB_TSR_SUFFIX L"_copyapp_"
+#define GRIDHUB_TSR_NAME L"GridHub_copyapp_.exe"
+#define GRIDHUB_IMAGE_NAME L"GridHub.exe"
 #else
 #define GRIDHUB_TSR_SUFFIX "_copyapp_"
 #define GRIDHUB_TSR_NAME "GridHub_copyapp_"
@@ -191,7 +191,7 @@ protected:
          specializations.Append("gridhub");
      }
 
-    QString         m_originalExeFileName;
+     QString        m_originalExeFileName;
      QDateTime      m_originalExeLastModified;
      bool           m_monitorForExeChanges;
      bool           m_needToRelaunch;
@@ -305,22 +305,22 @@ public:
     {
 #ifdef AZ_PLATFORM_WINDOWS
         HRESULT hres;
-        TCHAR startupFolder[MAX_PATH] = {0};
-        TCHAR fullLinkName[MAX_PATH] = {0};
+        wchar_t startupFolder[MAX_PATH] = {0};
+        wchar_t fullLinkName[MAX_PATH] = {0};
 
         LPITEMIDLIST pidlFolder = NULL;
         hres = SHGetFolderLocation(0,/*CSIDL_COMMON_STARTUP all users required admin access*/CSIDL_STARTUP,NULL,0,&pidlFolder);
         if (SUCCEEDED(hres))
         {
-            if( SHGetPathFromIDList(pidlFolder,startupFolder) )
+            if (SHGetPathFromIDList(pidlFolder, startupFolder))
             {
-                _tcscat_s(fullLinkName,startupFolder);
-                _tcscat_s(fullLinkName,"\\Amazon Grid Hub.lnk");
+                wcscat_s(fullLinkName, startupFolder);
+                wcscat_s(fullLinkName, L"\\Amazon Grid Hub.lnk");
             }
             CoTaskMemFree(pidlFolder);
         }
 
-        if( moduleFilename.isEmpty() || _tcslen(fullLinkName) == 0 )
+        if( moduleFilename.isEmpty() || wcslen(fullLinkName) == 0 )
             return;
 
         // for development, never autoadd to startup
@@ -342,8 +342,8 @@ public:
                 IPersistFile* ppf;
 
                 // Set the path to the shortcut target and add the description.
-                psl->SetPath(moduleFilename.toUtf8().data());
-                psl->SetDescription("Amazon Grid Hub");
+                psl->SetPath(moduleFilename.toStdWString().c_str());
+                psl->SetDescription(L"Amazon Grid Hub");
 
                 // Query IShellLink for the IPersistFile interface, used for saving the
                 // shortcut in persistent storage.
@@ -351,16 +351,8 @@ public:
 
                 if (SUCCEEDED(hres))
                 {
-                    WCHAR wsz[MAX_PATH];
-
-                    // Ensure that the string is Unicode.
-                    MultiByteToWideChar(CP_ACP, 0, fullLinkName, -1, wsz, MAX_PATH);
-
-                    // Add code here to check return value from MultiByteWideChar
-                    // for success.
-
                     // Save the link by calling IPersistFile::Save.
-                    hres = ppf->Save(wsz, TRUE);
+                    hres = ppf->Save(fullLinkName, TRUE);
                     ppf->Release();
                 }
                 psl->Release();
@@ -412,13 +404,17 @@ GridHubApplication::Create(const Descriptor& descriptor, const StartupParameters
     {
         bool isError = false;
 #ifdef AZ_PLATFORM_WINDOWS
-        TCHAR originalExeFileName[MAX_PATH];
-        if (GetModuleFileName(NULL, originalExeFileName, AZ_ARRAY_SIZE(originalExeFileName)))
+        char originalExeFileName[MAX_PATH];
+        if (AZ::Utils::GetExecutablePath(originalExeFileName, AZ_ARRAY_SIZE(originalExeFileName)).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
         {
-            PathRemoveFileSpec(originalExeFileName);
-            PathAppend(originalExeFileName, GRIDHUB_IMAGE_NAME);
+            wchar_t originalExeFileNameW[MAX_PATH];
+            AZStd::to_wstring(originalExeFileNameW, MAX_PATH, originalExeFileName, MAX_PATH);
+            PathRemoveFileSpec(originalExeFileNameW);
+            PathAppend(originalExeFileNameW, GRIDHUB_IMAGE_NAME);
 
-            m_originalExeFileName = originalExeFileName;
+            AZStd::string finalExeFileName;
+            AZStd::to_string(finalExeFileName, originalExeFileNameW);
+            m_originalExeFileName = finalExeFileName.c_str();
 
             m_originalExeLastModified = QFileInfo(m_originalExeFileName).lastModified();
         }
@@ -489,18 +485,20 @@ void GridHubApplication::RegisterCoreComponents()
 void CopyAndRun(bool failSilently)
 {
 #ifdef AZ_PLATFORM_WINDOWS
-    TCHAR myFileName[MAX_PATH] = { _T(0) };
-    if (GetModuleFileName(NULL, myFileName, MAX_PATH ))
+    char myFileName[MAX_PATH] = { 0 };
+    if (AZ::Utils::GetExecutablePath(myFileName, MAX_PATH).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
     {
-        TCHAR sourceProcPath[MAX_PATH] = { _T(0) };
-        TCHAR targetProcPath[MAX_PATH] = { _T(0) };
-        TCHAR procDrive[MAX_PATH] = { _T(0) };
-        TCHAR procDir[MAX_PATH] = { _T(0) };
-        TCHAR procFname[MAX_PATH] = { _T(0) };
-        TCHAR procExt[MAX_PATH] = { _T(0) };
-        _tsplitpath_s(myFileName, procDrive, procDir, procFname, procExt);
-        _tmakepath_s(sourceProcPath, procDrive, procDir, GRIDHUB_IMAGE_NAME, NULL);
-        _tmakepath_s(targetProcPath, procDrive, procDir, GRIDHUB_TSR_NAME, NULL);
+        wchar_t myFileNameW[MAX_PATH] = { 0 };
+        AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName, MAX_PATH);
+        wchar_t sourceProcPath[MAX_PATH] = { 0 };
+        wchar_t targetProcPath[MAX_PATH] = { 0 };
+        wchar_t procDrive[MAX_PATH] = { 0 };
+        wchar_t procDir[MAX_PATH] = { 0 };
+        wchar_t procFname[MAX_PATH] = { 0 };
+        wchar_t procExt[MAX_PATH] = { 0 };
+        _wsplitpath_s(myFileNameW, procDrive, procDir, procFname, procExt);
+        _wmakepath_s(sourceProcPath, procDrive, procDir, GRIDHUB_IMAGE_NAME, NULL);
+        _wmakepath_s(targetProcPath, procDrive, procDir, GRIDHUB_TSR_NAME, NULL);
         if (CopyFileEx(sourceProcPath, targetProcPath, NULL, NULL, NULL, 0))
         {
             STARTUPINFO si;
@@ -527,9 +525,9 @@ void CopyAndRun(bool failSilently)
         {
             if (!failSilently)
             {
-                TCHAR errorMsg[1024] = { _T(0) };
-                _stprintf_s(errorMsg, _T("Failed to copy GridHub. Make sure that %s%s is writable!"), procFname, procExt);
-                MessageBox(NULL, errorMsg, NULL, MB_ICONSTOP|MB_OK);
+                wchar_t errorMsg[1024] = { 0 };
+                swprintf_s(errorMsg, L"Failed to copy GridHub. Make sure that %s%s is writable!", procFname, procExt);
+                MessageBoxW(NULL, errorMsg, NULL, MB_ICONSTOP|MB_OK);
             }
         }
     }
@@ -565,16 +563,18 @@ void CopyAndRun(bool failSilently)
 void RelaunchImage()
 {
 #ifdef AZ_PLATFORM_WINDOWS
-    TCHAR myFileName[MAX_PATH] = { _T(0) };
-    if (GetModuleFileName(NULL, myFileName, MAX_PATH))
+    char myFileName[MAX_PATH] = { 0 };
+    if (AZ::Utils::GetExecutablePath(myFileName, MAX_PATH).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
     {
-        TCHAR targetProcPath[MAX_PATH] = { _T(0) };
-        TCHAR procDrive[MAX_PATH] = { _T(0) };
-        TCHAR procDir[MAX_PATH] = { _T(0) };
-        TCHAR procFname[MAX_PATH] = { _T(0) };
-        TCHAR procExt[MAX_PATH] = { _T(0) };
-        _tsplitpath_s(myFileName, procDrive, procDir, procFname, procExt);
-        _tmakepath_s(targetProcPath, procDrive, procDir, GRIDHUB_IMAGE_NAME, NULL);
+        wchar_t myFileNameW[MAX_PATH] = { 0 };
+        AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName, MAX_PATH);
+        wchar_t targetProcPath[MAX_PATH] = { 0 };
+        wchar_t procDrive[MAX_PATH] = { 0 };
+        wchar_t procDir[MAX_PATH] = { 0 };
+        wchar_t procFname[MAX_PATH] = { 0 };
+        wchar_t procExt[MAX_PATH] = { 0 };
+        _wsplitpath_s(myFileNameW, procDrive, procDir, procFname, procExt);
+        _wmakepath_s(targetProcPath, procDrive, procDir, GRIDHUB_IMAGE_NAME, NULL);
 
         STARTUPINFO si;
         PROCESS_INFORMATION pi;
@@ -635,8 +635,8 @@ int main(int argc, char *argv[])
     {
 
 #ifdef AZ_PLATFORM_WINDOWS
-        TCHAR exeFileName[MAX_PATH];
-        if( GetModuleFileName(NULL,exeFileName,AZ_ARRAY_SIZE(exeFileName)) )
+        char exeFileName[MAX_PATH];
+        if (AZ::Utils::GetExecutablePath(exeFileName, AZ_ARRAY_SIZE(exeFileName)).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
 #elif defined AZ_PLATFORM_LINUX
         //KDAB_TODO
         char exeFileName[MAXPATHLEN];
@@ -661,7 +661,7 @@ int main(int argc, char *argv[])
         {
 #ifdef AZ_PLATFORM_WINDOWS
             // Create a OS named mutex while the OS is running
-            HANDLE hInstanceMutex = CreateMutex(NULL,TRUE,"Global\\GridHub-Instance");
+            HANDLE hInstanceMutex = CreateMutex(NULL, TRUE, L"Global\\GridHub-Instance");
             AZ_Assert(hInstanceMutex!=NULL,"Failed to create OS mutex [GridHub-Instance]\n");
             if( hInstanceMutex != NULL && GetLastError() == ERROR_ALREADY_EXISTS)
             {
diff --git a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreRenderer.cpp b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreRenderer.cpp
index 40fcbc7f31..c753079d5b 100644
--- a/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreRenderer.cpp
+++ b/Gems/Atom/Feature/Common/Code/Source/LuxCore/LuxCoreRenderer.cpp
@@ -19,7 +19,7 @@
 
 namespace LuxCoreUI
 {
-    void LaunchLuxCoreUI(const AZStd::string& luxCoreExeFullPath, AZStd::string& commandLine);
+    void LaunchLuxCoreUI(const AZStd::string& luxCoreExeFullPath, const AZStd::string& commandLine);
 }
 
 namespace AZ
diff --git a/Gems/Atom/Feature/Common/Code/Source/Platform/Windows/LaunchLuxCoreUI_Windows.cpp b/Gems/Atom/Feature/Common/Code/Source/Platform/Windows/LaunchLuxCoreUI_Windows.cpp
index 3c8f304cb6..7f15949201 100644
--- a/Gems/Atom/Feature/Common/Code/Source/Platform/Windows/LaunchLuxCoreUI_Windows.cpp
+++ b/Gems/Atom/Feature/Common/Code/Source/Platform/Windows/LaunchLuxCoreUI_Windows.cpp
@@ -7,11 +7,12 @@
  */
 
 #include 
+#include 
 #include 
 
 namespace LuxCoreUI
 {
-    void LaunchLuxCoreUI(const AZStd::string& luxCoreExeFullPath, AZStd::string& commandLine)
+    void LaunchLuxCoreUI(const AZStd::string& luxCoreExeFullPath, const AZStd::string& commandLine)
     {
         STARTUPINFO si;
         PROCESS_INFORMATION pi;
@@ -20,9 +21,14 @@ namespace LuxCoreUI
         si.cb = sizeof(si);
         ZeroMemory(&pi, sizeof(pi));
 
+        AZStd::wstring luxCoreExeFullPathW;
+        AZStd::to_wstring(luxCoreExeFullPathW, luxCoreExeFullPath.c_str());
+        AZStd::wstring commandLineW;
+        AZStd::to_wstring(commandLineW, commandLine.c_str());
+
         // start the program up
-        CreateProcess(luxCoreExeFullPath.data(),   // the path
-            commandLine.data(),        // Command line
+        CreateProcessW(luxCoreExeFullPathW.c_str(),   // the path
+            commandLineW.data(),        // Command line
             NULL,           // Process handle not inheritable
             NULL,           // Thread handle not inheritable
             FALSE,          // Set handle inheritance to FALSE
diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/PhysicalDevice_Windows.cpp b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/PhysicalDevice_Windows.cpp
index 6e5206fc00..2c56a860e8 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/PhysicalDevice_Windows.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/PhysicalDevice_Windows.cpp
@@ -78,7 +78,7 @@ namespace AZ
             }
 
             constexpr uint32_t SubKeyLength = 256;
-            char subKeyName[SubKeyLength];
+            wchar_t subKeyName[SubKeyLength];
 
             uint32_t driverVersion = 0;
 
diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp
index 0301d48454..91f0a712dd 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp
@@ -18,7 +18,7 @@ namespace AZ
             bool GetWindowsVersionFromSystemDLL(WindowsVersion* windowsVersion)
             {
                 // We get the file version of one of the system DLLs to get the OS version.
-                constexpr const char* dllName = "Kernel32.dll";
+                constexpr const wchar_t* dllName = L"Kernel32.dll";
                 VS_FIXEDFILEINFO* fileInfo = nullptr;
                 DWORD handle;
                 DWORD infoSize = GetFileVersionInfoSize(dllName, &handle);
@@ -28,7 +28,7 @@ namespace AZ
                     if (GetFileVersionInfo(dllName, handle, infoSize, versionData.data()) != 0)
                     {
                         UINT len;
-                        const char* subBlock = "\\";
+                        const wchar_t* subBlock = L"\\";
                         if (VerQueryValue(versionData.data(), subBlock, reinterpret_cast(&fileInfo), &len) != 0)
                         {
                             windowsVersion->m_majorVersion = HIWORD(fileInfo->dwProductVersionMS);
diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp
index db15930c01..f61aa3f67f 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp
@@ -13,9 +13,13 @@ namespace AZ
     namespace DX12
     {
         FenceEvent::FenceEvent(const char* name)
-            : m_EventHandle(CreateEvent(nullptr, false, false, name))
+            : m_EventHandle(nullptr)
             , m_name(name)
-        {}
+        {
+            AZStd::wstring nameW;
+            AZStd::to_wstring(nameW, name);
+            m_EventHandle = CreateEvent(nullptr, false, false, nameW.c_str());
+        }
 
         FenceEvent::~FenceEvent()
         {
diff --git a/Gems/CrashReporting/Code/CMakeLists.txt b/Gems/CrashReporting/Code/CMakeLists.txt
index 37224ea1aa..b12b5d8944 100644
--- a/Gems/CrashReporting/Code/CMakeLists.txt
+++ b/Gems/CrashReporting/Code/CMakeLists.txt
@@ -28,6 +28,7 @@ ly_add_target(
     BUILD_DEPENDENCIES
         PRIVATE
             AZ::CrashHandler
+            AZ::AzCore
 )
 
 # Load the "Gem::CrashReporting" module in Clients and Servers
diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphCopyPasteTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphCopyPasteTests.cpp
index eb16a1a57c..4feb8cd86a 100644
--- a/Gems/EMotionFX/Code/Tests/AnimGraphCopyPasteTests.cpp
+++ b/Gems/EMotionFX/Code/Tests/AnimGraphCopyPasteTests.cpp
@@ -159,7 +159,7 @@ namespace EMotionFX
                     (azrtti_typeid<>(conditionPrototype) != azrtti_typeid()))
                 {
                     AZ::TypeId type = azrtti_typeid<>(conditionPrototype);
-                    OutputDebugString(AZStd::string::format("Condition: Name=%s, Type=%s\n", conditionPrototype->GetPaletteName(), type.ToString().c_str()).c_str());
+                    AZ::Debug::Platform::OutputToDebugger(nullptr, AZStd::string::format("Condition: Name=%s, Type=%s\n", conditionPrototype->GetPaletteName(), type.ToString().c_str()).c_str());
                     result.emplace_back(azrtti_typeid<>(conditionPrototype));
                 }
             }
diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
index 2d5aa7b410..a6d9e47eb1 100644
--- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
@@ -1963,7 +1963,7 @@ void CLightAnimWrapper::InvalidateAllNodes()
 
 CLightAnimWrapper* CLightAnimWrapper::FindLightAnim(const char* name)
 {
-    LightAnimWrapperCache::const_iterator it = ms_lightAnimWrapperCache.find(CONST_TEMP_STRING(name));
+    LightAnimWrapperCache::const_iterator it = ms_lightAnimWrapperCache.find(name);
     return it != ms_lightAnimWrapperCache.end() ? (*it).second : 0;
 }
 
@@ -1976,7 +1976,7 @@ void CLightAnimWrapper::CacheLightAnim(const char* name, CLightAnimWrapper* p)
 //////////////////////////////////////////////////////////////////////////
 void CLightAnimWrapper::RemoveCachedLightAnim(const char* name)
 {
-    ms_lightAnimWrapperCache.erase(CONST_TEMP_STRING(name));
+    ms_lightAnimWrapperCache.erase(name);
 }
 
 #ifdef MOVIESYSTEM_SUPPORT_EDITING
diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.h b/Gems/Maestro/Code/Source/Cinematics/Movie.h
index cb97cfc40b..6ac857d652 100644
--- a/Gems/Maestro/Code/Source/Cinematics/Movie.h
+++ b/Gems/Maestro/Code/Source/Cinematics/Movie.h
@@ -48,7 +48,7 @@ public:
     static void InvalidateAllNodes();
 
 private:
-    typedef std::map LightAnimWrapperCache;
+    typedef std::map LightAnimWrapperCache;
     static StaticInstance ms_lightAnimWrapperCache;
     static AZStd::intrusive_ptr ms_pLightAnimSet;
 
diff --git a/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp b/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp
index 236b2f525c..2e473cfea7 100644
--- a/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp
+++ b/Gems/SaveData/Code/Source/Platform/Windows/SaveData_SystemComponent_Windows.cpp
@@ -10,6 +10,7 @@
 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -99,7 +100,7 @@ namespace SaveData
     AZStd::string GetExecutableName()
     {
         char moduleFileName[AZ_MAX_PATH_LEN];
-        GetModuleFileNameA(nullptr, moduleFileName, AZ_MAX_PATH_LEN);
+        AZ::Utils::GetExecutablePath(moduleFileName, AZ_MAX_PATH_LEN);
 
         const AZStd::string moduleFileNameString(moduleFileName);
         const size_t executableNameStart = moduleFileNameString.find_last_of('\\') + 1;

From b9cfce8165fd368018a6ea73f25f42828f523899 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 09:26:06 -0700
Subject: [PATCH 032/205] Gems/AtomLyIntegration

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Platform/Windows/FFontXML_Windows.cpp     |  7 +++-
 .../AtomFont/Code/Source/FFont.cpp            | 42 ++++++++++++-------
 .../AtomFont/Code/Source/FontRenderer.cpp     |  7 ++--
 .../AtomFont/Code/Source/FontTexture.cpp      | 10 ++---
 .../AtomFont/Code/Source/GlyphCache.cpp       |  2 +-
 .../Source/AnimGraph/GameController.cpp       | 21 +++++-----
 6 files changed, 53 insertions(+), 36 deletions(-)

diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
index 4c923c43c4..dc7c6ccbb2 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Windows/FFontXML_Windows.cpp
@@ -9,6 +9,7 @@
 #include 
 
 #include 
+#include 
 
 #include 
 
@@ -16,11 +17,13 @@ namespace AtomFontInternal
 {
     void XmlFontShader::FoundElementImpl()
     {
-        TCHAR sysFontPath[MAX_PATH];
-        if (SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0, SHGFP_TYPE_DEFAULT, sysFontPath)))
+        wchar_t sysFontPathW[MAX_PATH];
+        if (SUCCEEDED(SHGetFolderPath(0, CSIDL_FONTS, 0, SHGFP_TYPE_DEFAULT, sysFontPathW)))
         {
             const AZ::IO::PathView fontName = AZ::IO::PathView(m_strFontPath.c_str()).Filename();
 
+            AZStd::string sysFontPath;
+            AZStd::to_string(sysFontPath, sysFontPathW);
             AZ::IO::Path newFontPath(sysFontPath);
             newFontPath /= fontName;
             m_font->Load(newFontPath.c_str(), m_FontTexSize.x, m_FontTexSize.y, m_slotSizes.x, m_slotSizes.y, CreateTTFFontFlag(m_FontSmoothMethod, m_FontSmoothAmount), m_SizeRatio);
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
index ddb2fa6292..fe6f733abc 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
@@ -13,6 +13,8 @@
 
 #if !defined(USE_NULLFONT_ALWAYS)
 
+#include 
+
 #include 
 #include 
 #include 
@@ -26,7 +28,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 
 #include 
@@ -409,6 +410,9 @@ Vec2 AZ::FFont::GetTextSizeUInternal(
     const size_t fxIdx = ctx.m_fxIdx < fxSize ? ctx.m_fxIdx : 0;
     const FontEffect& fx = m_effects[fxIdx];
 
+    AZStd::wstring strW;
+    AZStd::to_wstring(strW, str);
+
     for (size_t i = 0, numPasses = fx.m_passes.size(); i < numPasses; ++i)
     {
         const FontRenderingPass* pass = &fx.m_passes[numPasses - i - 1];
@@ -426,7 +430,7 @@ Vec2 AZ::FFont::GetTextSizeUInternal(
 
         // parse the string, ignoring control characters
         uint32_t nextCh = 0;
-        Unicode::CIterator pChar(str);
+        const wchar_t* pChar = strW.c_str();
         while (uint32_t ch = *pChar)
         {
             ++pChar;
@@ -556,6 +560,9 @@ uint32_t AZ::FFont::GetNumQuadsForText(const char* str, const bool asciiMultiLin
     const size_t fxIdx = ctx.m_fxIdx < fxSize ? ctx.m_fxIdx : 0;
     const FontEffect& fx = m_effects[fxIdx];
 
+    AZStd::wstring strW;
+    AZStd::to_wstring(strW, str);
+
     for (size_t j = 0, numPasses = fx.m_passes.size(); j < numPasses; ++j)
     {
         size_t i = numPasses - j - 1;
@@ -567,7 +574,7 @@ uint32_t AZ::FFont::GetNumQuadsForText(const char* str, const bool asciiMultiLin
         }
 
         uint32_t nextCh = 0;
-        Unicode::CIterator pChar(str);
+        const wchar_t* pChar = strW.c_str();
         while (uint32_t ch = *pChar)
         {
             ++pChar;
@@ -862,9 +869,12 @@ int AZ::FFont::CreateQuadsForText(const RHI::Viewport& viewport, float x, float
             }
         }
 
+        AZStd::wstring strW;
+        AZStd::to_wstring(strW, str);
+
         // parse the string, ignoring control characters
         uint32_t nextCh = 0;
-        Unicode::CIterator pChar(str);
+        const wchar_t* pChar = strW.c_str();
         while (uint32_t ch = *pChar)
         {
             ++pChar;
@@ -1188,7 +1198,7 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
     const bool multiLine = strSize.y > GetRestoredFontSize(ctx).y;
 
     int lastSpace = -1;
-    const char* pLastSpace = NULL;
+    const wchar_t* pLastSpace = NULL;
     float lastSpaceWidth = 0.0f;
 
     float curCharWidth = 0.0f;
@@ -1197,7 +1207,9 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
     float widthSum = 0.0f;
 
     int curChar = 0;
-    Unicode::CIterator pChar(result.c_str());
+    AZStd::wstring resultW;
+    AZStd::to_wstring(resultW, result.c_str());
+    const wchar_t* pChar = resultW.c_str();
     while (uint32_t ch = *pChar)
     {
         // Dollar sign escape codes.  The following scenarios can happen with dollar signs embedded in a string.
@@ -1224,7 +1236,7 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
         // get char width and sum it to the line width
         // Note: This is not unicode compatible, since char-width depends on surrounding context (ie, combining diacritics etc)
         char codepoint[5];
-        Unicode::Convert(codepoint, ch);
+        AZStd::to_string(codepoint, 5, (wchar_t*)&ch, 1);
         curCharWidth = GetTextSize(codepoint, true, ctx).x;
 
         // keep track of spaces
@@ -1233,15 +1245,15 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
         {
             lastSpace = curChar;
             lastSpaceWidth = curLineWidth + curCharWidth;
-            pLastSpace = pChar.GetPosition();
+            pLastSpace = pChar;
             assert(*pLastSpace == ' ');
         }
 
         bool prevCharWasNewline = false;
-        const bool notFirstChar = pChar.GetPosition() != result.c_str();
+        const bool notFirstChar = pChar != resultW.c_str();
         if (*pChar && notFirstChar)
         {
-            const char* pPrevCharStr = pChar.GetPosition() - 1;
+            const wchar_t* pPrevCharStr = pChar - 1;
             prevCharWasNewline = pPrevCharStr[0] == '\n';
         }
 
@@ -1268,12 +1280,12 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
             }
             else
             {
-                const char* buf = pChar.GetPosition();
-                size_t bytesProcessed = buf - result.c_str();
-                result.insert(bytesProcessed, '\n'); // Insert the newline, this invalidates the iterator
-                buf = result.c_str() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
+                const wchar_t* buf = pChar;
+                size_t bytesProcessed = buf - resultW.c_str();
+                resultW.insert(resultW.begin() + bytesProcessed, L'\n'); // Insert the newline, this invalidates the iterator
+                buf = resultW.c_str() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
                 assert(*buf == '\n');
-                pChar.SetPosition(buf); // pChar once again points inside the target string, at the current character
+                pChar = buf; // pChar once again points inside the target string, at the current character
                 assert(*pChar == ch);
                 ++pChar;
                 ++curChar;
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
index 101a506ddc..17ac896cf7 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
@@ -22,6 +22,8 @@
 
 #include 
 
+#include 
+
 // Sizes are defined in in 26.6 fixed float format (TT_F26Dot6), where
 // 1 unit is 1/64 of a pixel.
 constexpr int FractionalPixelUnits = 64;
@@ -94,7 +96,7 @@ AZ::FontRenderer::~FontRenderer()
 }
 
 //-------------------------------------------------------------------------------------------------
-int AZ::FontRenderer::LoadFromFile(const string& fileName)
+int AZ::FontRenderer::LoadFromFile(const AZStd::string& fileName)
 {
     int iError = FT_Init_FreeType(&m_library);
 
@@ -309,8 +311,7 @@ Vec2 AZ::FontRenderer::GetKerning(uint32_t leftGlyph, uint32_t rightGlyph)
 #if !defined(_RELEASE)
         if (0 != ftError)
         {
-            string warnMsg;
-            warnMsg.Format("FT_Get_Kerning returned %d", ftError);
+            AZStd::string warnMsg = AZStd::string::format("FT_Get_Kerning returned %d", ftError);
             CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, warnMsg.c_str());
         }
 #endif
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp
index 6008881ec3..1ee7f80eda 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp
@@ -14,8 +14,8 @@
 #if !defined(USE_NULLFONT_ALWAYS)
 
 #include 
-#include 
 #include 
+#include 
 
 //-------------------------------------------------------------------------------------------------
 AZ::FontTexture::FontTexture()
@@ -44,7 +44,7 @@ AZ::FontTexture::~FontTexture()
 }
 
 //-------------------------------------------------------------------------------------------------
-int AZ::FontTexture::CreateFromFile(const string& fileName, int width, int height, AZ::FontSmoothMethod smoothMethod, AZ::FontSmoothAmount smoothAmount, int widthCellCount, int heightCellCount)
+int AZ::FontTexture::CreateFromFile(const AZStd::string& fileName, int width, int height, AZ::FontSmoothMethod smoothMethod, AZ::FontSmoothAmount smoothAmount, int widthCellCount, int heightCellCount)
 {
     if (!m_glyphCache.LoadFontFromFile(fileName))
     {
@@ -255,10 +255,10 @@ int AZ::FontTexture::PreCacheString(const char* string, int* updated, float size
     uint16_t slotUsage = m_slotUsage++;
     int updateCount = 0;
 
-    uint32_t character;
-    for (Unicode::CIterator it(string); *it; ++it)
+    AZStd::wstring stringW;
+    AZStd::to_wstring(stringW, string);
+    for (wchar_t character : stringW)
     {
-        character = *it;
         TextureSlot* slot = GetCharSlot(character, clampedGlyphSize);
 
         if (!slot)
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphCache.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphCache.cpp
index 12ebd99183..ee52d36af5 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphCache.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphCache.cpp
@@ -124,7 +124,7 @@ int AZ::GlyphCache::Release()
 }
 
 //-------------------------------------------------------------------------------------------------
-int AZ::GlyphCache::LoadFontFromFile(const string& fileName)
+int AZ::GlyphCache::LoadFontFromFile(const AZStd::string & fileName)
 {
     return m_fontRenderer.LoadFromFile(fileName);
 }
diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.cpp
index 7038441e4c..c3b929ae7a 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.cpp
@@ -12,6 +12,7 @@
 #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER
 
 #include 
+#include 
 
 
 // joystick enum callback
@@ -20,7 +21,7 @@ BOOL CALLBACK GameController::EnumJoysticksCallback(const DIDEVICEINSTANCE* pdid
     GameController* manager = static_cast(pContext);
 
     // store the name
-    manager->mDeviceInfo.mName = pdidInstance->tszProductName;
+    AZStd::to_string(manager->mDeviceInfo.mName, pdidInstance->tszProductName);
 
     // Skip anything other than the perferred Joystick device as defined by the control panel.
     // Instead you could store all the enumerated Joysticks and let the user pick.
@@ -71,7 +72,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_XAxis)
     {
-        manager->mDeviceElements[ ELEM_POS_X ].mName                = pdidoi->tszName;
+        AZStd::to_string(manager->mDeviceElements[ ELEM_POS_X ].mName, pdidoi->tszName);
         manager->mDeviceElements[ ELEM_POS_X ].mPresent             = true;
         manager->mDeviceElements[ ELEM_POS_X ].mValue               = 0.0f;
         //manager->mDeviceElements[ ELEM_POS_X ].mCalibrationValue  = 0.0f;
@@ -81,7 +82,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_YAxis)
     {
-        manager->mDeviceElements[ ELEM_POS_Y ].mName                = pdidoi->tszName;
+        AZStd::to_string(manager->mDeviceElements[ ELEM_POS_Y ].mName, pdidoi->tszName);
         manager->mDeviceElements[ ELEM_POS_Y ].mPresent             = true;
         manager->mDeviceElements[ ELEM_POS_Y ].mValue               = 0.0f;
         //manager->mDeviceElements[ ELEM_POS_Y ].mCalibrationValue  = 0.0f;
@@ -91,7 +92,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_ZAxis)
     {
-        manager->mDeviceElements[ ELEM_POS_Z ].mName                = pdidoi->tszName;
+        AZStd::to_string(manager->mDeviceElements[ ELEM_POS_Z ].mName, pdidoi->tszName);
         manager->mDeviceElements[ ELEM_POS_Z ].mPresent             = true;
         manager->mDeviceElements[ ELEM_POS_Z ].mValue               = 0.0f;
         //manager->mDeviceElements[ ELEM_POS_Z ].mCalibrationValue  = 0.0f;
@@ -101,7 +102,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_RxAxis)
     {
-        manager->mDeviceElements[ ELEM_ROT_X ].mName                = pdidoi->tszName;
+        AZStd::to_string(manager->mDeviceElements[ ELEM_ROT_X ].mName, pdidoi->tszName);
         manager->mDeviceElements[ ELEM_ROT_X ].mPresent             = true;
         manager->mDeviceElements[ ELEM_ROT_X ].mValue               = 0.0f;
         //manager->mDeviceElements[ ELEM_ROT_X ].mCalibrationValue  = 0.0f;
@@ -111,7 +112,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_RyAxis)
     {
-        manager->mDeviceElements[ ELEM_ROT_Y ].mName                = pdidoi->tszName;
+        AZStd::to_string(manager->mDeviceElements[ ELEM_ROT_Y ].mName, pdidoi->tszName);
         manager->mDeviceElements[ ELEM_ROT_Y ].mPresent             = true;
         manager->mDeviceElements[ ELEM_ROT_Y ].mValue               = 0.0f;
         //manager->mDeviceElements[ ELEM_ROT_Y ].mCalibrationValue  = 0.0f;
@@ -121,7 +122,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
 
     if (pdidoi->guidType == GUID_RzAxis)
     {
-        manager->mDeviceElements[ ELEM_ROT_Z ].mName                = pdidoi->tszName;
+        AZStd::to_string(manager->mDeviceElements[ ELEM_ROT_Z ].mName, pdidoi->tszName);
         manager->mDeviceElements[ ELEM_ROT_Z ].mPresent             = true;
         manager->mDeviceElements[ ELEM_ROT_Z ].mValue               = 0.0f;
         //manager->mDeviceElements[ ELEM_ROT_Z ].mCalibrationValue  = 0.0f;
@@ -134,7 +135,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
     {
         if (manager->mDeviceInfo.mNumSliders == 0)
         {
-            manager->mDeviceElements[ ELEM_SLIDER_1 ].mName                 = pdidoi->tszName;
+            AZStd::to_string(manager->mDeviceElements[ ELEM_SLIDER_1 ].mName, pdidoi->tszName);
             manager->mDeviceElements[ ELEM_SLIDER_1 ].mPresent              = true;
             manager->mDeviceElements[ ELEM_SLIDER_1 ].mValue                = 0.0f;
             //manager->mDeviceElements[ ELEM_SLIDER_1 ].mCalibrationValue   = 0.0f;
@@ -142,7 +143,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
         }
         else
         {
-            manager->mDeviceElements[ ELEM_SLIDER_2 ].mName                 = pdidoi->tszName;
+            AZStd::to_string(manager->mDeviceElements[ ELEM_SLIDER_2 ].mName, pdidoi->tszName);
             manager->mDeviceElements[ ELEM_SLIDER_2 ].mPresent              = true;
             manager->mDeviceElements[ ELEM_SLIDER_2 ].mValue                = 0.0f;
             //manager->mDeviceElements[ ELEM_SLIDER_2 ].mCalibrationValue   = 0.0f;
@@ -156,7 +157,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE*
     if (pdidoi->guidType == GUID_POV)
     {
         const uint32 povIndex = manager->mDeviceInfo.mNumPOVs;
-        manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mName                 = pdidoi->tszName;
+        AZStd::to_string(manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mName, pdidoi->tszName);
         manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mPresent              = true;
         manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mValue                = 0.0f;
         //manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mCalibrationValue   = 0.0f;

From db7536acda4583ff46d2e4f84618e086f2577565 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 11:44:34 -0700
Subject: [PATCH 033/205] Gems/Maestro

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/Export/ExportManager.cpp          |  2 +-
 Code/Editor/TrackView/CommentNodeAnimator.cpp |  2 +-
 .../TrackView/TrackViewDopeSheetBase.cpp      |  6 ++---
 Code/Editor/TrackView/TrackViewNodes.cpp      |  2 +-
 Code/Legacy/CryCommon/ISurfaceType.h          | 14 +++++------
 Code/Legacy/CryCommon/Mocks/IRendererMock.h   |  2 +-
 Code/Legacy/CryCommon/Mocks/ISystemMock.h     |  2 +-
 Code/Legacy/CryCommon/WinBase.cpp             | 10 ++++----
 Code/Legacy/CryCommon/platform_impl.cpp       |  2 +-
 Code/Legacy/CrySystem/XConsole.cpp            |  2 +-
 .../Support/include/CrashSupport.h            | 24 ++++++++-----------
 .../Components/BlastSystemComponent.cpp       |  1 +
 .../Animation/UiAnimViewDopeSheetBase.cpp     |  6 ++---
 .../Source/Cinematics/AnimComponentNode.h     |  6 ++---
 .../Code/Source/Cinematics/AnimPostFXNode.cpp |  2 +-
 .../Code/Source/Cinematics/AnimSequence.cpp   | 17 ++-----------
 .../Code/Source/Cinematics/AnimSequence.h     |  2 +-
 .../Source/Cinematics/CompoundSplineTrack.cpp | 10 ++++----
 .../Source/Cinematics/CompoundSplineTrack.h   |  2 +-
 .../Code/Source/Cinematics/EventTrack.cpp     |  4 ++--
 .../Code/Source/Cinematics/MaterialNode.h     |  2 +-
 Gems/Maestro/Code/Source/Cinematics/Movie.cpp | 23 +++++++++---------
 .../Code/Source/Cinematics/SceneNode.cpp      |  4 ++--
 .../Source/Cinematics/ScreenFaderTrack.cpp    |  2 +-
 .../Source/Cinematics/TrackEventTrack.cpp     |  4 ++--
 25 files changed, 68 insertions(+), 85 deletions(-)

diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp
index 03aa0bed8b..5ba250c960 100644
--- a/Code/Editor/Export/ExportManager.cpp
+++ b/Code/Editor/Export/ExportManager.cpp
@@ -46,7 +46,7 @@ namespace
         SEfResTexture* pTex = pRes->GetTextureResource(nSlot);
         if (pTex)
         {
-            cry_strcat(outName, Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data());
+            azstrcat(outName, Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data());
         }
     }
 
diff --git a/Code/Editor/TrackView/CommentNodeAnimator.cpp b/Code/Editor/TrackView/CommentNodeAnimator.cpp
index 47f4c5d9ae..579bba00ef 100644
--- a/Code/Editor/TrackView/CommentNodeAnimator.cpp
+++ b/Code/Editor/TrackView/CommentNodeAnimator.cpp
@@ -92,7 +92,7 @@ void CCommentNodeAnimator::AnimateCommentTextTrack(CTrackViewTrack* pTrack, cons
         if (commentKey.m_duration > 0 && ac.time < keyHandle.GetTime() + commentKey.m_duration)
         {
             m_commentContext.m_strComment = commentKey.m_strComment;
-            cry_strcpy(m_commentContext.m_strFont,  commentKey.m_strFont.c_str());
+            azstrcpy(m_commentContext.m_strFont,  commentKey.m_strFont.c_str());
             m_commentContext.m_color = commentKey.m_color;
             m_commentContext.m_align = commentKey.m_align;
             m_commentContext.m_size = commentKey.m_size;
diff --git a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
index 34ca2f062f..f66bb19bf3 100644
--- a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
+++ b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
@@ -2808,10 +2808,10 @@ void CTrackViewDopeSheetBase::DrawKeys(CTrackViewTrack* pTrack, QPainter* painte
                 }
                 else
                 {
-                    cry_strcpy(keydesc, "{");
+                    azstrcpy(keydesc, "{");
                 }
-                cry_strcat(keydesc, pDescription);
-                cry_strcat(keydesc, "}");
+                azstrcat(keydesc, pDescription);
+                azstrcat(keydesc, "}");
                 // Draw key description text.
                 // Find next key.
                 const QRect textRect(QPoint(x + 10, rect.top()), QPoint(x1, rect.bottom()));
diff --git a/Code/Editor/TrackView/TrackViewNodes.cpp b/Code/Editor/TrackView/TrackViewNodes.cpp
index d69c256049..90e5598876 100644
--- a/Code/Editor/TrackView/TrackViewNodes.cpp
+++ b/Code/Editor/TrackView/TrackViewNodes.cpp
@@ -2516,7 +2516,7 @@ int CTrackViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, cons
     if (const char* pCh = strstr(nodeName, ".["))
     {
         char matPath[MAX_PATH];
-        cry_strcpy(matPath, nodeName, (size_t)(pCh - nodeName));
+        azstrcpy(matPath, nodeName, (size_t)(pCh - nodeName));
         matName = matPath;
         pCh += 2;
         if ((*pCh) != 0)
diff --git a/Code/Legacy/CryCommon/ISurfaceType.h b/Code/Legacy/CryCommon/ISurfaceType.h
index db5ec4eed4..10bddbbe6c 100644
--- a/Code/Legacy/CryCommon/ISurfaceType.h
+++ b/Code/Legacy/CryCommon/ISurfaceType.h
@@ -85,7 +85,7 @@ struct ISurfaceType
     };
     struct SBreakable2DParams
     {
-        string particle_effect;
+        AZStd::string particle_effect;
         float blast_radius;
         float blast_radius_first;
         float vert_size_spread;
@@ -97,12 +97,12 @@ struct ISurfaceType
         float shard_density;
         int use_edge_alpha;
         float crack_decal_scale;
-        string crack_decal_mtl;
+        AZStd::string crack_decal_mtl;
         float max_fracture;
-        string full_fracture_fx;
-        string fracture_fx;
+        AZStd::string full_fracture_fx;
+        AZStd::string fracture_fx;
         int no_procedural_full_fracture;
-        string broken_mtl;
+        AZStd::string broken_mtl;
         float destroy_timeout;
         float destroy_timeout_spread;
 
@@ -125,8 +125,8 @@ struct ISurfaceType
     };
     struct SBreakageParticles
     {
-        string type;
-        string particle_effect;
+        AZStd::string type;
+        AZStd::string particle_effect;
         int count_per_unit;
         float count_scale;
         float scale;
diff --git a/Code/Legacy/CryCommon/Mocks/IRendererMock.h b/Code/Legacy/CryCommon/Mocks/IRendererMock.h
index ff3550a738..be9c1eec8b 100644
--- a/Code/Legacy/CryCommon/Mocks/IRendererMock.h
+++ b/Code/Legacy/CryCommon/Mocks/IRendererMock.h
@@ -283,7 +283,7 @@ public:
     MOCK_METHOD0(EF_GetShaderMissLogPath,
         const char*());
     MOCK_METHOD1(EF_GetShaderNames,
-        string * (int& nNumShaders));
+        AZStd::string * (int& nNumShaders));
     MOCK_METHOD1(EF_ReloadFile,
         bool(const char* szFileName));
     MOCK_METHOD1(EF_ReloadFile_Request,
diff --git a/Code/Legacy/CryCommon/Mocks/ISystemMock.h b/Code/Legacy/CryCommon/Mocks/ISystemMock.h
index d891365696..9e4b7c99ec 100644
--- a/Code/Legacy/CryCommon/Mocks/ISystemMock.h
+++ b/Code/Legacy/CryCommon/Mocks/ISystemMock.h
@@ -122,7 +122,7 @@ public:
         const SFileVersion&());
 
     MOCK_METHOD1(AddCVarGroupDirectory,
-        void(const string&));
+        void(const AZStd::string&));
     MOCK_METHOD0(SaveConfiguration,
         void());
     MOCK_METHOD3(LoadConfiguration,
diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp
index a60dbdf00b..fe9c539569 100644
--- a/Code/Legacy/CryCommon/WinBase.cpp
+++ b/Code/Legacy/CryCommon/WinBase.cpp
@@ -349,23 +349,23 @@ void _makepath(char* path, const char* drive, const char* dir, const char* filen
     }
     if (dir && dir[0])
     {
-        cry_strcat(tmp, dir);
+        azstrcat(tmp, dir);
         ch = tmp[strlen(tmp) - 1];
         if (ch != '/' && ch != '\\')
         {
-            cry_strcat(tmp, "\\");
+            azstrcat(tmp, "\\");
         }
     }
     if (filename && filename[0])
     {
-        cry_strcat(tmp, filename);
+        azstrcat(tmp, filename);
         if (ext && ext[0])
         {
             if (ext[0] != '.')
             {
-                cry_strcat(tmp, ".");
+                azstrcat(tmp, ".");
             }
-            cry_strcat(tmp, ext);
+            azstrcat(tmp, ext);
         }
     }
     azstrcpy(path, strlen(tmp) + 1, tmp);
diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp
index 6badd2fe1e..1523622538 100644
--- a/Code/Legacy/CryCommon/platform_impl.cpp
+++ b/Code/Legacy/CryCommon/platform_impl.cpp
@@ -499,7 +499,7 @@ inline void CryDebugStr([[maybe_unused]] const char* format, ...)
      va_start(ArgList, format);
      azvsnprintf(szBuffer,sizeof(szBuffer)-1, format, ArgList);
      va_end(ArgList);
-     cry_strcat(szBuffer,"\n");
+     azstrcat(szBuffer,"\n");
      OutputDebugString(szBuffer);
      #endif
      */
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index f5e946be43..2348e78a0e 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -1545,7 +1545,7 @@ const char* CXConsole::GetFlagsString(const uint32 dwFlags)
     static char sFlags[256];
 
     // hiding this makes it a bit more difficult for cheaters
-    //  if(dwFlags&VF_CHEAT)                  cry_strcat( sFlags,"CHEAT, ");
+    //  if(dwFlags&VF_CHEAT)                  azstrcat( sFlags,"CHEAT, ");
 
     azstrcpy(sFlags, "");
 
diff --git a/Code/Tools/CrashHandler/Support/include/CrashSupport.h b/Code/Tools/CrashHandler/Support/include/CrashSupport.h
index 9932d950d4..1393930913 100644
--- a/Code/Tools/CrashHandler/Support/include/CrashSupport.h
+++ b/Code/Tools/CrashHandler/Support/include/CrashSupport.h
@@ -11,6 +11,8 @@
 #pragma once
 
 #include 
+#include 
+#include 
 
 #include 
 #include 
@@ -23,30 +25,24 @@
 namespace CrashHandler
 {
     std::string GetTimeString();
-    void GetExecutablePathA(char* pathBuffer, int& bufferSize);
-    void GetExecutablePathW(wchar_t* pathBuffer, int& bufferSize);
     void GetTimeInfo(tm& curTime);
 
-    template 
-    inline void GetExecutablePath(T& returnPath)
+    inline void GetExecutablePath(std::string& returnPath)
     {
         char currentFileName[CRASH_HANDLER_MAX_PATH_LEN] = { 0 };
-        int bufferLen{ CRASH_HANDLER_MAX_PATH_LEN };
-        GetExecutablePathA(currentFileName, bufferLen);
+        AZ::Utils::GetExecutablePath(currentFileName, CRASH_HANDLER_MAX_PATH_LEN);
 
         returnPath = currentFileName;
         std::replace(returnPath.begin(), returnPath.end(), '\\', '/');
     }
 
-    template <>
-    inline void GetExecutablePath(std::wstring& returnPath)
+    inline void GetExecutablePath(std::wstring& returnPathW)
     {
-        wchar_t currentFileName[CRASH_HANDLER_MAX_PATH_LEN] = { 0 };
-        int bufferLen{ CRASH_HANDLER_MAX_PATH_LEN };
-        GetExecutablePathW(currentFileName, bufferLen);
-
-        returnPath = currentFileName;
-        std::replace(returnPath.begin(), returnPath.end(), '\\', '/');
+        std::string returnPath;
+        GetExecutablePath(returnPath);
+        wchar_t currentFileNameW[CRASH_HANDLER_MAX_PATH_LEN] = { 0 };
+        AZStd::to_wstring(currentFileNameW, CRASH_HANDLER_MAX_PATH_LEN, returnPath.c_str(), returnPath.size());
+        returnPathW = currentFileNameW;
     }
 
     template
diff --git a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp
index 933633b5e3..bee94ed116 100644
--- a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp
+++ b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp
@@ -32,6 +32,7 @@
 #include 
 #include 
 #endif
+#include 
 
 namespace Blast
 {
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
index f9ce0e522f..ae0880e98e 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
@@ -2362,10 +2362,10 @@ void CUiAnimViewDopeSheetBase::DrawKeys(CUiAnimViewTrack* pTrack, QPainter* pain
                 }
                 else
                 {
-                    cry_strcpy(keydesc, "{");
+                    azstrcpy(keydesc, "{");
                 }
-                cry_strcat(keydesc, pDescription);
-                cry_strcat(keydesc, "}");
+                azstrcat(keydesc, pDescription);
+                azstrcat(keydesc, "}");
                 // Draw key description text.
                 // Find next key.
                 const QRect textRect(QPoint(x + 10, rect.top()), QPoint(x1, rect.bottom()));
diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.h b/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.h
index 4df6021aa9..5ad3ab6f94 100644
--- a/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.h
+++ b/Gems/Maestro/Code/Source/Cinematics/AnimComponentNode.h
@@ -144,7 +144,7 @@ private:
     {
     public:
         BehaviorPropertyInfo() {}
-        BehaviorPropertyInfo(const string& name)
+        BehaviorPropertyInfo(const AZStd::string& name)
         {
             *this = name;
         }
@@ -154,7 +154,7 @@ private:
             m_animNodeParamInfo.paramType = other.m_displayName;
             m_animNodeParamInfo.name = &m_displayName[0];
         }
-        BehaviorPropertyInfo& operator=(const string& str)
+        BehaviorPropertyInfo& operator=(const AZStd::string& str)
         {
             // TODO: clean this up - this weird memory sharing was copied from legacy Cry - could be better.
             m_displayName = str;
@@ -163,7 +163,7 @@ private:
             return *this;
         }
 
-        string     m_displayName;
+        AZStd::string m_displayName;
         SParamInfo m_animNodeParamInfo;
     };
     
diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp
index 78d878c0eb..fd7f99c9b3 100644
--- a/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp
@@ -39,7 +39,7 @@ public:
         virtual void GetDefault(bool& val) const = 0;
         virtual void GetDefault(Vec4& val) const = 0;
 
-        string m_name;
+        AZStd::string m_name;
 
     protected:
         virtual ~CControlParamBase(){}
diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimSequence.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimSequence.cpp
index e9f77f7947..23017e5779 100644
--- a/Gems/Maestro/Code/Source/Cinematics/AnimSequence.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/AnimSequence.cpp
@@ -98,10 +98,10 @@ void CAnimSequence::SetName(const char* name)
         return;   // should never happen, null pointer guard
     }
 
-    string originalName = GetName();
+    AZStd::string originalName = GetName();
 
     m_name = name;
-    m_pMovieSystem->OnSequenceRenamed(originalName, m_name.c_str());
+    m_pMovieSystem->OnSequenceRenamed(originalName.c_str(), m_name.c_str());
 
     // the sequence named LIGHT_ANIMATION_SET_NAME is a singleton sequence to hold all light animations.
     if (m_name == LIGHT_ANIMATION_SET_NAME)
@@ -744,9 +744,6 @@ void CAnimSequence::Deactivate()
         static_cast(animNode)->OnReset();
     }
 
-    // Remove a possibly cached game hint associated with this anim sequence.
-    stack_string sTemp("anim_sequence_");
-    sTemp += m_name.c_str();
     // Audio: Release precached sound
 
     m_bActive = false;
@@ -776,16 +773,6 @@ void CAnimSequence::PrecacheStatic(const float startTime)
         return;
     }
 
-    // Try to cache this sequence's game hint if one exists.
-    stack_string sTemp("anim_sequence_");
-    sTemp += m_name.c_str();
-
-    //if (gEnv->pAudioSystem)
-    {
-        // Make sure to use the non-serializable game hint type as trackview sequences get properly reactivated after load
-        // Audio: Precache sound
-    }
-
     gEnv->pLog->Log("=== Precaching render data for cutscene: %s ===", GetName());
 
     m_precached = true;
diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimSequence.h b/Gems/Maestro/Code/Source/Cinematics/AnimSequence.h
index 2c12f6e5ea..f69017c3a6 100644
--- a/Gems/Maestro/Code/Source/Cinematics/AnimSequence.h
+++ b/Gems/Maestro/Code/Source/Cinematics/AnimSequence.h
@@ -174,7 +174,7 @@ private:
 
     uint32 m_id;
     AZStd::string m_name;
-    mutable string m_fullNameHolder;
+    mutable AZStd::string m_fullNameHolder;
     Range m_timeRange;
     TrackEvents m_events;
 
diff --git a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
index 4dd52a734a..62de2dfdf5 100644
--- a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
@@ -457,31 +457,31 @@ void CCompoundSplineTrack::GetKeyInfo(int key, const char*& description, float&
         {
             float dummy;
             m_subTracks[0]->GetKeyInfo(m, subDesc, dummy);
-            cry_strcat(str, subDesc);
+            azstrcat(str, subDesc);
             break;
         }
     }
     if (m == m_subTracks[0]->GetNumKeys())
     {
-        cry_strcat(str, m_subTrackNames[0].c_str());
+        azstrcat(str, m_subTrackNames[0].c_str());
     }
     // Tail cases
     for (int i = 1; i < GetSubTrackCount(); ++i)
     {
-        cry_strcat(str, ",");
+        azstrcat(str, ",");
         for (m = 0; m < m_subTracks[i]->GetNumKeys(); ++m)
         {
             if (m_subTracks[i]->GetKeyTime(m) == time)
             {
                 float dummy;
                 m_subTracks[i]->GetKeyInfo(m, subDesc, dummy);
-                cry_strcat(str, subDesc);
+                azstrcat(str, subDesc);
                 break;
             }
         }
         if (m == m_subTracks[i]->GetNumKeys())
         {
-            cry_strcat(str, m_subTrackNames[i].c_str());
+            azstrcat(str, m_subTrackNames[i].c_str());
         }
     }
 }
diff --git a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.h b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.h
index f22b0fb144..b0a2733316 100644
--- a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.h
+++ b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.h
@@ -108,7 +108,7 @@ public:
 
     virtual int NextKeyByTime(int key) const;
 
-    void SetSubTrackName(const int i, const string& name) { assert (i < MAX_SUBTRACKS); m_subTrackNames[i] = name; }
+    void SetSubTrackName(const int i, const AZStd::string& name) { assert (i < MAX_SUBTRACKS); m_subTrackNames[i] = name; }
 
 #ifdef MOVIESYSTEM_SUPPORT_EDITING
     virtual ColorB GetCustomColor() const
diff --git a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
index 278833cfe2..36d468e36d 100644
--- a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
@@ -72,8 +72,8 @@ void CEventTrack::GetKeyInfo(int key, const char*& description, float& duration)
     azstrcpy(desc, m_keys[key].event.c_str());
     if (!m_keys[key].eventValue.empty())
     {
-        cry_strcat(desc, ", ");
-        cry_strcat(desc, m_keys[key].eventValue.c_str());
+        azstrcat(desc, ", ");
+        azstrcat(desc, m_keys[key].eventValue.c_str());
     }
 
     description = desc;
diff --git a/Gems/Maestro/Code/Source/Cinematics/MaterialNode.h b/Gems/Maestro/Code/Source/Cinematics/MaterialNode.h
index 51d1b8be15..003312c426 100644
--- a/Gems/Maestro/Code/Source/Cinematics/MaterialNode.h
+++ b/Gems/Maestro/Code/Source/Cinematics/MaterialNode.h
@@ -58,7 +58,7 @@ private:
     float m_fMaxKeyValue;
 
     std::vector< CAnimNode::SParamInfo > m_dynamicShaderParamInfos;
-    typedef AZStd::unordered_map< string, size_t, stl::hash_string_caseless, stl::equality_string_caseless > TDynamicShaderParamsMap;
+    typedef AZStd::unordered_map, stl::equality_string_caseless > TDynamicShaderParamsMap;
     TDynamicShaderParamsMap m_nameToDynamicShaderParam;
 };
 
diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
index a6d9e47eb1..b7fb82e0e7 100644
--- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
@@ -75,19 +75,19 @@ static SMovieSequenceAutoComplete s_movieSequenceAutoComplete;
 // Serialization for anim nodes & param types
 #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(AnimNodeType::name) == g_animNodeEnumToStringMap.end()); \
     g_animNodeEnumToStringMap[AnimNodeType::name] = STRINGIFY(name);                                                            \
-    g_animNodeStringToEnumMap[string(STRINGIFY(name))] = AnimNodeType::name;
+    g_animNodeStringToEnumMap[AZStd::string(STRINGIFY(name))] = AnimNodeType::name;
 
 #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(AnimParamType::name) == g_animParamEnumToStringMap.end()); \
     g_animParamEnumToStringMap[AnimParamType::name] = STRINGIFY(name);                                                              \
-    g_animParamStringToEnumMap[string(STRINGIFY(name))] = AnimParamType::name;
+    g_animParamStringToEnumMap[AZStd::string(STRINGIFY(name))] = AnimParamType::name;
 
 namespace
 {
-    AZStd::unordered_map g_animNodeEnumToStringMap;
-    StaticInstance >> g_animNodeStringToEnumMap;
+    AZStd::unordered_map g_animNodeEnumToStringMap;
+    StaticInstance >> g_animNodeStringToEnumMap;
 
-    AZStd::unordered_map g_animParamEnumToStringMap;
-    StaticInstance >> g_animParamStringToEnumMap;
+    AZStd::unordered_map g_animParamEnumToStringMap;
+    StaticInstance >> g_animParamStringToEnumMap;
 
     // If you get an assert in this function, it means two node types have the same enum value.
     void RegisterNodeTypes()
@@ -1479,8 +1479,7 @@ void CMovieSystem::GoToFrame(const char* seqName, float targetFrame)
 
     if (gEnv->IsEditor() && gEnv->IsEditorGameMode() == false)
     {
-        string editorCmd;
-        editorCmd.Format("mov_goToFrameEditor %s %f", seqName, targetFrame);
+        AZStd::string editorCmd = AZStd::string::format("mov_goToFrameEditor %s %f", seqName, targetFrame);
         gEnv->pConsole->ExecuteString(editorCmd.c_str());
         return;
     }
@@ -1679,7 +1678,7 @@ void CMovieSystem::SerializeNodeType(AnimNodeType& animNodeType, XmlNodeRef& xml
     {
         const char* pTypeString = "Invalid";
         assert(g_animNodeEnumToStringMap.find(animNodeType) != g_animNodeEnumToStringMap.end());
-        pTypeString = g_animNodeEnumToStringMap[animNodeType];
+        pTypeString = g_animNodeEnumToStringMap[animNodeType].c_str();
         xmlNode->setAttr(kType, pTypeString);
     }
 }
@@ -1780,7 +1779,7 @@ void CMovieSystem::SaveParamTypeToXml(const CAnimParamType& animParamType, XmlNo
         }
 
         assert(g_animParamEnumToStringMap.find(animParamType.m_type) != g_animParamEnumToStringMap.end());
-        pTypeString = g_animParamEnumToStringMap[animParamType.m_type];
+        pTypeString = g_animParamEnumToStringMap[animParamType.m_type].c_str();
     }
 
     xmlNode->setAttr(kParamType, pTypeString);
@@ -1815,7 +1814,7 @@ const char* CMovieSystem::GetParamTypeName(const CAnimParamType& animParamType)
     {
         if (g_animParamEnumToStringMap.find(animParamType.m_type) != g_animParamEnumToStringMap.end())
         {
-            return g_animParamEnumToStringMap[animParamType.m_type];
+            return g_animParamEnumToStringMap[animParamType.m_type].c_str();
         }
     }
 
@@ -1970,7 +1969,7 @@ CLightAnimWrapper* CLightAnimWrapper::FindLightAnim(const char* name)
 //////////////////////////////////////////////////////////////////////////
 void CLightAnimWrapper::CacheLightAnim(const char* name, CLightAnimWrapper* p)
 {
-    ms_lightAnimWrapperCache.insert(LightAnimWrapperCache::value_type(string(name), p));
+    ms_lightAnimWrapperCache.insert(LightAnimWrapperCache::value_type(AZStd::string(name), p));
 }
 
 //////////////////////////////////////////////////////////////////////////
diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
index 9e3fe212df..799747eb12 100644
--- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
@@ -917,7 +917,7 @@ void CAnimSceneNode::ApplyEventKey(IEventKey& key, [[maybe_unused]] SAnimContext
 {
     char funcName[1024];
     azstrcpy(funcName, "Event_");
-    cry_strcat(funcName, key.event.c_str());
+    azstrcat(funcName, key.event.c_str());
     gEnv->pMovieSystem->SendGlobalEvent(funcName);
 }
 
@@ -1003,7 +1003,7 @@ void CAnimSceneNode::ApplyGotoKey(CGotoTrack*   poGotoTrack, SAnimContext& ec)
         {
             if (stDiscreteFloadKey.m_fValue >= 0)
             {
-                string fullname = m_pSequence->GetName();
+                AZStd::string fullname = m_pSequence->GetName();
                 GetMovieSystem()->GoToFrame(fullname.c_str(), stDiscreteFloadKey.m_fValue);
             }
         }
diff --git a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
index af5b931dec..3541fe718e 100644
--- a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
@@ -32,7 +32,7 @@ void CScreenFaderTrack::GetKeyInfo(int key, const char*& description, float& dur
     CheckValid();
     description = 0;
     duration = m_keys[key].m_fadeTime;
-    cry_strcpy(desc, m_keys[key].m_fadeType == IScreenFaderKey::eFT_FadeIn ? "In" : "Out");
+    azstrcpy(desc, m_keys[key].m_fadeType == IScreenFaderKey::eFT_FadeIn ? "In" : "Out");
 
     description = desc;
 }
diff --git a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
index 3eca733a1d..25d709bcdc 100644
--- a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
@@ -146,8 +146,8 @@ void CTrackEventTrack::GetKeyInfo(int key, const char*& description, float& dura
     azstrcpy(desc, m_keys[key].event.c_str());
     if (!m_keys[key].eventValue.empty())
     {
-        cry_strcat(desc, ", ");
-        cry_strcat(desc, m_keys[key].eventValue.c_str());
+        azstrcat(desc, ", ");
+        azstrcat(desc, m_keys[key].eventValue.c_str());
     }
 
     description = desc;

From 29a2ad79a44d850e0046609c1c4ffd2a5012c0cc Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 14:04:18 -0700
Subject: [PATCH 034/205] Gems/Gestures

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h               | 2 +-
 Code/Legacy/CrySystem/XConsole.cpp                            | 4 ++--
 .../Code/Include/Gestures/GestureRecognizerClickOrTap.inl     | 1 +
 Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl | 1 +
 Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h   | 1 +
 Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl | 1 +
 .../Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl | 1 +
 .../Code/Include/Gestures/GestureRecognizerRotate.inl         | 1 +
 .../Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl | 1 +
 9 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h b/Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h
index 44962ddb61..4702435b83 100644
--- a/Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h
+++ b/Code/Legacy/CryCommon/LyShine/Bus/UiCanvasBus.h
@@ -101,7 +101,7 @@ public: // member functions
 
     //! Save this canvas to the given path in XML
     //! \return true if no error
-    virtual bool SaveToXml(const string& assetIdPathname, const string& sourceAssetPathname) = 0;
+    virtual bool SaveToXml(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname) = 0;
 
     //! Initialize a set of entities that have been added to the canvas
     //! Used when instantiating a slice or for undo/redo, copy/paste
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index 2348e78a0e..0f67e4ffd9 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -2911,9 +2911,9 @@ void CXConsole::Paste()
             if (cp != '\r')
             {
                 // Convert UCS code-point into UTF-8 string
-                char utf8_buf[5] = {0};
+                AZStd::fixed_string<5> utf8_buf = {0};
                 size_t size = 5;
-                it.to_utf8_sequence(cp, utf8_buf, size);
+                it.to_utf8_sequence(cp, utf8_buf.data(), size);
                 AddInputUTF8(utf8_buf);
             }
         }
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl
index 84837972e8..57716c7d9f 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerClickOrTap::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl
index 368f236338..2c1af6fbc9 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerDrag::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h
index b8d538b426..87c53d815a 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h
@@ -9,6 +9,7 @@
 
 #include "IGestureRecognizer.h"
 
+#include 
 #include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl
index 48f23cce1f..b399639f6d 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerHold::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl
index e577be0e48..f6c0427b2c 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerPinch::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl
index eb3b20287e..9dff9a115a 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerRotate::Config::Reflect(AZ::ReflectContext* context)
diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
index 9fdab7b1a2..8d59525e93 100644
--- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
+++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl
@@ -8,6 +8,7 @@
 
 #include 
 #include 
+#include 
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 inline void Gestures::RecognizerSwipe::Config::Reflect(AZ::ReflectContext* context)

From d5c491a694b3990ab6a5ab15a72f237cb4bc10a0 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 16:04:46 -0700
Subject: [PATCH 035/205] Gems\MetaStream

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Gems/Metastream/Code/Source/MetastreamGem.cpp | 2 +-
 Gems/Metastream/Code/Tests/MetastreamTest.cpp | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Gems/Metastream/Code/Source/MetastreamGem.cpp b/Gems/Metastream/Code/Source/MetastreamGem.cpp
index d1792c439f..2bb213662c 100644
--- a/Gems/Metastream/Code/Source/MetastreamGem.cpp
+++ b/Gems/Metastream/Code/Source/MetastreamGem.cpp
@@ -323,7 +323,7 @@ namespace Metastream
         {
             // Initialise and start the HTTP server
             m_server = std::unique_ptr(new CivetHttpServer(m_cache.get()));
-            string serverOptions = m_serverOptionsCVar->GetString();
+            AZStd::string serverOptions = m_serverOptionsCVar->GetString();
             CryLogAlways("Initializing Metastream: Options=\"%s\"", serverOptions.c_str());
 
             bool result = m_server->Start(serverOptions.c_str());
diff --git a/Gems/Metastream/Code/Tests/MetastreamTest.cpp b/Gems/Metastream/Code/Tests/MetastreamTest.cpp
index 4f1d37391a..1b25fb5327 100644
--- a/Gems/Metastream/Code/Tests/MetastreamTest.cpp
+++ b/Gems/Metastream/Code/Tests/MetastreamTest.cpp
@@ -60,7 +60,7 @@ public:
 
     }
 
-    const string m_serverOptionsString = "document_root=Gems/Metastream/Files;listening_ports=8082";
+    const char* m_serverOptionsString = "document_root=Gems/Metastream/Files;listening_ports=8082";
 
 protected:
     void SetUp() override

From 061cb98f74971b54744e8f241eeab3b3a26393b2 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 16:07:23 -0700
Subject: [PATCH 036/205] auto-search/replace

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/BaseLibraryManager.cpp            |   2 +-
 Code/Editor/Commands/CommandManager.cpp       |   2 +-
 Code/Editor/Commands/CommandManager.h         |  22 ++--
 Code/Editor/ConfigGroup.h                     |   6 +-
 Code/Editor/Controls/SplineCtrlEx.h           |   2 +-
 Code/Editor/Include/Command.h                 | 110 +++++++++---------
 .../EditorAssetImporter/AssetImporterPlugin.h |   2 +-
 Code/Editor/Util/EditorUtils.h                |   1 +
 Code/Editor/Util/FileUtil.cpp                 |   2 +-
 Code/Editor/Util/IXmlHistoryManager.h         |   2 +-
 Code/Editor/Util/StringHelpers.cpp            |  42 +++----
 Code/Editor/Util/StringHelpers.h              |  42 +++----
 Code/Editor/Util/XmlHistoryManager.cpp        |   2 +-
 Code/Editor/Util/XmlHistoryManager.h          |   2 +-
 .../GridMate/GridMate/Carrier/Carrier.cpp     |   8 +-
 .../GridMate/GridMate/Carrier/Carrier.h       |   2 +-
 .../GridMate/Carrier/DefaultHandshake.cpp     |   2 +-
 .../GridMate/Carrier/DefaultHandshake.h       |   2 +-
 .../GridMate/GridMate/Carrier/Driver.h        |   4 +-
 .../GridMate/GridMate/Carrier/Handshake.h     |   2 +-
 .../GridMate/Carrier/SocketDriver.cpp         |  14 +--
 .../GridMate/GridMate/Carrier/SocketDriver.h  |  14 +--
 .../GridMate/Drillers/SessionDriller.cpp      |   2 +-
 .../GridMate/Drillers/SessionDriller.h        |   2 +-
 .../GridMate/GridMate/Session/LANSession.cpp  |  12 +-
 .../GridMate/Session/LANSessionServiceTypes.h |   6 +-
 .../GridMate/GridMate/Session/Session.cpp     |   8 +-
 .../GridMate/GridMate/Session/Session.h       |  12 +-
 Code/Framework/GridMate/Tests/Session.cpp     |  12 +-
 .../Framework/GridMate/Tests/TestProfiler.cpp |   2 +-
 .../Legacy/CryCommon/LocalizationManagerBus.h |   2 +-
 .../LyShine/Animation/IUiAnimation.h          |  11 +-
 Code/Legacy/CryCommon/LyShine/ISprite.h       |   7 +-
 33 files changed, 179 insertions(+), 184 deletions(-)

diff --git a/Code/Editor/BaseLibraryManager.cpp b/Code/Editor/BaseLibraryManager.cpp
index 8e555cae8c..2189156454 100644
--- a/Code/Editor/BaseLibraryManager.cpp
+++ b/Code/Editor/BaseLibraryManager.cpp
@@ -560,7 +560,7 @@ QString CBaseLibraryManager::MakeUniqueItemName(const QString& srcName, const QS
         return srcName;
     }
 
-    std::sort(possibleDuplicates.begin(), possibleDuplicates.end(), [](const string& strOne, const string& strTwo)
+    std::sort(possibleDuplicates.begin(), possibleDuplicates.end(), [](const AZStd::string& strOne, const AZStd::string& strTwo)
         {
             // I can assume size sorting since if the length is different, either one of the two strings doesn't
             // closely match the string we are trying to duplicate, or it's a bigger number (X1 vs X10)
diff --git a/Code/Editor/Commands/CommandManager.cpp b/Code/Editor/Commands/CommandManager.cpp
index 90059ea195..708fccd16b 100644
--- a/Code/Editor/Commands/CommandManager.cpp
+++ b/Code/Editor/Commands/CommandManager.cpp
@@ -79,7 +79,7 @@ CEditorCommandManager::~CEditorCommandManager()
     m_uiCommands.clear();
 }
 
-string CEditorCommandManager::GetFullCommandName(const string& module, const string& name)
+string CEditorCommandManager::GetFullCommandName(const AZStd::string& module, const string& name)
 {
     string fullName = module;
     fullName += ".";
diff --git a/Code/Editor/Commands/CommandManager.h b/Code/Editor/Commands/CommandManager.h
index 2ec4a137bc..a76df830d0 100644
--- a/Code/Editor/Commands/CommandManager.h
+++ b/Code/Editor/Commands/CommandManager.h
@@ -48,20 +48,20 @@ public:
         const AZStd::function& functor,
         const CCommand0::SUIInfo& uiInfo);
     bool AttachUIInfo(const char* fullCmdName, const CCommand0::SUIInfo& uiInfo);
-    bool GetUIInfo(const string& module, const string& name, CCommand0::SUIInfo& uiInfo) const;
-    bool GetUIInfo(const string& fullCmdName, CCommand0::SUIInfo& uiInfo) const;
-    QString Execute(const string& cmdLine);
-    QString Execute(const string& module, const string& name, const CCommand::CArgs& args);
+    bool GetUIInfo(const AZStd::string& module, const AZStd::string& name, CCommand0::SUIInfo& uiInfo) const;
+    bool GetUIInfo(const AZStd::string& fullCmdName, CCommand0::SUIInfo& uiInfo) const;
+    QString Execute(const AZStd::string& cmdLine);
+    QString Execute(const AZStd::string& module, const AZStd::string& name, const CCommand::CArgs& args);
     void Execute(int commandId);
     void GetCommandList(std::vector& cmds) const;
     //! Used in the console dialog
-    string AutoComplete(const string& substr) const;
+    string AutoComplete(const AZStd::string& substr) const;
     bool IsRegistered(const char* module, const char* name) const;
     bool IsRegistered(const char* cmdLine) const;
     bool IsRegistered(int commandId) const;
-    void SetCommandAvailableInScripting(const string& module, const string& name);
-    bool IsCommandAvailableInScripting(const string& module, const string& name) const;
-    bool IsCommandAvailableInScripting(const string& fullCmdName) const;
+    void SetCommandAvailableInScripting(const AZStd::string& module, const AZStd::string& name);
+    bool IsCommandAvailableInScripting(const AZStd::string& module, const AZStd::string& name) const;
+    bool IsCommandAvailableInScripting(const AZStd::string& fullCmdName) const;
     //! Turning off the warning is needed for reloading the ribbon bar.
     void TurnDuplicateWarningOn() { m_bWarnDuplicate = true; }
     void TurnDuplicateWarningOff() { m_bWarnDuplicate = false; }
@@ -86,9 +86,9 @@ protected:
     bool m_bWarnDuplicate;
 
     static int GenNewCommandId();
-    static string GetFullCommandName(const string& module, const string& name);
-    static void GetArgsFromString(const string& argsTxt, CCommand::CArgs& argList);
-    void LogCommand(const string& fullCmdName, const CCommand::CArgs& args) const;
+    static string GetFullCommandName(const AZStd::string& module, const AZStd::string& name);
+    static void GetArgsFromString(const AZStd::string& argsTxt, CCommand::CArgs& argList);
+    void LogCommand(const AZStd::string& fullCmdName, const CCommand::CArgs& args) const;
     QString ExecuteAndLogReturn(CCommand* pCommand, const CCommand::CArgs& args);
 };
 
diff --git a/Code/Editor/ConfigGroup.h b/Code/Editor/ConfigGroup.h
index 35c0b8e47f..5d9b22b2b9 100644
--- a/Code/Editor/ConfigGroup.h
+++ b/Code/Editor/ConfigGroup.h
@@ -47,12 +47,12 @@ namespace Config
             return m_type;
         }
 
-        ILINE const string& GetName() const
+        ILINE const AZStd::string& GetName() const
         {
             return m_name;
         }
 
-        ILINE const string& GetDescription() const
+        ILINE const AZStd::string& GetDescription() const
         {
             return m_description;
         }
@@ -71,7 +71,7 @@ namespace Config
         static EType TranslateType(const bool&) { return eType_BOOL; }
         static EType TranslateType(const int&) { return eType_INT; }
         static EType TranslateType(const float&) { return eType_FLOAT; }
-        static EType TranslateType(const string&) { return eType_STRING; }
+        static EType TranslateType(const AZStd::string&) { return eType_STRING; }
 
     protected:
         EType m_type;
diff --git a/Code/Editor/Controls/SplineCtrlEx.h b/Code/Editor/Controls/SplineCtrlEx.h
index 8592febf88..de07c4214b 100644
--- a/Code/Editor/Controls/SplineCtrlEx.h
+++ b/Code/Editor/Controls/SplineCtrlEx.h
@@ -53,7 +53,7 @@ class QRubberBand;
 class ISplineSet
 {
 public:
-    virtual ISplineInterpolator* GetSplineFromID(const string& id) = 0;
+    virtual ISplineInterpolator* GetSplineFromID(const AZStd::string& id) = 0;
     virtual string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
     virtual int GetSplineCount() const = 0;
     virtual int GetKeyCountAtTime(float time, float threshold) const = 0;
diff --git a/Code/Editor/Include/Command.h b/Code/Editor/Include/Command.h
index 69853ddb4f..92a7736446 100644
--- a/Code/Editor/Include/Command.h
+++ b/Code/Editor/Include/Command.h
@@ -27,10 +27,10 @@ class CCommand
 {
 public:
     CCommand(
-        const string& module,
-        const string& name,
-        const string& description,
-        const string& example)
+        const AZStd::string& module,
+        const AZStd::string& name,
+        const AZStd::string& description,
+        const AZStd::string& example)
         : m_module(module)
         , m_name(name)
         , m_description(description)
@@ -79,7 +79,7 @@ public:
         }
         int GetArgCount() const
         { return m_args.size(); }
-        const string& GetArg(int i) const
+        const AZStd::string& GetArg(int i) const
         {
             assert(0 <= i && i < GetArgCount());
             return m_args[i];
@@ -89,10 +89,10 @@ public:
         unsigned char m_stringFlags;    // This is needed to quote string parameters when logging a command.
     };
 
-    const string& GetName() const { return m_name; }
-    const string& GetModule() const { return m_module; }
-    const string& GetDescription() const { return m_description; }
-    const string& GetExample() const { return m_example; }
+    const AZStd::string& GetName() const { return m_name; }
+    const AZStd::string& GetModule() const { return m_module; }
+    const AZStd::string& GetDescription() const { return m_description; }
+    const AZStd::string& GetExample() const { return m_example; }
 
     void SetAvailableInScripting() { m_bAlsoAvailableInScripting = true; };
     bool IsAvailableInScripting() const { return m_bAlsoAvailableInScripting; }
@@ -137,8 +137,8 @@ class CCommand0
     : public CCommand
 {
 public:
-    CCommand0(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand0(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor)
         : CCommand(module, name, description, example)
         , m_functor(functor) {}
@@ -179,8 +179,8 @@ class CCommand0wRet
     : public CCommand
 {
 public:
-    CCommand0wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand0wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -195,8 +195,8 @@ class CCommand1
     : public CCommand
 {
 public:
-    CCommand1(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand1(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -211,8 +211,8 @@ class CCommand1wRet
     : public CCommand
 {
 public:
-    CCommand1wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand1wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -227,8 +227,8 @@ class CCommand2
     : public CCommand
 {
 public:
-    CCommand2(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand2(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -243,8 +243,8 @@ class CCommand2wRet
     : public CCommand
 {
 public:
-    CCommand2wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand2wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -259,8 +259,8 @@ class CCommand3
     : public CCommand
 {
 public:
-    CCommand3(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand3(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -275,8 +275,8 @@ class CCommand3wRet
     : public CCommand
 {
 public:
-    CCommand3wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand3wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -291,8 +291,8 @@ class CCommand4
     : public CCommand
 {
 public:
-    CCommand4(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand4(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -307,8 +307,8 @@ class CCommand4wRet
     : public CCommand
 {
 public:
-    CCommand4wRet(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand4wRet(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -323,8 +323,8 @@ class CCommand5
     : public CCommand
 {
 public:
-    CCommand5(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand5(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -339,8 +339,8 @@ class CCommand6
     : public CCommand
 {
 public:
-    CCommand6(const string& module, const string& name,
-        const string& description, const string& example,
+    CCommand6(const AZStd::string& module, const AZStd::string& name,
+        const AZStd::string& description, const AZStd::string& example,
         const AZStd::function& functor);
 
     QString Execute(const CArgs& args);
@@ -353,8 +353,8 @@ protected:
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand0wRet::CCommand0wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand0wRet::CCommand0wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -373,8 +373,8 @@ QString CCommand0wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand1::CCommand1(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand1::CCommand1(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -410,8 +410,8 @@ QString CCommand1::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand1wRet::CCommand1wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand1wRet::CCommand1wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -448,8 +448,8 @@ QString CCommand1wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand2::CCommand2(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand2::CCommand2(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -487,8 +487,8 @@ QString CCommand2::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand2wRet::CCommand2wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand2wRet::CCommand2wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -527,8 +527,8 @@ QString CCommand2wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand3::CCommand3(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand3::CCommand3(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -568,8 +568,8 @@ QString CCommand3::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand3wRet::CCommand3wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand3wRet::CCommand3wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -610,8 +610,8 @@ QString CCommand3wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand4::CCommand4(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand4::CCommand4(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -654,8 +654,8 @@ QString CCommand4::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand4wRet::CCommand4wRet(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand4wRet::CCommand4wRet(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -699,8 +699,8 @@ QString CCommand4wRet::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand5::CCommand5(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand5::CCommand5(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
@@ -745,8 +745,8 @@ QString CCommand5::Execute(const CCommand::CArgs& args)
 //////////////////////////////////////////////////////////////////////////
 
 template 
-CCommand6::CCommand6(const string& module, const string& name,
-    const string& description, const string& example,
+CCommand6::CCommand6(const AZStd::string& module, const AZStd::string& name,
+    const AZStd::string& description, const AZStd::string& example,
     const AZStd::function& functor)
     : CCommand(module, name, description, example)
     , m_functor(functor)
diff --git a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
index c5b6694af4..8bdfb48774 100644
--- a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
+++ b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
@@ -41,7 +41,7 @@ public:
         return m_editor;
     }
 
-    const string& GetToolName() const
+    const AZStd::string& GetToolName() const
     {
         return m_toolName;
     }
diff --git a/Code/Editor/Util/EditorUtils.h b/Code/Editor/Util/EditorUtils.h
index fb767c98b3..1eb73532ef 100644
--- a/Code/Editor/Util/EditorUtils.h
+++ b/Code/Editor/Util/EditorUtils.h
@@ -18,6 +18,7 @@
 #include 
 #include "Util/FileUtil.h"
 #include 
+#include 
 
 //! Typedef for quaternion.
 //typedef CryQuat Quat;
diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp
index 9e4f688f69..d57d690154 100644
--- a/Code/Editor/Util/FileUtil.cpp
+++ b/Code/Editor/Util/FileUtil.cpp
@@ -1330,7 +1330,7 @@ IFileUtil::ECopyTreeResult CFileUtil::CopyTree(const QString& strSourceDirectory
         const QString fileName = QFileInfo(filePath).fileName();
 
         bool ignored = false;
-        for (const string& ignoredFile : ignoredPatterns)
+        for (const AZStd::string& ignoredFile : ignoredPatterns)
         {
             if (StringHelpers::CompareIgnoreCase(fileName.toStdString().c_str(), ignoredFile.c_str()) == 0)
             {
diff --git a/Code/Editor/Util/IXmlHistoryManager.h b/Code/Editor/Util/IXmlHistoryManager.h
index 78d849df7d..e133d073bc 100644
--- a/Code/Editor/Util/IXmlHistoryManager.h
+++ b/Code/Editor/Util/IXmlHistoryManager.h
@@ -62,7 +62,7 @@ struct IXmlHistoryManager
     // History
     virtual void ClearHistory(bool flagAsSaved = false) = 0;
     virtual int GetVersionCount() const = 0;
-    virtual const string& GetVersionDesc(int number) const = 0;
+    virtual const AZStd::string& GetVersionDesc(int number) const = 0;
     virtual int GetCurrentVersionNumber() const = 0;
 
     // Views
diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp
index a6bf622ad0..bf607e475e 100644
--- a/Code/Editor/Util/StringHelpers.cpp
+++ b/Code/Editor/Util/StringHelpers.cpp
@@ -84,7 +84,7 @@ static inline int Vsnprintf_s(wchar_t* str, size_t sizeInBytes, [[maybe_unused]]
 }
 
 
-int StringHelpers::Compare(const string& str0, const string& str1)
+int StringHelpers::Compare(const AZStd::string& str0, const AZStd::string& str1)
 {
     const size_t minLength = Util::getMin(str0.length(), str1.length());
     const int result = std::memcmp(str0.c_str(), str1.c_str(), minLength);
@@ -119,7 +119,7 @@ int StringHelpers::Compare(const wstring& str0, const wstring& str1)
 }
 
 
-int StringHelpers::CompareIgnoreCase(const string& str0, const string& str1)
+int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
 {
     const size_t minLength = Util::getMin(str0.length(), str1.length());
     const int result = azmemicmp(str0.c_str(), str1.c_str(), minLength);
@@ -154,7 +154,7 @@ int StringHelpers::CompareIgnoreCase(const wstring& str0, const wstring& str1)
 }
 
 
-bool StringHelpers::Equals(const string& str0, const string& str1)
+bool StringHelpers::Equals(const AZStd::string& str0, const AZStd::string& str1)
 {
     if (str0.length() != str1.length())
     {
@@ -173,7 +173,7 @@ bool StringHelpers::Equals(const wstring& str0, const wstring& str1)
 }
 
 
-bool StringHelpers::EqualsIgnoreCase(const string& str0, const string& str1)
+bool StringHelpers::EqualsIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
 {
     if (str0.length() != str1.length())
     {
@@ -200,7 +200,7 @@ bool StringHelpers::EqualsIgnoreCase(const wstring& str0, const wstring& str1)
 }
 
 
-bool StringHelpers::StartsWith(const string& str, const string& pattern)
+bool StringHelpers::StartsWith(const AZStd::string& str, const AZStd::string& pattern)
 {
     if (str.length() < pattern.length())
     {
@@ -219,7 +219,7 @@ bool StringHelpers::StartsWith(const wstring& str, const wstring& pattern)
 }
 
 
-bool StringHelpers::StartsWithIgnoreCase(const string& str, const string& pattern)
+bool StringHelpers::StartsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
 {
     if (str.length() < pattern.length())
     {
@@ -246,7 +246,7 @@ bool StringHelpers::StartsWithIgnoreCase(const wstring& str, const wstring& patt
 }
 
 
-bool StringHelpers::EndsWith(const string& str, const string& pattern)
+bool StringHelpers::EndsWith(const AZStd::string& str, const AZStd::string& pattern)
 {
     if (str.length() < pattern.length())
     {
@@ -265,7 +265,7 @@ bool StringHelpers::EndsWith(const wstring& str, const wstring& pattern)
 }
 
 
-bool StringHelpers::EndsWithIgnoreCase(const string& str, const string& pattern)
+bool StringHelpers::EndsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
 {
     if (str.length() < pattern.length())
     {
@@ -292,7 +292,7 @@ bool StringHelpers::EndsWithIgnoreCase(const wstring& str, const wstring& patter
 }
 
 
-bool StringHelpers::Contains(const string& str, const string& pattern)
+bool StringHelpers::Contains(const AZStd::string& str, const AZStd::string& pattern)
 {
     const size_t patternLength = pattern.length();
     if (str.length() < patternLength)
@@ -329,7 +329,7 @@ bool StringHelpers::Contains(const wstring& str, const wstring& pattern)
 }
 
 
-bool StringHelpers::ContainsIgnoreCase(const string& str, const string& pattern)
+bool StringHelpers::ContainsIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
 {
     const size_t patternLength = pattern.length();
     if (str.length() < patternLength)
@@ -380,7 +380,7 @@ bool StringHelpers::ContainsIgnoreCase(const wstring& str, const wstring& patter
     return false;
 }
 
-string StringHelpers::TrimLeft(const string& s)
+string StringHelpers::TrimLeft(const AZStd::string& s)
 {
     const size_t first = s.find_first_not_of(" \r\t");
     return (first == s.npos) ? string() : s.substr(first);
@@ -393,7 +393,7 @@ wstring StringHelpers::TrimLeft(const wstring& s)
 }
 
 
-string StringHelpers::TrimRight(const string& s)
+string StringHelpers::TrimRight(const AZStd::string& s)
 {
     const size_t last = s.find_last_not_of(" \r\t");
     return (last == s.npos) ? s : s.substr(0, last + 1);
@@ -406,7 +406,7 @@ wstring StringHelpers::TrimRight(const wstring& s)
 }
 
 
-string StringHelpers::Trim(const string& s)
+string StringHelpers::Trim(const AZStd::string& s)
 {
     return TrimLeft(TrimRight(s));
 }
@@ -447,7 +447,7 @@ static inline TS RemoveDuplicateSpaces_Tpl(const TS& s)
     return res;
 }
 
-string StringHelpers::RemoveDuplicateSpaces(const string& s)
+string StringHelpers::RemoveDuplicateSpaces(const AZStd::string& s)
 {
     return RemoveDuplicateSpaces_Tpl(s);
 }
@@ -470,7 +470,7 @@ static inline TS MakeLowerCase_Tpl(const TS& s)
     return copy;
 }
 
-string StringHelpers::MakeLowerCase(const string& s)
+string StringHelpers::MakeLowerCase(const AZStd::string& s)
 {
     return MakeLowerCase_Tpl(s);
 }
@@ -493,7 +493,7 @@ static inline TS MakeUpperCase_Tpl(const TS& s)
     return copy;
 }
 
-string StringHelpers::MakeUpperCase(const string& s)
+string StringHelpers::MakeUpperCase(const AZStd::string& s)
 {
     return MakeUpperCase_Tpl(s);
 }
@@ -517,7 +517,7 @@ static inline TS Replace_Tpl(const TS& s, const typename TS::value_type oldChar,
     return copy;
 }
 
-string StringHelpers::Replace(const string& s, char oldChar, char newChar)
+string StringHelpers::Replace(const AZStd::string& s, char oldChar, char newChar)
 {
     return Replace_Tpl(s, oldChar, newChar);
 }
@@ -528,12 +528,12 @@ wstring StringHelpers::Replace(const wstring& s, wchar_t oldChar, wchar_t newCha
 }
 
 
-void StringHelpers::ConvertStringByRef(string& out, const string& in)
+void StringHelpers::ConvertStringByRef(string& out, const AZStd::string& in)
 {
     out = in;
 }
 
-void StringHelpers::ConvertStringByRef(wstring& out, const string& in)
+void StringHelpers::ConvertStringByRef(wstring& out, const AZStd::string& in)
 {
     Unicode::Convert(out, in);
 }
@@ -630,7 +630,7 @@ static inline void SplitByAnyOf_Tpl(const TS& str, const TS& separators, bool bR
 
 
 
-void StringHelpers::Split(const string& str, const string& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
+void StringHelpers::Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
     Split_Tpl(str, separator, bReturnEmptyPartsToo, outParts);
 }
@@ -641,7 +641,7 @@ void StringHelpers::Split(const wstring& str, const wstring& separator, bool bRe
 }
 
 
-void StringHelpers::SplitByAnyOf(const string& str, const string& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
+void StringHelpers::SplitByAnyOf(const AZStd::string& str, const AZStd::string& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
     SplitByAnyOf_Tpl(str, separators, bReturnEmptyPartsToo, outParts);
 }
diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h
index da4aa9c9cc..ec5515fbc9 100644
--- a/Code/Editor/Util/StringHelpers.h
+++ b/Code/Editor/Util/StringHelpers.h
@@ -15,83 +15,83 @@ namespace StringHelpers
 {
     // compares two strings to see if they are the same or different, case sensitive
     // returns 0 if the strings are the same, a -1 if the first string is bigger, or a 1 if the second string is bigger
-    int Compare(const string& str0, const string& str1);
+    int Compare(const AZStd::string& str0, const AZStd::string& str1);
     int Compare(const wstring& str0, const wstring& str1);
 
     // compares two strings to see if they are the same or different, case is ignored
     // returns 0 if the strings are the same, a -1 if the first string is bigger, or a 1 if the second string is bigger
-    int CompareIgnoreCase(const string& str0, const string& str1);
+    int CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1);
     int CompareIgnoreCase(const wstring& str0, const wstring& str1);
 
     // compares two strings to see if they are the same, case senstive
     // returns true if they are the same or false if they are different
-    bool Equals(const string& str0, const string& str1);
+    bool Equals(const AZStd::string& str0, const AZStd::string& str1);
     bool Equals(const wstring& str0, const wstring& str1);
 
     // compares two strings to see if they are the same, case is ignored
     // returns true if they are the same or false if they are different
-    bool EqualsIgnoreCase(const string& str0, const string& str1);
+    bool EqualsIgnoreCase(const AZStd::string& str0, const AZStd::string& str1);
     bool EqualsIgnoreCase(const wstring& str0, const wstring& str1);
 
     // checks to see if a string starts with a specified string, case sensitive
     // returns true if the string does start with a specified string or false if it does not
-    bool StartsWith(const string& str, const string& pattern);
+    bool StartsWith(const AZStd::string& str, const AZStd::string& pattern);
     bool StartsWith(const wstring& str, const wstring& pattern);
 
     // checks to see if a string starts with a specified string, case is ignored
     // returns true if the string does start with a specified string or false if it does not
-    bool StartsWithIgnoreCase(const string& str, const string& pattern);
+    bool StartsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
     bool StartsWithIgnoreCase(const wstring& str, const wstring& pattern);
 
     // checks to see if a string ends with a specified string, case sensitive
     // returns true if the string does end with a specified string or false if it does not
-    bool EndsWith(const string& str, const string& pattern);
+    bool EndsWith(const AZStd::string& str, const AZStd::string& pattern);
     bool EndsWith(const wstring& str, const wstring& pattern);
 
     // checks to see if a string ends with a specified string, case is ignored
     // returns true if the string does end with a specified string or false if it does not
-    bool EndsWithIgnoreCase(const string& str, const string& pattern);
+    bool EndsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
     bool EndsWithIgnoreCase(const wstring& str, const wstring& pattern);
 
     // checks to see if a string contains a specified string, case sensitive
     // returns true if the string does contain the specified string or false if it does not
-    bool Contains(const string& str, const string& pattern);
+    bool Contains(const AZStd::string& str, const AZStd::string& pattern);
     bool Contains(const wstring& str, const wstring& pattern);
 
     // checks to see if a string contains a specified string, case is ignored
     // returns true if the string does contain the specified string or false if it does not
-    bool ContainsIgnoreCase(const string& str, const string& pattern);
+    bool ContainsIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
     bool ContainsIgnoreCase(const wstring& str, const wstring& pattern);
 
-    string TrimLeft(const string& s);
+    string TrimLeft(const AZStd::string& s);
     wstring TrimLeft(const wstring& s);
 
-    string TrimRight(const string& s);
+    string TrimRight(const AZStd::string& s);
     wstring TrimRight(const wstring& s);
 
-    string Trim(const string& s);
+    string Trim(const AZStd::string& s);
     wstring Trim(const wstring& s);
 
-    string RemoveDuplicateSpaces(const string& s);
+    string RemoveDuplicateSpaces(const AZStd::string& s);
     wstring RemoveDuplicateSpaces(const wstring& s);
 
     // converts a string with upper case characters to be all lower case
     // returns the string in all lower case
-    string MakeLowerCase(const string& s);
+    string MakeLowerCase(const AZStd::string& s);
     wstring MakeLowerCase(const wstring& s);
 
     // converts a string with lower case characters to be all upper case
     // returns the string in all upper case
-    string MakeUpperCase(const string& s);
+    string MakeUpperCase(const AZStd::string& s);
     wstring MakeUpperCase(const wstring& s);
 
     // replace a specified character in a string with a specified replacement character
     // returns string with specified character replaced
-    string Replace(const string& s, char oldChar, char newChar);
+    string Replace(const AZStd::string& s, char oldChar, char newChar);
     wstring Replace(const wstring& s, wchar_t oldChar, wchar_t newChar);
 
-    void ConvertStringByRef(string& out, const string& in);
-    void ConvertStringByRef(wstring& out, const string& in);
+    void ConvertStringByRef(string& out, const AZStd::string& in);
+    void ConvertStringByRef(wstring& out, const AZStd::string& in);
     void ConvertStringByRef(string& out, const wstring& in);
     void ConvertStringByRef(wstring& out, const wstring& in);
 
@@ -103,10 +103,10 @@ namespace StringHelpers
         return out;
     }
     
-    void Split(const string& str, const string& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
+    void Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
     void Split(const wstring& str, const wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
 
-    void SplitByAnyOf(const string& str, const string& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
+    void SplitByAnyOf(const AZStd::string& str, const AZStd::string& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
     void SplitByAnyOf(const wstring& str, const wstring& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
 
     string FormatVA(const char* const format, va_list parg);
diff --git a/Code/Editor/Util/XmlHistoryManager.cpp b/Code/Editor/Util/XmlHistoryManager.cpp
index 3aea041d29..5a1bc237bb 100644
--- a/Code/Editor/Util/XmlHistoryManager.cpp
+++ b/Code/Editor/Util/XmlHistoryManager.cpp
@@ -419,7 +419,7 @@ void CXmlHistoryManager::ClearHistory(bool flagAsSaved)
 }
 
 /////////////////////////////////////////////////////////////////////////////
-const string& CXmlHistoryManager::GetVersionDesc(int number) const
+const AZStd::string& CXmlHistoryManager::GetVersionDesc(int number) const
 {
     THistoryInfoMap::const_iterator it = m_HistoryInfoMap.find(number);
     if (it != m_HistoryInfoMap.end())
diff --git a/Code/Editor/Util/XmlHistoryManager.h b/Code/Editor/Util/XmlHistoryManager.h
index d894bc7f00..12699536e5 100644
--- a/Code/Editor/Util/XmlHistoryManager.h
+++ b/Code/Editor/Util/XmlHistoryManager.h
@@ -103,7 +103,7 @@ public:
     // History
     void ClearHistory(bool flagAsSaved = false);
     int GetVersionCount() const { return m_LatestVersion; }
-    const string& GetVersionDesc(int number) const;
+    const AZStd::string& GetVersionDesc(int number) const;
     int GetCurrentVersionNumber() const { return m_CurrentVersion; }
 
     // Views
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp b/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
index 3c3c1183e4..23e967c3fa 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
@@ -417,7 +417,7 @@ namespace GridMate
     {
         GM_CLASS_ALLOCATOR(Connection); // make a pool and use it...
 
-        Connection(CarrierThread* threadOwner, const string& address);
+        Connection(CarrierThread* threadOwner, const AZStd::string& address);
         ~Connection();
 
         CarrierThread*              m_threadOwner;                                  ///< Pointer to the carrier thread that operates with this connection.
@@ -999,7 +999,7 @@ namespace GridMate
         /// Connect with host and port. This is ASync operation, the connection is active after OnConnectionEstablished is called.
         ConnectionID    Connect(const char* hostAddress, unsigned int port) override;
         /// Connect with internal address format. This is ASync operation, the connection is active after OnConnectionEstablished is called.
-        ConnectionID    Connect(const string& address) override;
+        ConnectionID    Connect(const AZStd::string& address) override;
         /// Request a disconnect procedure. This is ASync operation, the connection is closed after OnDisconnect is called.
         void            Disconnect(ConnectionID id) override;
 
@@ -1118,7 +1118,7 @@ using namespace GridMate;
 // Connection
 //////////////////////////////////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////////
-Connection::Connection(CarrierThread* threadOwner, const string& address)
+Connection::Connection(CarrierThread* threadOwner, const AZStd::string& address)
     : m_threadOwner(threadOwner)
     , m_threadConn(NULL)
     , m_fullAddress(address)
@@ -3740,7 +3740,7 @@ CarrierImpl::Connect(const char* hostAddress, unsigned int port)
 // [1/12/2011]
 //=========================================================================
 ConnectionID
-CarrierImpl::Connect(const string& address)
+CarrierImpl::Connect(const AZStd::string& address)
 {
     // check if we don't have it in the list.
     for(auto& i : m_connections)
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Carrier.h b/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
index 5bfa621af1..2968582c0d 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
@@ -88,7 +88,7 @@ namespace GridMate
         /// Connect with host and port. This is ASync operation, the connection is active after OnConnectionEstablished is called.
         virtual ConnectionID    Connect(const char* hostAddress, unsigned int port) = 0;
         /// Connect with internal address format. This is ASync operation, the connection is active after OnConnectionEstablished is called.
-        virtual ConnectionID    Connect(const string& address) = 0;
+        virtual ConnectionID    Connect(const AZStd::string& address) = 0;
         /// Request a disconnect procedure. This is ASync operation, the connection is closed after OnDisconnect is called.
         virtual void            Disconnect(ConnectionID id) = 0;
 
diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.cpp b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.cpp
index bc657becbc..58436bb757 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.cpp
@@ -98,7 +98,7 @@ DefaultHandshake::OnConfirmAck(ConnectionID id, ReadBuffer& rb)
 // [11/5/2010]
 //=========================================================================
 bool
-DefaultHandshake::OnNewConnection(const string& address)
+DefaultHandshake::OnNewConnection(const AZStd::string& address)
 {
     (void)address;
     return true; /// We don't have a ban list yet
diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
index 0b9240dfa3..8f456e4649 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
@@ -47,7 +47,7 @@ namespace GridMate
         */
         virtual bool                OnConfirmAck(ConnectionID id, ReadBuffer& rb);
         /// Return true if you want to reject early reject a connection.
-        virtual bool                OnNewConnection(const string& address);
+        virtual bool                OnNewConnection(const AZStd::string& address);
         /// Called when we close a connection.
         virtual void                OnDisconnect(ConnectionID id);
         /// Return timeout in milliseconds of the handshake procedure.
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Driver.h b/Code/Framework/GridMate/GridMate/Carrier/Driver.h
index 84e43b5acf..2c806be5e0 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Driver.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Driver.h
@@ -140,7 +140,7 @@ namespace GridMate
         /// @{ Address conversion functionality. They MUST implemented thread safe. Generally this is not a problem since they just part local data.
         ///  Create address from ip and port. If ip == NULL we will assign a broadcast address.
         virtual string          IPPortToAddress(const char* ip, unsigned int port) const = 0;
-        virtual bool            AddressToIPPort(const string& address, string& ip, unsigned int& port) const = 0;
+        virtual bool            AddressToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) const = 0;
         /// @}
 
         /**
@@ -150,7 +150,7 @@ namespace GridMate
          * \note Driver address allocates internal resources, use it only when you intend to communicate. Otherwise operate with
          * the string address.
          */
-        virtual AZStd::intrusive_ptr CreateDriverAddress(const string& address) = 0;
+        virtual AZStd::intrusive_ptr CreateDriverAddress(const AZStd::string& address) = 0;
 
         /**
          * Returns true if the driver can accept new data (ex, has buffer space).
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
index 5d06f2f1b8..ffd332b65c 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
@@ -53,7 +53,7 @@ namespace GridMate
          */
         virtual bool                OnConfirmAck(ConnectionID id, ReadBuffer& rb) = 0;
         /// Return true if you want to reject early reject a connection.
-        virtual bool                OnNewConnection(const string& address) = 0;
+        virtual bool                OnNewConnection(const AZStd::string& address) = 0;
         /// Called when we close a connection.
         virtual void                OnDisconnect(ConnectionID id) = 0;
         /// Return timeout in milliseconds of the handshake procedure.
diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
index b75de6f383..fc3062062c 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
@@ -498,7 +498,7 @@ namespace GridMate
         }
     }
 
-    SocketDriverAddress::SocketDriverAddress(Driver* driver, const string& ip, unsigned int port)
+    SocketDriverAddress::SocketDriverAddress(Driver* driver, const AZStd::string& ip, unsigned int port)
         : DriverAddress(driver)
     {
         AZ_Assert(!ip.empty(), "Invalid address string!");
@@ -1156,7 +1156,7 @@ namespace GridMate
     // [3/4/2013]
     //=========================================================================
     bool
-    SocketDriverCommon::AddressStringToIPPort(const string& address, string& ip, unsigned int& port)
+    SocketDriverCommon::AddressStringToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port)
     {
         AZStd::size_t pos = address.find('|');
         AZ_Assert(pos != string::npos, "Invalid driver address!");
@@ -1176,7 +1176,7 @@ namespace GridMate
     // [7/11/2013]
     //=========================================================================
     Driver::BSDSocketFamilyType
-    SocketDriverCommon::AddressFamilyType(const string& ip)
+    SocketDriverCommon::AddressFamilyType(const AZStd::string& ip)
     {
         // TODO: We can/should use inet_ntop() to detect the family type
         AZStd::size_t pos = ip.find(".");
@@ -1198,13 +1198,13 @@ namespace GridMate
     //////////////////////////////////////////////////////////////////////////
     //////////////////////////////////////////////////////////////////////////
     //=========================================================================
-    // CreateDriverAddress(const string&)
+    // CreateDriverAddress(const AZStd::string&)
     // [1/12/2011]
     //=========================================================================
     AZStd::intrusive_ptr
-    SocketDriver::CreateDriverAddress(const string& address)
+    SocketDriver::CreateDriverAddress(const AZStd::string& address)
     {
-        string ip;
+        AZStd::string ip;
         unsigned int port;
         if (!AddressToIPPort(address, ip, port))
         {
@@ -1243,7 +1243,7 @@ namespace GridMate
     namespace Utils
     {
         // \note function moved here to use addinfo when IPV6 is not in use, consider moving those definitions to a header file
-        bool GetIpByHostName(int familyType, const char* hostName, string& ip)
+        bool GetIpByHostName(int familyType, const char* hostName, AZStd::string& ip)
         {
             static const size_t kMaxLen = 64; // max length of ipv6 ip is 45 chars, so all ips should be able to fit in this buf
             char ipBuf[kMaxLen];
diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
index bda135f532..7555c92639 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
@@ -83,7 +83,7 @@ namespace GridMate
 
         SocketDriverAddress(Driver* driver);
         SocketDriverAddress(Driver* driver, const sockaddr* addr);
-        SocketDriverAddress(Driver* driver, const string& ip, unsigned int port);
+        SocketDriverAddress(Driver* driver, const AZStd::string& ip, unsigned int port);
 
         bool operator==(const SocketDriverAddress& rhs) const;
         bool operator!=(const SocketDriverAddress& rhs) const;
@@ -164,17 +164,17 @@ namespace GridMate
         /// @{ Address conversion functionality. They MUST implemented thread safe. Generally this is not a problem since they just part local data.
         ///  Create address from ip and port. If ip == NULL we will assign a broadcast address.
         virtual string  IPPortToAddress(const char* ip, unsigned int port) const                        { return IPPortToAddressString(ip, port); }
-        virtual bool    AddressToIPPort(const string& address, string& ip, unsigned int& port) const    { return AddressStringToIPPort(address, ip, port); }
+        virtual bool    AddressToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) const    { return AddressStringToIPPort(address, ip, port); }
         /// Create address for the socket driver from IP and port
         static string   IPPortToAddressString(const char* ip, unsigned int port);
         /// Decompose an address to IP and port
-        static bool     AddressStringToIPPort(const string& address, string& ip, unsigned int& port);
+        static bool     AddressStringToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port);
         /// Return the family type of the address (AF_INET,AF_INET6 AF_UNSPEC)
-        static BSDSocketFamilyType  AddressFamilyType(const string& ip);
+        static BSDSocketFamilyType  AddressFamilyType(const AZStd::string& ip);
         static BSDSocketFamilyType  AddressFamilyType(const char* ip)           { return AddressFamilyType(string(ip)); }
         /// @}
 
-        virtual AZStd::intrusive_ptr CreateDriverAddress(const string& address) = 0;
+        virtual AZStd::intrusive_ptr CreateDriverAddress(const AZStd::string& address) = 0;
         /// Additional CreateDriverAddress function should be implemented.
         virtual AZStd::intrusive_ptr CreateDriverAddress(const sockaddr* sockAddr) = 0;
 
@@ -352,7 +352,7 @@ namespace GridMate
         * \note Driver address allocates internal resources, use it only when you intend to communicate. Otherwise operate with
         * the string address.
         */
-        virtual AZStd::intrusive_ptr CreateDriverAddress(const string& address);
+        virtual AZStd::intrusive_ptr CreateDriverAddress(const AZStd::string& address);
         virtual AZStd::intrusive_ptr CreateDriverAddress(const sockaddr* addr);
         /// Called only from the DriverAddress when the use count becomes 0
         virtual void    DestroyDriverAddress(DriverAddress* address);
@@ -364,7 +364,7 @@ namespace GridMate
     namespace Utils
     {
         ///< Retrieves ip address corresponding to a host name. Blocks thread until dns resolving is happened.
-        bool GetIpByHostName(int familyType, const char* hostName, string& ip);
+        bool GetIpByHostName(int familyType, const char* hostName, AZStd::string& ip);
     }
 
     /**
diff --git a/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.cpp b/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.cpp
index 5a34b70e74..a7130218f8 100644
--- a/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.cpp
+++ b/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.cpp
@@ -224,7 +224,7 @@ namespace GridMate
         // [4/15/2011]
         //=========================================================================
         void
-        SessionDriller::OnSessionError(GridSession* session, const string& errorMsg)
+        SessionDriller::OnSessionError(GridSession* session, const AZStd::string& errorMsg)
         {
             m_output->BeginTag(m_drillerTag);
             m_output->BeginTag(AZ_CRC("SessionError", 0xc689cc40));
diff --git a/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.h b/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.h
index b89fae3d73..59f178976f 100644
--- a/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.h
+++ b/Code/Framework/GridMate/GridMate/Drillers/SessionDriller.h
@@ -62,7 +62,7 @@ namespace GridMate
             /// Callback that notifies the title when a session will be left. session pointer is NOT valid after the callback returns.
             virtual void OnSessionDelete(GridSession* session);
             /// Called when a session error occurs.
-            virtual void OnSessionError(GridSession* session, const string& errorMsg);
+            virtual void OnSessionError(GridSession* session, const AZStd::string& errorMsg);
             /// Called when the actual game(match) starts
             virtual void OnSessionStart(GridSession* session);
             /// Called when the actual game(match) ends
diff --git a/Code/Framework/GridMate/GridMate/Session/LANSession.cpp b/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
index fca43c2709..0127d8fa23 100644
--- a/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
+++ b/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
@@ -37,7 +37,7 @@ namespace GridMate
     {
         friend class LANMemberIDMarshaler;
 
-        static LANMemberID Create(MemberIDCompact id, const string& address)
+        static LANMemberID Create(MemberIDCompact id, const AZStd::string& address)
         {
             LANMemberID mid;
             mid.m_id = id;
@@ -45,7 +45,7 @@ namespace GridMate
             return mid;
         }
 
-        void SetAddress(const string& address)
+        void SetAddress(const AZStd::string& address)
         {
             m_address = address;
         }
@@ -120,14 +120,14 @@ namespace GridMate
         /// Creates the local player.
         GridMember* CreateLocalMember(bool isHost, bool isInvited, RemotePeerMode peerMode);
         /// Creates remote player, when he wants to join.
-        GridMember* CreateRemoteMember(const string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId = InvalidConnectionID) override;
+        GridMember* CreateRemoteMember(const AZStd::string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId = InvalidConnectionID) override;
 
         /// Called when we receive the session replica. We create one and return the pointer.
         LANSessionReplica*  OnSessionReplicaArrived();
 
         /// Called when session parameters have changed.
         void OnSessionParamChanged(const GridSessionParam& param) override { (void)param; }
-        void OnSessionParamRemoved(const string& paramId) override { (void)paramId; }
+        void OnSessionParamRemoved(const AZStd::string& paramId) override { (void)paramId; }
 
     private:
         explicit LANSession(LANSessionService* service);
@@ -762,7 +762,7 @@ LANSession::CreateLocalMember(bool isHost, bool isInvited, RemotePeerMode peerMo
 // [2/2/2011]
 //==========================================================================
 GridMember*
-LANSession::CreateRemoteMember(const string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId)
+LANSession::CreateRemoteMember(const AZStd::string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId)
 {
     MemberIDCompact id;
     data.Read(id);
@@ -803,7 +803,7 @@ LANSession::OnStateCreate(AZ::HSM& sm, const AZ::HSM::Event& e)
     {
         // patch the ID if we use implicit port
         AZ_Assert(m_carrier, "Carrier must be created!");
-        string ip;
+        AZStd::string ip;
         unsigned int port;
         SocketDriverCommon::AddressStringToIPPort(m_myMember->GetId().ToAddress(), ip, port);
         AZ_Assert(port == 0 || port == m_carrier->GetPort(), "Carrier port missmatch! It should either be 0 (and patched here) in the implicit bind or the port number for explicit bind!");
diff --git a/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h b/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
index ee4c0a8659..20ade42a6e 100644
--- a/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
+++ b/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
@@ -39,9 +39,9 @@ namespace GridMate
         {}
 
         int     m_familyType;                   ///< Socket driver specific, by default 0.
-        string  m_serverAddress;                ///< Address of the server, we empty we create a broadcast address.
+        AZStd::string  m_serverAddress;         ///< Address of the server, we empty we create a broadcast address.
         int     m_serverPort;                   ///< Server port (must be provided).
-        string  m_listenAddress;                ///< Address to bind for listening. By default is empty, which means we are listening to any address.
+        AZStd::string  m_listenAddress;         ///< Address to bind for listening. By default is empty, which means we are listening to any address.
         int     m_listenPort;                   ///< Search listen port, if not set we will use ephimeral port.
         unsigned int m_broadcastFrequencyMs;    ///< Time in MS between search broadcasts.
     };
@@ -52,7 +52,7 @@ namespace GridMate
     struct LANSearchInfo
         : public SearchInfo
     {
-        string m_serverIP; ///< server ID as we see it
+        AZStd::string m_serverIP; ///< server ID as we see it
         AZ::u16 m_serverPort; ///< server port for the session
     };
 }
diff --git a/Code/Framework/GridMate/GridMate/Session/Session.cpp b/Code/Framework/GridMate/GridMate/Session/Session.cpp
index 5746a91c19..8a9bdea273 100644
--- a/Code/Framework/GridMate/GridMate/Session/Session.cpp
+++ b/Code/Framework/GridMate/GridMate/Session/Session.cpp
@@ -92,7 +92,7 @@ namespace GridMate
             */
             virtual bool            OnConfirmAck(ConnectionID id, ReadBuffer& rb)   { (void)id; (void)rb; return true; } // we don't do any further filtering
             /// Return true if you want to reject early reject a connection.
-            virtual bool            OnNewConnection(const string& address);
+            virtual bool            OnNewConnection(const AZStd::string& address);
             /// Called when we close a connection.
             virtual void            OnDisconnect(ConnectionID id);
             /// Return timeout in milliseconds of the handshake procedure.
@@ -684,7 +684,7 @@ GridSession::SetParam(const GridSessionParam& param)
 // RemoveParam
 //=========================================================================
 bool
-GridSession::RemoveParam(const string& paramId)
+GridSession::RemoveParam(const AZStd::string& paramId)
 {
     AZ_Assert(m_state, "Invalid session state replica. Session is not initialized.");
 
@@ -970,7 +970,7 @@ GridSession::AddMember(GridMember* member)
 // IsAddressInMemberList
 //=========================================================================
 bool
-GridSession::IsAddressInMemberList(const string& address)
+GridSession::IsAddressInMemberList(const AZStd::string& address)
 {
     for (AZStd::size_t i = 0; i < m_members.size(); ++i)
     {
@@ -2783,7 +2783,7 @@ bool GridSessionHandshake::OnConfirmRequest(ConnectionID id, ReadBuffer& rb)
 //=========================================================================
 // OnNewConnection
 //=========================================================================
-bool GridSessionHandshake::OnNewConnection(const string& address)
+bool GridSessionHandshake::OnNewConnection(const AZStd::string& address)
 {
     AZStd::lock_guard l(m_dataLock);
 
diff --git a/Code/Framework/GridMate/GridMate/Session/Session.h b/Code/Framework/GridMate/GridMate/Session/Session.h
index 63aa504a49..03556756ba 100644
--- a/Code/Framework/GridMate/GridMate/Session/Session.h
+++ b/Code/Framework/GridMate/GridMate/Session/Session.h
@@ -249,7 +249,7 @@ namespace GridMate
         /// Callback that notifies the title when a session will be left. session pointer is NOT valid after the callback returns.
         virtual void OnSessionDelete(GridSession* session) { (void)session; }
         /// Called when a session error occurs.
-        virtual void OnSessionError(GridSession* session, const string& errorMsg) { (void)session; (void)errorMsg; }
+        virtual void OnSessionError(GridSession* session, const AZStd::string& errorMsg) { (void)session; (void)errorMsg; }
         /// Called when the actual game(match) starts
         virtual void OnSessionStart(GridSession* session) { (void)session; }
         /// Called when the actual game(match) ends
@@ -484,7 +484,7 @@ namespace GridMate
         // Adds/updates a parameter. Returns false if parameter can not be added.
         bool SetParam(const GridSessionParam& param);
         // Removes a parameter by id. Returns false if parameter can not be removed.
-        bool RemoveParam(const string& paramId);
+        bool RemoveParam(const AZStd::string& paramId);
         // Removes a parameter by index. Returns false if parameter can not be removed.
         bool RemoveParam(unsigned int index);
 
@@ -543,9 +543,9 @@ namespace GridMate
         /// Frees a slot based on a slot type.
         void FreeSlot(int slotType);
         /// Creates remote player, when he wants to join.
-        virtual GridMember* CreateRemoteMember(const string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId = InvalidConnectionID) = 0;
+        virtual GridMember* CreateRemoteMember(const AZStd::string& address, ReadBuffer& data, RemotePeerMode peerMode, ConnectionID connId = InvalidConnectionID) = 0;
         /// Returns true if this address belongs to a member in the list, otherwise false.
-        virtual bool IsAddressInMemberList(const string& address);
+        virtual bool IsAddressInMemberList(const AZStd::string& address);
         virtual bool IsConnectionIdInMemberList(const ConnectionID& connId);
         /// Adds a created member to the session. Return false if no free slow was found!
         virtual bool AddMember(GridMember* member);
@@ -558,7 +558,7 @@ namespace GridMate
         /// Called when a session parameter is added/changed.
         virtual void OnSessionParamChanged(const GridSessionParam& param) = 0;
         /// Called when a session parameter is deleted.
-        virtual void OnSessionParamRemoved(const string& paramId) = 0;
+        virtual void OnSessionParamRemoved(const AZStd::string& paramId) = 0;
         //////////////////////////////////////////////////////////////////////////
 
         SessionID m_sessionId; ///< Session id. Content of the string will vary based on session types and platforms.
@@ -975,7 +975,7 @@ namespace GridMate
             /// Callback that notifies the title when a session will be left. session pointer is NOT valid after the callback returns.
             virtual void OnSessionDelete(GridSession* session) { (void)session; }
             /// Called when a session error occurs.
-            virtual void OnSessionError(GridSession* session, const string& errorMsg) { (void)session; (void)errorMsg; }
+            virtual void OnSessionError(GridSession* session, const AZStd::string& errorMsg) { (void)session; (void)errorMsg; }
             /// Called when the actual game(match) starts
             virtual void OnSessionStart(GridSession* session) { (void)session; }
             /// Called when the actual game(match) ends
diff --git a/Code/Framework/GridMate/Tests/Session.cpp b/Code/Framework/GridMate/Tests/Session.cpp
index 9e10e84e98..0c5baef483 100644
--- a/Code/Framework/GridMate/Tests/Session.cpp
+++ b/Code/Framework/GridMate/Tests/Session.cpp
@@ -241,7 +241,7 @@ namespace UnitTest
                 (void)reason;
             }
 
-            void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+            void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
             {
                 (void)session;
 #ifndef AZ_LAN_TEST_MAIN_THREAD_BLOCKED  // we will receive an error is we block for a long time
@@ -599,7 +599,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
             AZ_TEST_ASSERT(false);
@@ -834,7 +834,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
 #ifndef AZ_LAN_TEST_MAIN_THREAD_BLOCKED  // we will receive an error is we block for a long time
@@ -1207,7 +1207,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
             AZ_TEST_ASSERT(false);
@@ -1521,7 +1521,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
             // On this test we will get a open port error because we have multiple hosts. This is ok, since we test migration here!
@@ -1861,7 +1861,7 @@ namespace UnitTest
             (void)member;
             (void)reason;
         }
-        void OnSessionError(GridSession* session, const string& /*errorMsg*/) override
+        void OnSessionError(GridSession* session, const AZStd::string& /*errorMsg*/) override
         {
             (void)session;
             // On this test we will get a open port error because we have multiple hosts. This is ok, since we test migration here!
diff --git a/Code/Framework/GridMate/Tests/TestProfiler.cpp b/Code/Framework/GridMate/Tests/TestProfiler.cpp
index 428c1249ee..9f79d5a9fe 100644
--- a/Code/Framework/GridMate/Tests/TestProfiler.cpp
+++ b/Code/Framework/GridMate/Tests/TestProfiler.cpp
@@ -34,7 +34,7 @@ static bool CollectPerformanceCounters(const AZ::Debug::ProfilerRegister& reg, c
     return true;
 }
 
-static string FormatString(const string& pre, const string& name, const string& post, AZ::u64 time, AZ::u64 calls)
+static string FormatString(const AZStd::string& pre, const AZStd::string& name, const AZStd::string& post, AZ::u64 time, AZ::u64 calls)
 {
     string units = "us";
     if (AZ::u64 divtime = time / 1000)
diff --git a/Code/Legacy/CryCommon/LocalizationManagerBus.h b/Code/Legacy/CryCommon/LocalizationManagerBus.h
index 69ab32cebf..1d818de111 100644
--- a/Code/Legacy/CryCommon/LocalizationManagerBus.h
+++ b/Code/Legacy/CryCommon/LocalizationManagerBus.h
@@ -102,7 +102,7 @@ public:
     virtual bool LocalizeString_ch(const char* sString, AZStd::string& outLocalizedString, bool bEnglish = false) = 0;
 
     // Summary:
-    //   Same as LocalizeString( const char* sString, string& outLocalizedString, bool bEnglish=false )
+    //   Same as LocalizeString( const char* sString, AZStd::string& outLocalizedString, bool bEnglish=false )
     //   but at the moment this is faster.
     virtual bool LocalizeString_s(const AZStd::string& sString, AZStd::string& outLocalizedString, bool bEnglish = false) = 0;
 
diff --git a/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h b/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h
index 3515dab68e..e04fb6ada7 100644
--- a/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h
+++ b/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h
@@ -120,7 +120,7 @@ public:
     CUiAnimParamType()
         : m_type(eUiAnimParamType_Invalid) {}
 
-    CUiAnimParamType(const string& name)
+    CUiAnimParamType(const AZStd::string& name)
     {
         *this = name;
     }
@@ -136,17 +136,12 @@ public:
         m_type = (EUiAnimParamType)type;
     }
 
-    void operator =(const string& name)
-    {
-        m_type = eUiAnimParamType_ByString;
-        m_name = name;
-    }
-
     void operator =(const AZStd::string& name)
     {
         m_type = eUiAnimParamType_ByString;
         m_name = name.c_str();
     }
+
     // Convert to enum. This needs to be explicit,
     // otherwise operator== will be ambiguous
     EUiAnimParamType GetType() const { return m_type; }
@@ -1301,7 +1296,7 @@ inline void SUiAnimContext::Serialize(IUiAnimationSystem* animationSystem, XmlNo
     {
         if (pSequence)
         {
-            string fullname = pSequence->GetName();
+            AZStd::string fullname = pSequence->GetName();
             xmlNode->setAttr("sequence", fullname.c_str());
         }
         xmlNode->setAttr("dt", dt);
diff --git a/Code/Legacy/CryCommon/LyShine/ISprite.h b/Code/Legacy/CryCommon/LyShine/ISprite.h
index cd2b70ef25..373024d2db 100644
--- a/Code/Legacy/CryCommon/LyShine/ISprite.h
+++ b/Code/Legacy/CryCommon/LyShine/ISprite.h
@@ -59,10 +59,10 @@ public: // member functions
     virtual ~ISprite() {}
 
     //! Get the pathname of this sprite
-    virtual const string& GetPathname() const = 0;
+    virtual const AZStd::string& GetPathname() const = 0;
 
     //! Get the pathname of the texture of this sprite
-    virtual const string& GetTexturePathname() const = 0;
+    virtual const AZStd::string& GetTexturePathname() const = 0;
 
     //! Get the borders of this sprite
     virtual Borders GetBorders() const = 0;
@@ -77,7 +77,7 @@ public: // member functions
     virtual void Serialize(TSerialize ser) = 0;
 
     //! Save this sprite data to disk
-    virtual bool SaveToXml(const string& pathname) = 0;
+    virtual bool SaveToXml(const AZStd::string& pathname) = 0;
 
     //! Test if this sprite has any borders
     virtual bool AreBordersZeroWidth() const = 0;
@@ -136,4 +136,3 @@ public: // member functions
     //! Returns true if this sprite is configured as a sprite-sheet, false otherwise
     virtual bool IsSpriteSheet() const = 0;
 };
-

From 58f1cb9b6c02f4a315c3b21ba6212e382a92166c Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:55:08 -0700
Subject: [PATCH 037/205] Gems/LytShine

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Animation/Controls/UiSplineCtrlEx.cpp     |  2 +-
 .../Animation/Controls/UiSplineCtrlEx.h       |  4 +-
 .../Editor/Animation/UiAnimViewAnimNode.cpp   |  4 +-
 .../Editor/Animation/UiAnimViewDialog.cpp     |  6 +--
 .../Editor/Animation/UiAnimViewFindDlg.cpp    |  3 +-
 .../Animation/UiAnimViewNewSequenceDialog.cpp |  2 +-
 .../Code/Editor/Animation/UiAnimViewNodes.cpp | 14 +++---
 .../Editor/Animation/UiAnimViewSequence.cpp   | 12 ++---
 .../Code/Editor/Animation/UiAnimViewUndo.cpp  |  6 +--
 .../Code/Editor/Animation/UiAnimViewUndo.h    |  6 +--
 Gems/LyShine/Code/Editor/AssetTreeEntry.cpp   |  2 +-
 Gems/LyShine/Code/Editor/EditorMenu.cpp       |  2 +-
 .../Code/Editor/PropertiesContainer.cpp       |  2 +-
 .../Code/Editor/PropertyHandlerChar.cpp       | 13 +++---
 .../Code/Editor/PropertyHandlerDirectory.cpp  |  8 ++--
 .../Code/Editor/SpriteBorderEditor.cpp        |  2 +-
 .../Code/Source/Animation/AnimSequence.cpp    |  4 +-
 .../Code/Source/Animation/AnimSequence.h      |  2 +-
 .../Code/Source/Animation/AzEntityNode.cpp    |  4 +-
 .../Code/Source/Animation/AzEntityNode.h      |  6 +--
 .../Source/Animation/CompoundSplineTrack.h    |  2 +-
 .../Source/Animation/UiAnimationSystem.cpp    | 18 ++++----
 Gems/LyShine/Code/Source/LyShine.cpp          | 10 ++---
 Gems/LyShine/Code/Source/LyShine.h            | 10 ++---
 Gems/LyShine/Code/Source/LyShineDebug.cpp     |  4 +-
 .../LyShine/Code/Source/LyShineLoadScreen.cpp |  6 +--
 .../Platform/Windows/UiClipboard_Windows.cpp  |  6 ++-
 Gems/LyShine/Code/Source/Sprite.cpp           | 18 ++++----
 Gems/LyShine/Code/Source/Sprite.h             | 16 +++----
 Gems/LyShine/Code/Source/StringUtfUtils.h     | 25 +++++------
 .../Tests/internal/test_UiTextComponent.cpp   |  2 +-
 Gems/LyShine/Code/Source/TextMarkup.cpp       |  3 +-
 .../LyShine/Code/Source/UiCanvasComponent.cpp | 12 ++---
 Gems/LyShine/Code/Source/UiCanvasComponent.h  |  6 +--
 Gems/LyShine/Code/Source/UiCanvasManager.cpp  | 16 +++----
 Gems/LyShine/Code/Source/UiCanvasManager.h    |  2 +-
 .../Code/Source/UiDropdownComponent.cpp       |  3 +-
 .../Code/Source/UiInteractableState.cpp       |  2 +-
 Gems/LyShine/Code/Source/UiTextComponent.cpp  | 44 +++++++++++--------
 .../Source/UiTextComponentOffsetsSelector.cpp |  2 +-
 .../Code/Source/UiTextInputComponent.cpp      |  5 ++-
 41 files changed, 161 insertions(+), 155 deletions(-)

diff --git a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp
index 39e5bd0f5f..746ea04559 100644
--- a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.cpp
@@ -135,7 +135,7 @@ private:
         std::vector keySelectionFlags;
         _smart_ptr undo;
         _smart_ptr redo;
-        string id;
+        AZStd::string id;
         ISplineInterpolator* pSpline;
     };
 
diff --git a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.h b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.h
index 18ee7e173c..2a7b0c3d1f 100644
--- a/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.h
+++ b/Gems/LyShine/Code/Editor/Animation/Controls/UiSplineCtrlEx.h
@@ -45,8 +45,8 @@ class QRubberBand;
 class ISplineSet
 {
 public:
-    virtual ISplineInterpolator* GetSplineFromID(const string& id) = 0;
-    virtual string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
+    virtual ISplineInterpolator* GetSplineFromID(const AZStd::string& id) = 0;
+    virtual AZStd::string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
     virtual int GetSplineCount() const = 0;
     virtual int GetKeyCountAtTime(float time, float threshold) const = 0;
 };
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp
index f860725276..8880795466 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp
@@ -1100,7 +1100,7 @@ bool CUiAnimViewAnimNode::SetName(const char* pName)
         }
     }
 
-    string oldName = GetName();
+    AZStd::string oldName = GetName();
     m_pAnimNode->SetName(pName);
 
     if (UiAnimUndo::IsRecording())
@@ -1108,7 +1108,7 @@ bool CUiAnimViewAnimNode::SetName(const char* pName)
         UiAnimUndo::Record(new CUndoAnimNodeRename(this, oldName));
     }
 
-    GetSequence()->OnNodeRenamed(this, oldName);
+    GetSequence()->OnNodeRenamed(this, oldName.c_str());
 
     return true;
 }
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp
index 61d6b66b29..ac210ba2f2 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp
@@ -992,7 +992,7 @@ void CUiAnimViewDialog::ReloadSequencesComboBox()
         for (int k = 0; k < numSequences; ++k)
         {
             CUiAnimViewSequence* pSequence = pSequenceManager->GetSequenceByIndex(k);
-            QString fullname = QtUtil::ToQString(pSequence->GetName());
+            QString fullname = pSequence->GetName();
             m_sequencesComboBox->addItem(fullname);
         }
     }
@@ -1132,7 +1132,7 @@ void CUiAnimViewDialog::OnSequenceChanged(CUiAnimViewSequence* pSequence)
 
     if (pSequence)
     {
-        m_currentSequenceName = QtUtil::ToQString(pSequence->GetName());
+        m_currentSequenceName = pSequence->GetName();
 
         pSequence->Reset(true);
         SaveZoomScrollSettings();
@@ -1733,7 +1733,7 @@ void CUiAnimViewDialog::OnNodeRenamed(CUiAnimViewNode* pNode, const char* pOldNa
     {
         if (m_currentSequenceName == QString(pOldName))
         {
-            m_currentSequenceName = QtUtil::ToQString(pNode->GetName());
+            m_currentSequenceName = pNode->GetName();
         }
 
         ReloadSequencesComboBox();
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewFindDlg.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewFindDlg.cpp
index 86f1f786d0..511866db43 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewFindDlg.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewFindDlg.cpp
@@ -13,7 +13,6 @@
 #include "UiAnimViewSequenceManager.h"
 
 #include 
-#include 
 #include 
 
 #include 
@@ -64,7 +63,7 @@ void CUiAnimViewFindDlg::FillData()
             ObjName obj;
             obj.m_objName = pNode->GetName();
             obj.m_directorName = pNode->HasDirectorAsParent() ? pNode->HasDirectorAsParent()->GetName() : "";
-            string fullname = seq->GetName();
+            AZStd::string fullname = seq->GetName();
             obj.m_seqName = fullname.c_str();
             m_objs.push_back(obj);
         }
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp
index 7c4882e7f0..ac824bfc4d 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp
@@ -46,7 +46,7 @@ void CUiAVNewSequenceDialog::OnOK()
     for (int k = 0; k < CUiAnimViewSequenceManager::GetSequenceManager()->GetCount(); ++k)
     {
         CUiAnimViewSequence* pSequence = CUiAnimViewSequenceManager::GetSequenceManager()->GetSequenceByIndex(k);
-        QString fullname = QtUtil::ToQString(pSequence->GetName());
+        QString fullname = pSequence->GetName();
 
         if (fullname.compare(m_sequenceName, Qt::CaseInsensitive) == 0)
         {
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
index 9cca6cdf8d..67fd542c3f 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
@@ -486,7 +486,7 @@ CUiAnimViewNodesCtrl::CRecord* CUiAnimViewNodesCtrl::AddAnimNodeRecord(CRecord*
 {
     CRecord* pNewRecord = new CRecord(pAnimNode);
 
-    pNewRecord->setText(0, QtUtil::ToQString(pAnimNode->GetName()));
+    pNewRecord->setText(0, pAnimNode->GetName());
     UpdateUiAnimNodeRecord(pNewRecord, pAnimNode);
     pParentRecord->insertChild(GetInsertPosition(pParentRecord, pAnimNode), pNewRecord);
     FillNodesRec(pNewRecord, pAnimNode);
@@ -499,7 +499,7 @@ CUiAnimViewNodesCtrl::CRecord* CUiAnimViewNodesCtrl::AddTrackRecord(CRecord* pPa
 {
     CRecord* pNewTrackRecord = new CRecord(pTrack);
     pNewTrackRecord->setSizeHint(0, QSize(30, 18));
-    pNewTrackRecord->setText(0, QtUtil::ToQString(pTrack->GetName()));
+    pNewTrackRecord->setText(0, pTrack->GetName());
     UpdateTrackRecord(pNewTrackRecord, pTrack);
     pParentRecord->insertChild(GetInsertPosition(pParentRecord, pTrack), pNewTrackRecord);
     FillNodesRec(pNewTrackRecord, pTrack);
@@ -708,7 +708,7 @@ void CUiAnimViewNodesCtrl::OnFillItems()
         m_nodeToRecordMap.clear();
 
         CRecord* pRootGroupRec = new CRecord(pSequence);
-        pRootGroupRec->setText(0, QtUtil::ToQString(pSequence->GetName()));
+        pRootGroupRec->setText(0, pSequence->GetName());
         QFont f = font();
         f.setBold(true);
         pRootGroupRec->setData(0, Qt::FontRole, f);
@@ -1323,7 +1323,7 @@ int CUiAnimViewNodesCtrl::ShowPopupMenuSingleSelection(UiAnimContextMenu& contex
                     continue;
                 }
 
-                QAction* a = contextMenu.main.addAction(QString("  %1").arg(QtUtil::ToQString(pTrack2->GetName())));
+                QAction* a = contextMenu.main.addAction(QString("  %1").arg(pTrack2->GetName()));
                 a->setData(eMI_ShowHideBase + childIndex);
                 a->setCheckable(true);
                 a->setChecked(!pTrack2->IsHidden());
@@ -1459,7 +1459,7 @@ void CUiAnimViewNodesCtrl::FillAutoCompletionListForFilter()
 
         for (unsigned int i = 0; i < animNodeCount; ++i)
         {
-            strings << QtUtil::ToQString(animNodes.GetNode(i)->GetName());
+            strings << QString(animNodes.GetNode(i)->GetName());
         }
     }
     else
@@ -1512,7 +1512,7 @@ int CUiAnimViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, con
     if (const char* pCh = strstr(nodeName, ".["))
     {
         char matPath[MAX_PATH];
-        azstrcpy(matPath, nodeName, (size_t)(pCh - nodeName));
+        azstrncpy(matPath, nodeName, (size_t)(pCh - nodeName));
         matName = matPath;
         pCh += 2;
         if ((*pCh) != 0)
@@ -1763,7 +1763,7 @@ void CUiAnimViewNodesCtrl::OnNodeRenamed(CUiAnimViewNode* pNode, [[maybe_unused]
     if (!m_bIgnoreNotifications)
     {
         CRecord* pNodeRecord = GetNodeRecord(pNode);
-        pNodeRecord->setText(0, QtUtil::ToQString(pNode->GetName()));
+        pNodeRecord->setText(0, pNode->GetName());
 
         update();
     }
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
index 7f7f8f7aaf..cdafd8a4ce 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
@@ -683,7 +683,7 @@ bool CUiAnimViewSequence::SetName(const char* pName)
         return false;
     }
 
-    string oldName = GetName();
+    AZStd::string oldName = GetName();
     m_pAnimSequence->SetName(pName);
 
     if (UiAnimUndo::IsRecording())
@@ -691,7 +691,7 @@ bool CUiAnimViewSequence::SetName(const char* pName)
         UiAnimUndo::Record(new CUndoAnimNodeRename(this, oldName));
     }
 
-    GetSequence()->OnNodeRenamed(this, oldName);
+    GetSequence()->OnNodeRenamed(this, oldName.c_str());
 
     return true;
 }
@@ -893,7 +893,7 @@ std::deque CUiAnimViewSequence::GetMatchingTracks(CUiAnimView
 {
     std::deque matchingTracks;
 
-    const string trackName = trackNode->getAttr("name");
+    const AZStd::string trackName = trackNode->getAttr("name");
 
     IUiAnimationSystem* animationSystem = nullptr;
     EBUS_EVENT_RESULT(animationSystem, UiEditorAnimationBus, GetAnimationSystem);
@@ -956,11 +956,11 @@ void CUiAnimViewSequence::GetMatchedPasteLocationsRec(std::vectorgetChild(nodeIndex);
-        const string tagName = xmlChildNode->getTag();
+        const AZStd::string tagName = xmlChildNode->getTag();
 
         if (tagName == "Node")
         {
-            const string nodeName = xmlChildNode->getAttr("name");
+            const AZStd::string nodeName = xmlChildNode->getAttr("name");
 
             int nodeType = eUiAnimNodeType_Invalid;
             xmlChildNode->getAttr("type", nodeType);
@@ -982,7 +982,7 @@ void CUiAnimViewSequence::GetMatchedPasteLocationsRec(std::vectorgetAttr("name");
+            const AZStd::string trackName = xmlChildNode->getAttr("name");
 
             IUiAnimationSystem* animationSystem = nullptr;
             EBUS_EVENT_RESULT(animationSystem, UiEditorAnimationBus, GetAnimationSystem);
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.cpp
index 8ab6f2e58c..cd4bf5b1ac 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.cpp
@@ -546,7 +546,7 @@ void CUndoAnimNodeReparent::AddParentsInChildren(CUiAnimViewAnimNode* pCurrentNo
 }
 
 //////////////////////////////////////////////////////////////////////////
-CUndoAnimNodeRename::CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const string& oldName)
+CUndoAnimNodeRename::CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const AZStd::string& oldName)
     : m_pNode(pNode)
     , m_newName(pNode->GetName())
     , m_oldName(oldName)
@@ -556,13 +556,13 @@ CUndoAnimNodeRename::CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const strin
 //////////////////////////////////////////////////////////////////////////
 void CUndoAnimNodeRename::Undo([[maybe_unused]] bool bUndo)
 {
-    m_pNode->SetName(m_oldName);
+    m_pNode->SetName(m_oldName.c_str());
 }
 
 //////////////////////////////////////////////////////////////////////////
 void CUndoAnimNodeRename::Redo()
 {
-    m_pNode->SetName(m_newName);
+    m_pNode->SetName(m_newName.c_str());
 }
 
 //////////////////////////////////////////////////////////////////////////
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.h b/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.h
index d79336cedd..923420c653 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.h
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewUndo.h
@@ -304,7 +304,7 @@ class CUndoAnimNodeRename
     : public UiAnimUndoObject
 {
 public:
-    CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const string& oldName);
+    CUndoAnimNodeRename(CUiAnimViewAnimNode* pNode, const AZStd::string& oldName);
 
 protected:
     virtual int GetSize() override { return sizeof(*this); };
@@ -315,8 +315,8 @@ protected:
 
 private:
     CUiAnimViewAnimNode* m_pNode;
-    string m_newName;
-    string m_oldName;
+    AZStd::string m_newName;
+    AZStd::string m_oldName;
 };
 
 /** Base class for track event transactions
diff --git a/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp b/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp
index caff5d2da0..206da8cb3a 100644
--- a/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp
+++ b/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp
@@ -75,7 +75,7 @@ void AssetTreeEntry::Insert(const AZStd::string& path, const AZStd::string& menu
         AZStd::string folderName;
         AZStd::string remainderPath;
         size_t separator = path.find('/');
-        if (separator == string::npos)
+        if (separator == AZStd::string::npos)
         {
             folderName = path;
         }
diff --git a/Gems/LyShine/Code/Editor/EditorMenu.cpp b/Gems/LyShine/Code/Editor/EditorMenu.cpp
index 97db065a4d..840bd206ab 100644
--- a/Gems/LyShine/Code/Editor/EditorMenu.cpp
+++ b/Gems/LyShine/Code/Editor/EditorMenu.cpp
@@ -724,7 +724,7 @@ void EditorWindow::AddMenu_View_LanguageSetting(QMenu* viewMenu)
     // Iterate through the subdirectories of the localization folder. Each
     // directory corresponds to a different language containing localization
     // translations for that language.
-    string fullLocPath(string(gEnv->pFileIO->GetAlias("@assets@")) + "/" + string(m_startupLocFolderName.toUtf8().constData()));
+    AZStd::string fullLocPath(AZStd::string(gEnv->pFileIO->GetAlias("@assets@")) + "/" + AZStd::string(m_startupLocFolderName.toUtf8().constData()));
     QDir locDir(fullLocPath.c_str());
     locDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
     locDir.setSorting(QDir::Name);
diff --git a/Gems/LyShine/Code/Editor/PropertiesContainer.cpp b/Gems/LyShine/Code/Editor/PropertiesContainer.cpp
index 36a78fe684..21b3b99b02 100644
--- a/Gems/LyShine/Code/Editor/PropertiesContainer.cpp
+++ b/Gems/LyShine/Code/Editor/PropertiesContainer.cpp
@@ -788,7 +788,7 @@ void PropertiesContainer::Update()
     }
     else // more than one entity selected
     {
-        displayName = ToString(selectedEntitiesAmount) + " elements selected";
+        displayName = (ToString(selectedEntitiesAmount) + " elements selected").c_str();
     }
 
     // Update the selected element display name
diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
index ac55cd38e9..b3cacec065 100644
--- a/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
+++ b/Gems/LyShine/Code/Editor/PropertyHandlerChar.cpp
@@ -9,6 +9,8 @@
 
 #include "PropertyHandlerChar.h"
 
+#include 
+
 QWidget* PropertyHandlerChar::CreateGUI(QWidget* pParent)
 {
     AzToolsFramework::PropertyStringLineEditCtrl* ctrl = aznew AzToolsFramework::PropertyStringLineEditCtrl(pParent);
@@ -29,12 +31,8 @@ void PropertyHandlerChar::WriteGUIValuesIntoProperty(size_t index, AzToolsFramew
 {
     (int)index;
     AZStd::string str = GUI->value();
-    uint32_t character = '\0';
-    if (!str.empty())
-    {
-        Unicode::CIterator pChar(str.c_str());
-        character = *pChar;
-    }
+    wchar_t character = '\0';
+    AZStd::to_wstring(&character, 1, str.c_str());
     instance = character;
 }
 
@@ -47,7 +45,8 @@ bool PropertyHandlerChar::ReadValuesIntoGUI(size_t index, AzToolsFramework::Prop
         // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
         // work for cases tested but may not in general.
         wchar_t wcharString[2] = { static_cast(instance), 0 };
-        AZStd::string val(CryStringUtils::WStrToUTF8(wcharString));
+        AZStd::string val;
+        AZStd::to_string(val, wcharString);
         GUI->setValue(val);
     }
     GUI->blockSignals(false);
diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp
index ab51c3a29d..1f3e28b077 100644
--- a/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp
+++ b/Gems/LyShine/Code/Editor/PropertyHandlerDirectory.cpp
@@ -93,7 +93,7 @@ AzToolsFramework::AssetBrowser::AssetSelectionModel PropertyAssetDirectorySelect
 
 void PropertyAssetDirectorySelectionCtrl::SetFolderSelection(const AZStd::string& folderPath)
 {
-    string strFolderPath = folderPath.c_str();
+    AZStd::string strFolderPath = folderPath.c_str();
     if (strFolderPath.empty())
     {
         m_folderPath.clear();
@@ -106,12 +106,14 @@ void PropertyAssetDirectorySelectionCtrl::SetFolderSelection(const AZStd::string
         // the project folder, which we need to omit since file IO routines
         // seem to assume this anyways.
         strFolderPath = strFolderPath.substr(strFolderPath.find('/') + 1);
-        m_folderPath = PathUtil::MakeGamePath(strFolderPath).MakeLower();
+        m_folderPath = PathUtil::MakeGamePath(strFolderPath);
+        AZStd::to_lower(m_folderPath.begin(), m_folderPath.end());
     }
     // For paths in gems, absolute paths are returned
     else
     {
-        m_folderPath = Path::FullPathToGamePath(strFolderPath.c_str()).MakeLower();
+        m_folderPath = Path::FullPathToGamePath(strFolderPath.c_str());
+        AZStd::to_lower(m_folderPath.begin(), m_folderPath.end());
     }
 }
 
diff --git a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
index 2bb1686a93..d833c93af8 100644
--- a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
+++ b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
@@ -921,7 +921,7 @@ void SpriteBorderEditor::AddButtonsSection(QGridLayout* gridLayout, int& rowNum)
                 // The texture is guaranteed to exist so use that to get the full path.
                 QString fullTexturePath = Path::GamePathToFullPath(m_sprite->GetTexturePathname().c_str());
                 const char* const spriteExtension = "sprite";
-                string fullSpritePath = PathUtil::ReplaceExtension(fullTexturePath.toUtf8().data(), spriteExtension);
+                AZStd::string fullSpritePath = PathUtil::ReplaceExtension(fullTexturePath.toUtf8().data(), spriteExtension);
 
                 FileHelpers::SourceControlAddOrEdit(fullSpritePath.c_str(), QApplication::activeWindow());
 
diff --git a/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp b/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
index f1ecb4af9e..43a80d5002 100644
--- a/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
+++ b/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
@@ -80,10 +80,10 @@ void CUiAnimSequence::SetName(const char* name)
         return;   // should never happen, null pointer guard
     }
 
-    string originalName = GetName();
+    AZStd::string originalName = GetName();
 
     m_name = name;
-    m_pUiAnimationSystem->OnSequenceRenamed(originalName, m_name.c_str());
+    m_pUiAnimationSystem->OnSequenceRenamed(originalName.c_str(), m_name.c_str());
 
     if (GetOwner())
     {
diff --git a/Gems/LyShine/Code/Source/Animation/AnimSequence.h b/Gems/LyShine/Code/Source/Animation/AnimSequence.h
index efbe886ce2..e4026ce250 100644
--- a/Gems/LyShine/Code/Source/Animation/AnimSequence.h
+++ b/Gems/LyShine/Code/Source/Animation/AnimSequence.h
@@ -146,7 +146,7 @@ private:
 
     uint32 m_id;
     AZStd::string m_name;
-    mutable string m_fullNameHolder;
+    mutable AZStd::string m_fullNameHolder;
     Range m_timeRange;
     UiTrackEvents m_events;
 
diff --git a/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp b/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp
index ca435dadf9..32dfb97a58 100644
--- a/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp
+++ b/Gems/LyShine/Code/Source/Animation/AzEntityNode.cpp
@@ -278,8 +278,8 @@ const AZ::SerializeContext::ClassElement* CUiAnimAzEntityNode::ComputeOffsetFrom
 
         if (mismatch)
         {
-            string warnMsg = "Data mismatch reading animation data for type ";
-            warnMsg += classData->m_typeId.ToString();
+            AZStd::string warnMsg = "Data mismatch reading animation data for type ";
+            warnMsg += classData->m_typeId.ToString();
             warnMsg += ". The field \"";
             warnMsg += paramData.GetName();
             if (!element)
diff --git a/Gems/LyShine/Code/Source/Animation/AzEntityNode.h b/Gems/LyShine/Code/Source/Animation/AzEntityNode.h
index 6ca26ef84a..56680f1094 100644
--- a/Gems/LyShine/Code/Source/Animation/AzEntityNode.h
+++ b/Gems/LyShine/Code/Source/Animation/AzEntityNode.h
@@ -170,14 +170,14 @@ private:
 
     struct SScriptPropertyParamInfo
     {
-        string variableName;
-        string displayName;
+        AZStd::string variableName;
+        AZStd::string displayName;
         bool isVectorTable;
         SParamInfo animNodeParamInfo;
     };
 
     std::vector< SScriptPropertyParamInfo > m_entityScriptPropertiesParamInfos;
-    typedef AZStd::unordered_map< string, size_t, stl::hash_string_caseless, stl::equality_string_caseless > TScriptPropertyParamInfoMap;
+    typedef AZStd::unordered_map, stl::equality_string_caseless > TScriptPropertyParamInfoMap;
     TScriptPropertyParamInfoMap m_nameToScriptPropertyParamInfo;
     #ifdef CHECK_FOR_TOO_MANY_ONPROPERTY_SCRIPT_CALLS
     uint32 m_OnPropertyCalls;
diff --git a/Gems/LyShine/Code/Source/Animation/CompoundSplineTrack.h b/Gems/LyShine/Code/Source/Animation/CompoundSplineTrack.h
index b707d0bc77..3ae230d4e4 100644
--- a/Gems/LyShine/Code/Source/Animation/CompoundSplineTrack.h
+++ b/Gems/LyShine/Code/Source/Animation/CompoundSplineTrack.h
@@ -112,7 +112,7 @@ public:
 
     virtual int NextKeyByTime(int key) const;
 
-    void SetSubTrackName(const int i, const string& name) { assert (i < MAX_SUBTRACKS); m_subTrackNames[i] = name; }
+    void SetSubTrackName(const int i, const AZStd::string& name) { assert (i < MAX_SUBTRACKS); m_subTrackNames[i] = name; }
 
 #ifdef UI_ANIMATION_SYSTEM_SUPPORT_EDITING
     virtual ColorB GetCustomColor() const
diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
index 5c897620c7..1ea35006e2 100644
--- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
+++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
@@ -27,19 +27,19 @@
 // Serialization for anim nodes & param types
 #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(eUiAnimNodeType_ ## name) == g_animNodeEnumToStringMap.end()); \
     g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = STRINGIFY(name);                                                            \
-    g_animNodeStringToEnumMap[string(STRINGIFY(name))] = eUiAnimNodeType_ ## name;
+    g_animNodeStringToEnumMap[AZStd::string(STRINGIFY(name))] = eUiAnimNodeType_ ## name;
 
 #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(eUiAnimParamType_ ## name) == g_animParamEnumToStringMap.end()); \
     g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = STRINGIFY(name);                                                              \
-    g_animParamStringToEnumMap[string(STRINGIFY(name))] = eUiAnimParamType_ ## name;
+    g_animParamStringToEnumMap[AZStd::string(STRINGIFY(name))] = eUiAnimParamType_ ## name;
 
 namespace
 {
-    AZStd::unordered_map g_animNodeEnumToStringMap;
-    StaticInstance >> g_animNodeStringToEnumMap;
+    AZStd::unordered_map g_animNodeEnumToStringMap;
+    StaticInstance >> g_animNodeStringToEnumMap;
 
-    AZStd::unordered_map g_animParamEnumToStringMap;
-    StaticInstance >> g_animParamStringToEnumMap;
+    AZStd::unordered_map g_animParamEnumToStringMap;
+    StaticInstance >> g_animParamStringToEnumMap;
 
     // If you get an assert in this function, it means two node types have the same enum value.
     void RegisterNodeTypes()
@@ -1189,7 +1189,7 @@ void UiAnimationSystem::SerializeNodeType(EUiAnimNodeType& animNodeType, XmlNode
     {
         const char* pTypeString = "Invalid";
         assert(g_animNodeEnumToStringMap.find(animNodeType) != g_animNodeEnumToStringMap.end());
-        pTypeString = g_animNodeEnumToStringMap[animNodeType];
+        pTypeString = g_animNodeEnumToStringMap[animNodeType].c_str();
         xmlNode->setAttr(kType, pTypeString);
     }
 }
@@ -1273,7 +1273,7 @@ void UiAnimationSystem::SerializeParamType(CUiAnimParamType& animParamType, XmlN
         else
         {
             assert(g_animParamEnumToStringMap.find(animParamType.m_type) != g_animParamEnumToStringMap.end());
-            pTypeString = g_animParamEnumToStringMap[animParamType.m_type];
+            pTypeString = g_animParamEnumToStringMap[animParamType.m_type].c_str();
         }
 
         xmlNode->setAttr(kParamType, pTypeString);
@@ -1341,7 +1341,7 @@ const char* UiAnimationSystem::GetParamTypeName(const CUiAnimParamType& animPara
     {
         if (g_animParamEnumToStringMap.find(animParamType.m_type) != g_animParamEnumToStringMap.end())
         {
-            return g_animParamEnumToStringMap[animParamType.m_type];
+            return g_animParamEnumToStringMap[animParamType.m_type].c_str();
         }
     }
 
diff --git a/Gems/LyShine/Code/Source/LyShine.cpp b/Gems/LyShine/Code/Source/LyShine.cpp
index f5edc4d7f1..4e265bd973 100644
--- a/Gems/LyShine/Code/Source/LyShine.cpp
+++ b/Gems/LyShine/Code/Source/LyShine.cpp
@@ -287,7 +287,7 @@ AZ::EntityId CLyShine::CreateCanvas()
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::EntityId CLyShine::LoadCanvas(const string& assetIdPathname)
+AZ::EntityId CLyShine::LoadCanvas(const AZStd::string& assetIdPathname)
 {
     return m_uiCanvasManager->LoadCanvas(assetIdPathname.c_str());
 }
@@ -299,7 +299,7 @@ AZ::EntityId CLyShine::CreateCanvasInEditor(UiEntityContext* entityContext)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::EntityId CLyShine::LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext)
+AZ::EntityId CLyShine::LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext)
 {
     return m_uiCanvasManager->LoadCanvasInEditor(assetIdPathname, sourceAssetPathname, entityContext);
 }
@@ -317,7 +317,7 @@ AZ::EntityId CLyShine::FindCanvasById(LyShine::CanvasId id)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::EntityId CLyShine::FindLoadedCanvasByPathName(const string& assetIdPathname)
+AZ::EntityId CLyShine::FindLoadedCanvasByPathName(const AZStd::string& assetIdPathname)
 {
     return m_uiCanvasManager->FindLoadedCanvasByPathName(assetIdPathname.c_str());
 }
@@ -335,13 +335,13 @@ void CLyShine::ReleaseCanvasDeferred(AZ::EntityId canvas)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-ISprite* CLyShine::LoadSprite(const string& pathname)
+ISprite* CLyShine::LoadSprite(const AZStd::string& pathname)
 {
     return CSprite::LoadSprite(pathname);
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-ISprite* CLyShine::CreateSprite(const string& renderTargetName)
+ISprite* CLyShine::CreateSprite(const AZStd::string& renderTargetName)
 {
     return CSprite::CreateSprite(renderTargetName);
 }
diff --git a/Gems/LyShine/Code/Source/LyShine.h b/Gems/LyShine/Code/Source/LyShine.h
index a7a8cab700..cb5b77a861 100644
--- a/Gems/LyShine/Code/Source/LyShine.h
+++ b/Gems/LyShine/Code/Source/LyShine.h
@@ -56,18 +56,18 @@ public:
     IDraw2d* GetDraw2d() override;
 
     AZ::EntityId CreateCanvas() override;
-    AZ::EntityId LoadCanvas(const string& assetIdPathname) override;
+    AZ::EntityId LoadCanvas(const AZStd::string& assetIdPathname) override;
     AZ::EntityId CreateCanvasInEditor(UiEntityContext* entityContext) override;
-    AZ::EntityId LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext) override;
+    AZ::EntityId LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext) override;
     AZ::EntityId ReloadCanvasFromXml(const AZStd::string& xmlString, UiEntityContext* entityContext) override;
     AZ::EntityId FindCanvasById(LyShine::CanvasId id) override;
-    AZ::EntityId FindLoadedCanvasByPathName(const string& assetIdPathname) override;
+    AZ::EntityId FindLoadedCanvasByPathName(const AZStd::string& assetIdPathname) override;
 
     void ReleaseCanvas(AZ::EntityId canvas, bool forEditor) override;
     void ReleaseCanvasDeferred(AZ::EntityId canvas) override;
 
-    ISprite* LoadSprite(const string& pathname) override;
-    ISprite* CreateSprite(const string& renderTargetName) override;
+    ISprite* LoadSprite(const AZStd::string& pathname) override;
+    ISprite* CreateSprite(const AZStd::string& renderTargetName) override;
     bool DoesSpriteTextureAssetExist(const AZStd::string& pathname) override;
 
     void PostInit() override;
diff --git a/Gems/LyShine/Code/Source/LyShineDebug.cpp b/Gems/LyShine/Code/Source/LyShineDebug.cpp
index c7ffea1aec..c7dccc162f 100644
--- a/Gems/LyShine/Code/Source/LyShineDebug.cpp
+++ b/Gems/LyShine/Code/Source/LyShineDebug.cpp
@@ -995,7 +995,7 @@ static AZ::Entity* CreateButton(const char* name, bool atRoot, AZ::EntityId pare
         EBUS_EVENT_ID(buttonId, UiInteractableStatesBus, SetStateColor, UiInteractableStatesInterface::StatePressed, buttonId, pressedColor);
         EBUS_EVENT_ID(buttonId, UiInteractableStatesBus, SetStateAlpha, UiInteractableStatesInterface::StatePressed, buttonId, pressedColor.GetA());
 
-        string pathname = "Textures/Basic/Button_Sliced_Normal.sprite";
+        AZStd::string pathname = "Textures/Basic/Button_Sliced_Normal.sprite";
         ISprite* sprite = gEnv->pLyShine->LoadSprite(pathname);
 
         EBUS_EVENT_ID(buttonId, UiImageBus, SetSprite, sprite);
@@ -1094,7 +1094,7 @@ static AZ::Entity* CreateTextInput(const char* name, bool atRoot, AZ::EntityId p
         EBUS_EVENT_ID(textInputId, UiInteractableStatesBus, SetStateColor, UiInteractableStatesInterface::StatePressed, textInputId, pressedColor);
         EBUS_EVENT_ID(textInputId, UiInteractableStatesBus, SetStateAlpha, UiInteractableStatesInterface::StatePressed, textInputId, pressedColor.GetA());
 
-        string pathname = "Textures/Basic/Button_Sliced_Normal.sprite";
+        AZStd::string pathname = "Textures/Basic/Button_Sliced_Normal.sprite";
         ISprite* sprite = gEnv->pLyShine->LoadSprite(pathname);
 
         EBUS_EVENT_ID(textInputId, UiImageBus, SetSprite, sprite);
diff --git a/Gems/LyShine/Code/Source/LyShineLoadScreen.cpp b/Gems/LyShine/Code/Source/LyShineLoadScreen.cpp
index 9d4f0bcc3c..64a577efa2 100644
--- a/Gems/LyShine/Code/Source/LyShineLoadScreen.cpp
+++ b/Gems/LyShine/Code/Source/LyShineLoadScreen.cpp
@@ -215,7 +215,7 @@ namespace LyShine
     AZ::EntityId LyShineLoadScreenComponent::loadFromCfg(const char* pathVarName, const char* autoPlayVarName)
     {
         ICVar* pathVar = gEnv->pConsole->GetCVar(pathVarName);
-        string path = pathVar ? pathVar->GetString() : "";
+        AZStd::string path = pathVar ? pathVar->GetString() : "";
         if (path.empty())
         {
             // No canvas specified.
@@ -238,7 +238,7 @@ namespace LyShine
         EBUS_EVENT_ID(canvasId, UiCanvasBus, SetDrawOrder, std::numeric_limits::max());
 
         ICVar* autoPlayVar = gEnv->pConsole->GetCVar(autoPlayVarName);
-        string sequence = autoPlayVar ? autoPlayVar->GetString() : "";
+        AZStd::string sequence = autoPlayVar ? autoPlayVar->GetString() : "";
         if (sequence.empty())
         {
             // Nothing to auto-play.
@@ -253,7 +253,7 @@ namespace LyShine
             return canvasId;
         }
 
-        animSystem->PlaySequence(sequence, nullptr, false, false);
+        animSystem->PlaySequence(sequence.c_str(), nullptr, false, false);
 
         return canvasId;
     }
diff --git a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
index 7bcdc26712..ae118aee00 100644
--- a/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
+++ b/Gems/LyShine/Code/Source/Platform/Windows/UiClipboard_Windows.cpp
@@ -9,6 +9,7 @@
 
 #include "UiClipboard.h"
 #include 
+#include 
 
 bool UiClipboard::SetText(const AZStd::string& text)
 {
@@ -19,7 +20,8 @@ bool UiClipboard::SetText(const AZStd::string& text)
         {
             if (text.length() > 0)
             {
-                auto wstr = CryStringUtils::UTF8ToWStr(text.c_str());
+                AZStd::wstring wstr;
+                AZStd::to_wstring(wstr, text.c_str());
                 const SIZE_T buffSize = (wstr.size() + 1) * sizeof(WCHAR);
                 if (HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, buffSize))
                 {
@@ -45,7 +47,7 @@ AZStd::string UiClipboard::GetText()
         if (HANDLE hText = GetClipboardData(CF_UNICODETEXT))
         {
             const WCHAR* text = static_cast(GlobalLock(hText));
-            outText = CryStringUtils::WStrToUTF8(text);
+            AZStd::to_string(outText, text);
             GlobalUnlock(hText);
         }
         CloseClipboard();
diff --git a/Gems/LyShine/Code/Source/Sprite.cpp b/Gems/LyShine/Code/Source/Sprite.cpp
index 134768f814..0e0edb8e34 100644
--- a/Gems/LyShine/Code/Source/Sprite.cpp
+++ b/Gems/LyShine/Code/Source/Sprite.cpp
@@ -146,9 +146,9 @@ namespace
     {
         if (ser.IsReading())
         {
-            string stringVal;
+            AZStd::string stringVal;
             ser.Value(attributeName, stringVal);
-            stringVal.replace(',', ' ');
+            AZ::StringFunc::Replace(stringVal, ',', ' ');
             char* pEnd = nullptr;
             float uVal = strtof(stringVal.c_str(), &pEnd);
             float vVal = strtof(pEnd, nullptr);
@@ -202,13 +202,13 @@ CSprite::~CSprite()
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-const string& CSprite::GetPathname() const
+const AZStd::string& CSprite::GetPathname() const
 {
     return m_pathname;
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-const string& CSprite::GetTexturePathname() const
+const AZStd::string& CSprite::GetTexturePathname() const
 {
     return m_texturePathname;
 }
@@ -283,7 +283,7 @@ void CSprite::Serialize(TSerialize ser)
                 m_spriteSheetCells.push_back(SpriteSheetCell());
             }
 
-            string aliasTemp;
+            AZStd::string aliasTemp;
             if (ser.IsReading())
             {
                 ser.Value("alias", aliasTemp);
@@ -318,7 +318,7 @@ void CSprite::Serialize(TSerialize ser)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-bool CSprite::SaveToXml(const string& pathname)
+bool CSprite::SaveToXml(const AZStd::string& pathname)
 {
     // NOTE: The input pathname has to be a path that can used to save - so not an Asset ID
     // because of this we do not store the pathname
@@ -331,7 +331,7 @@ bool CSprite::SaveToXml(const string& pathname)
     ser.Value(spriteVersionNumberTag, spriteFileVersionNumber);
     Serialize(ser);
 
-    return root->saveToFile(pathname);
+    return root->saveToFile(pathname.c_str());
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -629,7 +629,7 @@ void CSprite::Shutdown()
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-CSprite* CSprite::LoadSprite(const string& pathname)
+CSprite* CSprite::LoadSprite(const AZStd::string& pathname)
 {
     AZStd::string spritePath;
     AZStd::string texturePath;
@@ -691,7 +691,7 @@ CSprite* CSprite::LoadSprite(const string& pathname)
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-CSprite* CSprite::CreateSprite(const string& renderTargetName)
+CSprite* CSprite::CreateSprite(const AZStd::string& renderTargetName)
 {
     // test if the sprite is already loaded, if so return loaded sprite
     auto result = s_loadedSprites->find(renderTargetName);
diff --git a/Gems/LyShine/Code/Source/Sprite.h b/Gems/LyShine/Code/Source/Sprite.h
index e7e353a77b..8a645b78b1 100644
--- a/Gems/LyShine/Code/Source/Sprite.h
+++ b/Gems/LyShine/Code/Source/Sprite.h
@@ -32,13 +32,13 @@ public: // member functions
 
     ~CSprite() override;
 
-    const string& GetPathname() const override;
-    const string& GetTexturePathname() const override;
+    const AZStd::string& GetPathname() const override;
+    const AZStd::string& GetTexturePathname() const override;
     Borders GetBorders() const override;
     void SetBorders(Borders borders) override;
     void SetCellBorders(int cellIndex, Borders borders) override;
     void Serialize(TSerialize ser) override;
-    bool SaveToXml(const string& pathname) override;
+    bool SaveToXml(const AZStd::string& pathname) override;
     bool AreBordersZeroWidth() const override;
     bool AreCellBordersZeroWidth(int index) const override;
     AZ::Vector2 GetSize() override;
@@ -72,8 +72,8 @@ public: // static member functions
 
     static void Initialize();
     static void Shutdown();
-    static CSprite* LoadSprite(const string& pathname);
-    static CSprite* CreateSprite(const string& renderTargetName);
+    static CSprite* LoadSprite(const AZStd::string& pathname);
+    static CSprite* CreateSprite(const AZStd::string& renderTargetName);
     static bool DoesSpriteTextureAssetExist(const AZStd::string& pathname);
 
     //! Replaces baseSprite with newSprite with proper ref-count handling and null-checks.
@@ -96,7 +96,7 @@ protected: // member functions
     bool CellIndexWithinRange(int cellIndex) const;
 
 private: // types
-    typedef AZStd::unordered_map, stl::equality_string_caseless > CSpriteHashMap;
+    typedef AZStd::unordered_map, stl::equality_string_caseless > CSpriteHashMap;
 
 private: // member functions
     bool LoadFromXmlFile();
@@ -109,8 +109,8 @@ private: // data
 
     SpriteSheetCellContainer m_spriteSheetCells;  //!< Stores information for each cell defined within the sprite-sheet.
 
-    string m_pathname;
-    string m_texturePathname;
+    AZStd::string m_pathname;
+    AZStd::string m_texturePathname;
     Borders m_borders;
     AZ::Data::Instance m_image;
     int m_numSpriteSheetCellTags;                       //!< Number of Cell child-tags in sprite XML; unfortunately needed to help with serialization.
diff --git a/Gems/LyShine/Code/Source/StringUtfUtils.h b/Gems/LyShine/Code/Source/StringUtfUtils.h
index 74a27afe9f..40dd22dd33 100644
--- a/Gems/LyShine/Code/Source/StringUtfUtils.h
+++ b/Gems/LyShine/Code/Source/StringUtfUtils.h
@@ -7,6 +7,8 @@
  */
 #pragma once
 
+#include 
+
 namespace LyShine
 {
     //! \brief Returns the number of UTF8 characters in a string.
@@ -16,15 +18,9 @@ namespace LyShine
     //! character in the string.
     inline int GetUtf8StringLength(const AZStd::string& utf8String)
     {
-        int utf8StrLen = 0;
-        Unicode::CIterator pChar(utf8String.c_str());
-        while (uint32_t ch = *pChar)
-        {
-            ++pChar;
-            ++utf8StrLen;
-        }
-
-        return utf8StrLen;
+        AZStd::wstring utf8StringW;
+        AZStd::to_wstring(utf8StringW, utf8String.c_str());
+        return static_cast(utf8StringW.size());
     }
 
     //! \brief Returns the number of bytes of the size of the given multi-byte char.
@@ -34,17 +30,16 @@ namespace LyShine
         // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
         // work for cases tested but may not in general.
         // In the long run it would be better to eliminate
-        // this function and use Unicode::CIterator<>::Position instead.
-        wchar_t wcharString[2] = { static_cast(multiByteChar), 0 };
-        AZStd::string utf8String(CryStringUtils::WStrToUTF8(wcharString));
-        int utf8Length = utf8String.length();
-        return utf8Length;
+        // this function and use some sequence_lenght function that is not internal.
+        return Utf8::Internal::sequence_length(&multiByteChar);
     }
 
     inline int GetByteLengthOfUtf8Chars(const char* utf8String, int numUtf8Chars)
     {
+        AZStd::wstring utf8StringW;
+        AZStd::to_wstring(utf8StringW, utf8String);
+        AZStd::wstring::const_iterator pChar = utf8StringW.begin();
         int byteStrlen = 0;
-        Unicode::CIterator pChar(utf8String);
         for (int i = 0; i < numUtf8Chars; i++)
         {
             uint32_t ch = *pChar;
diff --git a/Gems/LyShine/Code/Source/Tests/internal/test_UiTextComponent.cpp b/Gems/LyShine/Code/Source/Tests/internal/test_UiTextComponent.cpp
index 3cd137b25f..8cf2cd2edb 100644
--- a/Gems/LyShine/Code/Source/Tests/internal/test_UiTextComponent.cpp
+++ b/Gems/LyShine/Code/Source/Tests/internal/test_UiTextComponent.cpp
@@ -3508,7 +3508,7 @@ void UiTextComponent::UnitTestLocalization(CLyShine* lyshine, IConsoleCmdArgs* /
 {
     ILocalizationManager* pLocMan = GetISystem()->GetLocalizationManager();
 
-    string localizationXml("libs/localization/localization.xml");
+    AZStd::string localizationXml("libs/localization/localization.xml");
 
     bool initLocSuccess = false;
 
diff --git a/Gems/LyShine/Code/Source/TextMarkup.cpp b/Gems/LyShine/Code/Source/TextMarkup.cpp
index 864d7a2cfc..8c1a6e0b62 100644
--- a/Gems/LyShine/Code/Source/TextMarkup.cpp
+++ b/Gems/LyShine/Code/Source/TextMarkup.cpp
@@ -162,7 +162,8 @@ namespace
                     }
                     else if (AZStd::string(key) == "color")
                     {
-                        AZStd::string colorValue(string(value).Trim());
+                        AZStd::string colorValue(value);
+                        AZ::StringFunc::TrimWhiteSpace(colorValue, true, true);
                         AZStd::string::size_type ExpectedNumChars = 7;
                         if (ExpectedNumChars == colorValue.size() && '#' == colorValue.at(0))
                         {
diff --git a/Gems/LyShine/Code/Source/UiCanvasComponent.cpp b/Gems/LyShine/Code/Source/UiCanvasComponent.cpp
index 72d9f92d1f..b665f039b0 100644
--- a/Gems/LyShine/Code/Source/UiCanvasComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiCanvasComponent.cpp
@@ -177,11 +177,11 @@ namespace
 
     ////////////////////////////////////////////////////////////////////////////////////////////////
     // test if the given text file starts with the given text string
-    bool TestFileStartString(const string& pathname, const char* expectedStart)
+    bool TestFileStartString(const AZStd::string& pathname, const char* expectedStart)
     {
         // Open the file using CCryFile, this supports it being in the pak file or a standalone file
         CCryFile file;
-        if (!file.Open(pathname, "r"))
+        if (!file.Open(pathname.c_str(), "r"))
         {
             return false;
         }
@@ -208,7 +208,7 @@ namespace
 
     ////////////////////////////////////////////////////////////////////////////////////////////////
     // Check if the given file was saved using AZ serialization
-    bool IsValidAzSerializedFile(const string& pathname)
+    bool IsValidAzSerializedFile(const AZStd::string& pathname)
     {
         return TestFileStartString(pathname, " dstData;
@@ -3884,7 +3884,7 @@ UiCanvasComponent* UiCanvasComponent::CreateCanvasInternal(UiEntityContext* enti
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-UiCanvasComponent*  UiCanvasComponent::LoadCanvasInternal(const string& pathnameToOpen, bool forEditor, const string& assetIdPathname, UiEntityContext* entityContext,
+UiCanvasComponent*  UiCanvasComponent::LoadCanvasInternal(const AZStd::string& pathnameToOpen, bool forEditor, const AZStd::string& assetIdPathname, UiEntityContext* entityContext,
     const AZ::SliceComponent::EntityIdToEntityIdMap* previousRemapTable, AZ::EntityId previousCanvasId)
 {
     UiCanvasComponent* canvasComponent = nullptr;
diff --git a/Gems/LyShine/Code/Source/UiCanvasComponent.h b/Gems/LyShine/Code/Source/UiCanvasComponent.h
index 852bb482d0..097f23cbda 100644
--- a/Gems/LyShine/Code/Source/UiCanvasComponent.h
+++ b/Gems/LyShine/Code/Source/UiCanvasComponent.h
@@ -99,7 +99,7 @@ public: // member functions
     LyShine::EntityArray PickElements(const AZ::Vector2& bound0, const AZ::Vector2& bound1) override;
     AZ::EntityId FindInteractableToHandleEvent(AZ::Vector2 point) override;
 
-    bool SaveToXml(const string& assetIdPathname, const string& sourceAssetPathname) override;
+    bool SaveToXml(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname) override;
     void FixupCreatedEntities(LyShine::EntityArray topLevelEntities, bool makeUniqueNamesAndIds, AZ::Entity* optionalInsertionPoint) override;
     void AddElement(AZ::Entity* element, AZ::Entity* parent, AZ::Entity* insertBefore) override;
     void ReinitializeElements() override;
@@ -307,7 +307,7 @@ public: // static member functions
     static void Shutdown();
 
     static UiCanvasComponent* CreateCanvasInternal(UiEntityContext* entityContext, bool forEditor);
-    static UiCanvasComponent* LoadCanvasInternal(const string& pathToOpen, bool forEditor, const string& assetIdPathname, UiEntityContext* entityContext,
+    static UiCanvasComponent* LoadCanvasInternal(const AZStd::string& pathToOpen, bool forEditor, const AZStd::string& assetIdPathname, UiEntityContext* entityContext,
         const AZ::SliceComponent::EntityIdToEntityIdMap* previousRemapTable = nullptr, AZ::EntityId previousCanvasId = AZ::EntityId());
     static UiCanvasComponent* FixupReloadedCanvasForEditorInternal(AZ::Entity* newCanvasEntity,
         AZ::Entity* rootSliceEntity, UiEntityContext* entityContext,
@@ -403,7 +403,7 @@ private: // member functions
     void DestroyRenderTarget();
     void RenderCanvasToTexture();
 
-    bool SaveCanvasToFile(const string& pathname, AZ::DataStream::StreamType streamType);
+    bool SaveCanvasToFile(const AZStd::string& pathname, AZ::DataStream::StreamType streamType);
     bool SaveCanvasToStream(AZ::IO::GenericStream& stream, AZ::DataStream::StreamType streamType);
 
     //! Notify elements that their canvas space rect has changed since the last update, and recompute invalid layouts
diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.cpp b/Gems/LyShine/Code/Source/UiCanvasManager.cpp
index cb27f09672..bed3bcf433 100644
--- a/Gems/LyShine/Code/Source/UiCanvasManager.cpp
+++ b/Gems/LyShine/Code/Source/UiCanvasManager.cpp
@@ -342,7 +342,7 @@ void UiCanvasManager::OnCatalogAssetChanged(const AZ::Data::AssetId& assetId)
 
             // reload canvas with the same entity IDs (except for new entities, deleted entities etc)
             UiGameEntityContext* entityContext = new UiGameEntityContext();
-            string pathname(assetPath.c_str());
+            AZStd::string pathname(assetPath.c_str());
             UiCanvasComponent* newCanvasComponent = UiCanvasComponent::LoadCanvasInternal(pathname, false, "", entityContext, &existingRemapTable, existingCanvasEntityId);
 
             if (!newCanvasComponent)
@@ -393,7 +393,7 @@ AZ::EntityId UiCanvasManager::CreateCanvasInEditor(UiEntityContext* entityContex
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::EntityId UiCanvasManager::LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext)
+AZ::EntityId UiCanvasManager::LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext)
 {
     return LoadCanvasInternal(assetIdPathname.c_str(), true, sourceAssetPathname.c_str(), entityContext);
 }
@@ -1064,10 +1064,10 @@ void UiCanvasManager::DebugDisplayCanvasData(int setting) const
     for (auto canvas : m_loadedCanvases)
     {
         // Name
-        const string pathname = canvas->GetPathname().c_str();
+        const AZStd::string pathname = canvas->GetPathname().c_str();
         size_t lastDot = pathname.find_last_of(".");
         size_t lastSlash = pathname.find_last_of("/");
-        string leafName = pathname;
+        AZStd::string leafName = pathname;
         if (lastDot > lastSlash)
         {
             leafName = pathname.substr(lastSlash+1, lastDot-lastSlash-1);
@@ -1209,10 +1209,10 @@ void UiCanvasManager::DebugDisplayDrawCallData() const
     for (auto canvas : m_loadedCanvases)
     {
         // Name
-        const string pathname = canvas->GetPathname().c_str();
+        const AZStd::string pathname = canvas->GetPathname().c_str();
         size_t lastDot = pathname.find_last_of(".");
         size_t lastSlash = pathname.find_last_of("/");
-        string leafName = pathname;
+        AZStd::string leafName = pathname;
         if (lastDot > lastSlash)
         {
             leafName = pathname.substr(lastSlash+1, lastDot-lastSlash-1);
@@ -1373,7 +1373,7 @@ void UiCanvasManager::DebugReportDrawCalls(const AZStd::string& name) const
         }
 
         // Name of canvas
-        const string pathname = canvas->GetPathname().c_str();
+        const AZStd::string pathname = canvas->GetPathname().c_str();
         logLine = "\r\n=====================================================================================\r\n";
         AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
         logLine = AZStd::string::format("Canvas: %s\r\n", pathname.c_str());
@@ -1461,7 +1461,7 @@ void UiCanvasManager::DebugReportDrawCalls(const AZStd::string& name) const
                 {
                     if (!loggedCanvasHeader)
                     {
-                        const string pathname = canvas->GetPathname().c_str();
+                        const AZStd::string pathname = canvas->GetPathname().c_str();
                         logLine = AZStd::string::format("\r\nCanvas: %s\r\n\r\n", pathname.c_str());
                         AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
                         loggedCanvasHeader = true;
diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.h b/Gems/LyShine/Code/Source/UiCanvasManager.h
index 85783fab84..ebcee200e4 100644
--- a/Gems/LyShine/Code/Source/UiCanvasManager.h
+++ b/Gems/LyShine/Code/Source/UiCanvasManager.h
@@ -68,7 +68,7 @@ public: // member functions
     // ~AssetCatalogEventBus::Handler
 
     AZ::EntityId CreateCanvasInEditor(UiEntityContext* entityContext);
-    AZ::EntityId LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext);
+    AZ::EntityId LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext);
     AZ::EntityId ReloadCanvasFromXml(const AZStd::string& xmlString, UiEntityContext* entityContext);
 
     void ReleaseCanvas(AZ::EntityId canvas, bool forEditor);
diff --git a/Gems/LyShine/Code/Source/UiDropdownComponent.cpp b/Gems/LyShine/Code/Source/UiDropdownComponent.cpp
index 1940d57cbb..448c208c5e 100644
--- a/Gems/LyShine/Code/Source/UiDropdownComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiDropdownComponent.cpp
@@ -826,7 +826,8 @@ AZ::Outcome UiDropdownComponent::ValidatePotentialExpandedP
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-AZ::FailureValue FailureMessage(string message) {
+AZ::FailureValue FailureMessage(AZStd::string message)
+{
     return AZ::Failure(AZStd::string(message));
 }
 
diff --git a/Gems/LyShine/Code/Source/UiInteractableState.cpp b/Gems/LyShine/Code/Source/UiInteractableState.cpp
index d3440a9354..98abae4484 100644
--- a/Gems/LyShine/Code/Source/UiInteractableState.cpp
+++ b/Gems/LyShine/Code/Source/UiInteractableState.cpp
@@ -575,7 +575,7 @@ void UiInteractableStateFont::SetFontPathname(const AZStd::string& pathname)
             fontFamily = gEnv->pCryFont->LoadFontFamily(fileName.c_str());
             if (!fontFamily)
             {
-                string errorMsg = "Error loading a font from ";
+                AZStd::string errorMsg = "Error loading a font from ";
                 errorMsg += fileName.c_str();
                 errorMsg += ".";
                 CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, errorMsg.c_str());
diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp
index fadf09571f..be26a5a618 100644
--- a/Gems/LyShine/Code/Source/UiTextComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp
@@ -623,12 +623,14 @@ namespace
 
             int batchCurChar = 0;
 
-            Unicode::CIterator pChar(drawBatch.text.c_str());
+            Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
             uint32_t prevCh = 0;
             while (uint32_t ch = *pChar)
             {
-                char codepoint[5];
-                Unicode::Convert(codepoint, ch);
+                size_t maxSize = 5;
+                char codepoint[5] = { 0 };
+                char* codepointPtr = codepoint;
+                Utf8::Unchecked::octet_iterator::to_utf8_sequence(ch, codepointPtr, maxSize);
 
                 float curCharWidth = drawBatch.font->GetTextSize(codepoint, true, ctx).x;
 
@@ -652,15 +654,15 @@ namespace
                     lastSpaceIndexInBatch = batchCurChar;
                     lastSpaceBatch = &drawBatch;
                     lastSpaceWidth = curLineWidth + curCharWidth;
-                    pLastSpace = pChar.GetPosition();
+                    pLastSpace = pChar.base();
                     assert(*pLastSpace == ' ');
                 }
 
                 bool prevCharWasNewline = false;
-                const bool isFirstChar = pChar.GetPosition() == drawBatch.text.c_str();
+                const bool isFirstChar = pChar.base() == drawBatch.text.c_str();
                 if (ch && !isFirstChar)
                 {
-                    const char* pPrevCharStr = pChar.GetPosition() - 1;
+                    const char* pPrevCharStr = pChar.base() - 1;
                     prevCharWasNewline = pPrevCharStr[0] == '\n';
                 }
                 else if (isFirstChar)
@@ -705,12 +707,12 @@ namespace
                     }
                     else
                     {
-                        const char* pBuf = pChar.GetPosition();
+                        char* pBuf = pChar.base();
                         AZStd::string::size_type bytesProcessed = pBuf - drawBatch.text.c_str();
                         drawBatch.text.insert(bytesProcessed, "\n"); // Insert the newline, this invalidates the iterator
-                        pBuf = drawBatch.text.c_str() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
+                        pBuf = drawBatch.text.data() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
                         assert(*pBuf == '\n');
-                        pChar.SetPosition(pBuf); // pChar once again points inside the target string, at the current character
+                        pChar = Utf8::Unchecked::octet_iterator(pBuf); // pChar once again points inside the target string, at the current character
                         assert(*pChar == ch);
                         ++pChar;
                         ++curChar;
@@ -1189,7 +1191,7 @@ void UiTextComponent::DrawBatch::CalculateSize(const STextDrawContext& ctx, bool
             if (displayString.length() > 0)
             {
                 AZStd::string::size_type endpos = displayString.find_last_not_of(" \t\n\v\f\r");
-                if ((endpos != string::npos) && (endpos != displayString.length() - 1))
+                if ((endpos != AZStd::string::npos) && (endpos != displayString.length() - 1))
                 {
                     displayString.erase(endpos + 1);
                 }
@@ -1295,12 +1297,14 @@ bool UiTextComponent::DrawBatch::GetOverflowInfo(const STextDrawContext& ctx,
 
         float maxEffectOffsetX = font->GetMaxEffectOffset(ctx.m_fxIdx).x;
 
-        Unicode::CIterator pChar(text.c_str());
+        Utf8::Unchecked::octet_iterator pChar(text.data());
         uint32_t prevCh = 0;
         while (uint32_t ch = *pChar)
         {
-            char codepoint[5];
-            Unicode::Convert(codepoint, ch);
+            size_t maxSize = 5;
+            char codepoint[5] = { 0 };
+            char* codepointPtr = codepoint;
+            Utf8::Unchecked::octet_iterator::to_utf8_sequence(ch, codepointPtr, maxSize);
 
             float curCharWidth = font->GetTextSize(codepoint, true, ctx).x;
             if (prevCh)
@@ -2274,7 +2278,7 @@ int UiTextComponent::GetCharIndexFromCanvasSpacePoint(AZ::Vector2 point, bool mu
         // Iterate across the line
         for (const DrawBatch& drawBatch : batchLine.drawBatchList)
         {
-            Unicode::CIterator pChar(drawBatch.text.c_str());
+            Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
             while (uint32_t ch = *pChar)
             {
                 ++pChar;
@@ -4827,14 +4831,16 @@ int UiTextComponent::GetStartEllipseIndexInDrawBatch(const DrawBatch* drawBatchT
 {
     float overflowStringSize = 0.0f;
     int ellipsisCharPos = 0;
-    Unicode::CIterator pChar(drawBatchToEllipse->text.c_str());
+    Utf8::Unchecked::octet_iterator pChar(drawBatchToEllipse->text.data());
     uint32_t stringBufferIndex = 0;
     uint32_t prevCh = 0;
     while (uint32_t ch = *pChar)
     {
         ++pChar;
-        char codepoint[5];
-        Unicode::Convert(codepoint, ch);
+        size_t maxSize = 5;
+        char codepoint[5] = { 0 };
+        char* codepointPtr = codepoint;
+        Utf8::Unchecked::octet_iterator::to_utf8_sequence(ch, codepointPtr, maxSize);
         
         overflowStringSize += drawBatchToEllipse->font->GetTextSize(codepoint, true, ctx).x;
 
@@ -4925,7 +4931,7 @@ AZ::Vector2 UiTextComponent::GetTextSizeFromDrawBatchLines(const UiTextComponent
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 AZStd::string UiTextComponent::GetLocalizedText([[maybe_unused]] const AZStd::string& text)
 {
-    string locText;
+    AZStd::string locText;
     LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::LocalizeString_ch, m_text.c_str(), locText, false);
     return locText.c_str();
 }
@@ -5110,7 +5116,7 @@ int UiTextComponent::GetLineNumberFromCharIndex(const DrawBatchLines& drawBatchL
 
         for (const DrawBatch& drawBatch : batchLine.drawBatchList)
         {
-            Unicode::CIterator pChar(drawBatch.text.c_str());
+            Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
             while (uint32_t ch = *pChar)
             {
                 ++pChar;
diff --git a/Gems/LyShine/Code/Source/UiTextComponentOffsetsSelector.cpp b/Gems/LyShine/Code/Source/UiTextComponentOffsetsSelector.cpp
index b4e8a8d63e..b472f79bd6 100644
--- a/Gems/LyShine/Code/Source/UiTextComponentOffsetsSelector.cpp
+++ b/Gems/LyShine/Code/Source/UiTextComponentOffsetsSelector.cpp
@@ -30,7 +30,7 @@ void UiTextComponentOffsetsSelector::ParseBatchLine(const UiTextComponent::DrawB
     {
         // Iterate character by character over DrawBatch string contents,
         // looking for m_firstIndex and m_lastIndex.
-        Unicode::CIterator pChar(drawBatch.text.c_str());
+        Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
         while (uint32_t ch = *pChar)
         {
             ++pChar;
diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
index c149c5a4d4..8cc0efcaaf 100644
--- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
@@ -70,7 +70,7 @@ namespace
         if (stringLength > 0 && stringLength >= utf8Index)
         {
             // Iterate over the string until the given index is found.
-            Unicode::CIterator pChar(utf8String.c_str());
+            Utf8::Unchecked::octet_iterator pChar(utf8String.data());
             while (uint32_t ch = *pChar)
             {
                 if (utf8Index == utfIndexIter)
@@ -1185,7 +1185,8 @@ void UiTextInputComponent::UpdateDisplayedTextFunction()
                 // NOTE: this assumes the uint32_t can be interpreted as a wchar_t, it seems to
                 // work for cases tested but may not in general.
                 wchar_t wcharString[2] = { static_cast(this->GetReplacementCharacter()), 0 };
-                AZStd::string replacementCharString(CryStringUtils::WStrToUTF8(wcharString));
+                AZStd::string replacementCharString;
+                AZStd::to_string(replacementCharString, wcharString, 1);
 
                 int numReplacementChars = LyShine::GetUtf8StringLength(originalText);
 

From ad14d9cdd7a65ef44decde1ada4bb76741ba4a29 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:55:27 -0700
Subject: [PATCH 038/205] AtomFont

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h  | 2 +-
 .../AtomFont/Code/Platform/Common/FontTexture_Common.cpp        | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h
index 0e97440538..6443633245 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FBitmap.h
@@ -26,7 +26,7 @@ namespace AZ
         int Create(int width, int height);
         int Release();
 
-        int SaveBitmap(const string& fileName);
+        int SaveBitmap(const AZStd::string& fileName);
         int Get32Bpp(unsigned int** buffer)
         {
             (*buffer) = new unsigned int[m_width * m_height];
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Common/FontTexture_Common.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Common/FontTexture_Common.cpp
index 02cbb5a7a4..e3be52965c 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Platform/Common/FontTexture_Common.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Platform/Common/FontTexture_Common.cpp
@@ -11,7 +11,7 @@
 #include 
 
 //-------------------------------------------------------------------------------------------------
-int AZ::FontTexture::WriteToFile([[maybe_unused]] const string& fileName)
+int AZ::FontTexture::WriteToFile([[maybe_unused]] const AZStd::string& fileName)
 {
     return 1;
 }

From b1e9d81d96b2d30cd5e3a82dcb6503f7617ac73c Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:55:55 -0700
Subject: [PATCH 039/205] Gems/GameStateSamples

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../GameStateSamples/GameStatePrimaryControllerDisconnected.inl | 2 +-
 .../Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryControllerDisconnected.inl b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryControllerDisconnected.inl
index 4e9fb33c7e..ded069a638 100644
--- a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryControllerDisconnected.inl
+++ b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryControllerDisconnected.inl
@@ -83,7 +83,7 @@ namespace GameStateSamples
             return;
         }
 
-        string localizedMessage;
+        AZStd::string localizedMessage;
         const char* localizationKey = AZ_TRAIT_GAMESTATESAMPLES_PRIMARY_CONTROLLER_DISCONNECTED_LOC_KEY;
         bool wasLocalized = false;
         LocalizationManagerRequestBus::BroadcastResult(wasLocalized,
diff --git a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl
index d7e45fcbdd..62fa9710dc 100644
--- a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl
+++ b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStatePrimaryUserSignedOut.inl
@@ -99,7 +99,7 @@ namespace GameStateSamples
             return;
         }
 
-        string localizedMessage;
+        AZStd::string localizedMessage;
         const char* localizationKey = "@PRIMARY_CONTROLLER_DISCONNECTED_LOC_KEY";
         bool wasLocalized = false;
         LocalizationManagerRequestBus::BroadcastResult(wasLocalized,

From 3b28267569005e7eed1f88b0ce082a129898b454 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:56:28 -0700
Subject: [PATCH 040/205] Gems/PhysXDebug

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Gems/PhysXDebug/Code/Source/SystemComponent.cpp | 1 -
 Gems/PhysXDebug/Code/Source/SystemComponent.h   | 1 +
 2 files changed, 1 insertion(+), 1 deletion(-)

diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
index 0ccc77bba4..4944626d77 100644
--- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
+++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
@@ -30,7 +30,6 @@
 #include 
 
 #include 
-#include 
 
 #include 
 
diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.h b/Gems/PhysXDebug/Code/Source/SystemComponent.h
index 40434ad3e1..83756f20f9 100644
--- a/Gems/PhysXDebug/Code/Source/SystemComponent.h
+++ b/Gems/PhysXDebug/Code/Source/SystemComponent.h
@@ -18,6 +18,7 @@
 
 #include 
 #include 
+#include 
 
 #include 
 

From a14b4e478ee4b893fca85f00f56e4f4378f1d6e3 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Mon, 2 Aug 2021 17:56:56 -0700
Subject: [PATCH 041/205] Code/Editor

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/BaseLibraryManager.cpp            |   4 +-
 Code/Editor/Commands/CommandManager.cpp       |  71 +-
 Code/Editor/Commands/CommandManager.h         |   8 +-
 Code/Editor/ConfigGroup.cpp                   |   6 +-
 Code/Editor/ConfigGroup.h                     |   4 +-
 Code/Editor/Controls/ConsoleSCB.cpp           |   4 +-
 Code/Editor/Controls/FolderTreeCtrl.cpp       |   2 +-
 .../PropertyGenericCtrl.cpp                   |   4 +-
 Code/Editor/Controls/SplineCtrlEx.cpp         |   2 +-
 Code/Editor/Controls/SplineCtrlEx.h           |   2 +-
 Code/Editor/Core/QtEditorApplication.cpp      |   2 +-
 Code/Editor/Core/Tests/test_Main.cpp          |   2 +-
 Code/Editor/CryEdit.cpp                       |  38 +-
 Code/Editor/CryEdit.h                         |  24 +-
 Code/Editor/CryEditDoc.cpp                    |   8 +-
 Code/Editor/CryEditDoc.h                      |   2 +-
 Code/Editor/CryEditPy.cpp                     |   4 +-
 Code/Editor/EditorFileMonitor.cpp             |  12 +-
 Code/Editor/GameExporter.cpp                  |  10 +-
 Code/Editor/IEditorImpl.cpp                   |  33 +-
 Code/Editor/Include/Command.h                 |  24 +-
 Code/Editor/LevelFileDialog.cpp               |   6 +-
 Code/Editor/LogFile.cpp                       |  26 +-
 Code/Editor/MainWindow.cpp                    |   2 +-
 .../Platform/Windows/Util/Mailer_Windows.cpp  |   4 +-
 Code/Editor/PluginManager.cpp                 |   4 +-
 .../EditorAssetImporter/AssetImporterPlugin.h |   2 +-
 Code/Editor/ResourceSelectorHost.cpp          |   4 +-
 Code/Editor/SelectSequenceDialog.cpp          |   2 +-
 Code/Editor/ToolBox.cpp                       |  10 +-
 .../Editor/TrackView/CommentKeyUIControls.cpp |   2 +-
 .../TrackView/SequenceKeyUIControls.cpp       |   2 +-
 Code/Editor/TrackView/TrackViewAnimNode.cpp   |   4 +-
 Code/Editor/TrackView/TrackViewFindDlg.cpp    |   2 +-
 Code/Editor/TrackView/TrackViewNodes.cpp      |   2 +-
 Code/Editor/TrackView/TrackViewSequence.cpp   |   8 +-
 Code/Editor/TrackViewNewSequenceDialog.cpp    |   2 +-
 .../Util/AutoDirectoryRestoreFileDialog.cpp   |   2 +-
 Code/Editor/Util/FileUtil.cpp                 |  15 +-
 Code/Editor/Util/ImageASC.cpp                 |   3 +-
 Code/Editor/Util/ImageTIF.cpp                 |   6 +-
 Code/Editor/Util/ImageUtil.cpp                |   3 +-
 Code/Editor/Util/StringHelpers.cpp            | 847 +-----------------
 Code/Editor/Util/StringHelpers.h              | 188 +---
 Code/Editor/Util/XmlHistoryManager.cpp        |   6 +-
 Code/Editor/Util/XmlHistoryManager.h          |   2 +-
 Code/Legacy/CrySystem/XConsole.cpp            |   7 +-
 47 files changed, 208 insertions(+), 1219 deletions(-)

diff --git a/Code/Editor/BaseLibraryManager.cpp b/Code/Editor/BaseLibraryManager.cpp
index 2189156454..da41525d8b 100644
--- a/Code/Editor/BaseLibraryManager.cpp
+++ b/Code/Editor/BaseLibraryManager.cpp
@@ -526,7 +526,7 @@ void CBaseLibraryManager::Serialize(XmlNodeRef& node, bool bLoading)
 QString CBaseLibraryManager::MakeUniqueItemName(const QString& srcName, const QString& libName)
 {
     // unlikely we'll ever encounter more than 16
-    std::vector possibleDuplicates;
+    std::vector possibleDuplicates;
     possibleDuplicates.reserve(16);
 
     // search for strings in the database that might have a similar name (ignore case)
@@ -550,7 +550,7 @@ QString CBaseLibraryManager::MakeUniqueItemName(const QString& srcName, const QS
         const QString& name = pItem->GetName();
         if (name.startsWith(srcName, Qt::CaseInsensitive))
         {
-            possibleDuplicates.push_back(string(name.toUtf8().data()));
+            possibleDuplicates.push_back(AZStd::string(name.toUtf8().data()));
         }
     }
     pEnum->Release();
diff --git a/Code/Editor/Commands/CommandManager.cpp b/Code/Editor/Commands/CommandManager.cpp
index 708fccd16b..35f55babe2 100644
--- a/Code/Editor/Commands/CommandManager.cpp
+++ b/Code/Editor/Commands/CommandManager.cpp
@@ -79,9 +79,9 @@ CEditorCommandManager::~CEditorCommandManager()
     m_uiCommands.clear();
 }
 
-string CEditorCommandManager::GetFullCommandName(const AZStd::string& module, const string& name)
+AZStd::string CEditorCommandManager::GetFullCommandName(const AZStd::string& module, const AZStd::string& name)
 {
-    string fullName = module;
+    AZStd::string fullName = module;
     fullName += ".";
     fullName += name;
     return fullName;
@@ -91,10 +91,10 @@ bool CEditorCommandManager::AddCommand(CCommand* pCommand, TPfnDeleter deleter)
 {
     assert(pCommand);
 
-    string module = pCommand->GetModule();
-    string name = pCommand->GetName();
+    AZStd::string module = pCommand->GetModule();
+    AZStd::string name = pCommand->GetName();
 
-    if (IsRegistered(module, name) && m_bWarnDuplicate)
+    if (IsRegistered(module.c_str(), name.c_str()) && m_bWarnDuplicate)
     {
         QString errMsg;
 
@@ -118,7 +118,7 @@ bool CEditorCommandManager::AddCommand(CCommand* pCommand, TPfnDeleter deleter)
 
 bool CEditorCommandManager::UnregisterCommand(const char* module, const char* name)
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
     CommandTable::iterator itr = m_commands.find(fullName);
 
     if (itr != m_commands.end())
@@ -154,7 +154,7 @@ bool CEditorCommandManager::RegisterUICommand(
         return false;
     }
 
-    return AttachUIInfo(GetFullCommandName(module, name), uiInfo);
+    return AttachUIInfo(GetFullCommandName(module, name).c_str(), uiInfo);
 }
 
 bool CEditorCommandManager::AttachUIInfo(const char* fullCmdName, const CCommand0::SUIInfo& uiInfo)
@@ -190,14 +190,14 @@ bool CEditorCommandManager::AttachUIInfo(const char* fullCmdName, const CCommand
     return true;
 }
 
-bool CEditorCommandManager::GetUIInfo(const string& module, const string& name, CCommand0::SUIInfo& uiInfo) const
+bool CEditorCommandManager::GetUIInfo(const AZStd::string& module, const AZStd::string& name, CCommand0::SUIInfo& uiInfo) const
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
 
     return GetUIInfo(fullName, uiInfo);
 }
 
-bool CEditorCommandManager::GetUIInfo(const string& fullCmdName, CCommand0::SUIInfo& uiInfo) const
+bool CEditorCommandManager::GetUIInfo(const AZStd::string& fullCmdName, CCommand0::SUIInfo& uiInfo) const
 {
     CommandTable::const_iterator iter = m_commands.find(fullCmdName);
 
@@ -223,9 +223,9 @@ int CEditorCommandManager::GenNewCommandId()
     return uniqueId++;
 }
 
-QString CEditorCommandManager::Execute(const string& module, const string& name, const CCommand::CArgs& args)
+QString CEditorCommandManager::Execute(const AZStd::string& module, const AZStd::string& name, const CCommand::CArgs& args)
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
     CommandTable::iterator iter = m_commands.find(fullName);
 
     if (iter != m_commands.end())
@@ -245,18 +245,18 @@ QString CEditorCommandManager::Execute(const string& module, const string& name,
     return "";
 }
 
-QString CEditorCommandManager::Execute(const string& cmdLine)
+QString CEditorCommandManager::Execute(const AZStd::string& cmdLine)
 {
-    string cmdTxt, argsTxt;
+    AZStd::string cmdTxt, argsTxt;
     size_t argStart = cmdLine.find_first_of(' ');
 
     cmdTxt = cmdLine.substr(0, argStart);
     argsTxt = "";
 
-    if (argStart != string::npos)
+    if (argStart != AZStd::string::npos)
     {
         argsTxt = cmdLine.substr(argStart + 1);
-        argsTxt.Trim();
+        AZ::StringFunc::TrimWhiteSpace(argsTxt, true, true);
     }
 
     CommandTable::iterator itr = m_commands.find(cmdTxt);
@@ -301,7 +301,7 @@ void CEditorCommandManager::Execute(int commandId)
     }
 }
 
-void CEditorCommandManager::GetCommandList(std::vector& cmds) const
+void CEditorCommandManager::GetCommandList(std::vector& cmds) const
 {
     cmds.clear();
     cmds.reserve(m_commands.size());
@@ -315,9 +315,9 @@ void CEditorCommandManager::GetCommandList(std::vector& cmds) const
     std::sort(cmds.begin(), cmds.end());
 }
 
-string CEditorCommandManager::AutoComplete(const string& substr) const
+AZStd::string CEditorCommandManager::AutoComplete(const AZStd::string& substr) const
 {
-    std::vector cmds;
+    std::vector cmds;
     GetCommandList(cmds);
 
     // If substring is empty return first command.
@@ -358,7 +358,7 @@ string CEditorCommandManager::AutoComplete(const string& substr) const
 
 bool CEditorCommandManager::IsRegistered(const char* module, const char* name) const
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
     CommandTable::const_iterator iter = m_commands.find(fullName);
 
     if (iter != m_commands.end())
@@ -373,7 +373,7 @@ bool CEditorCommandManager::IsRegistered(const char* module, const char* name) c
 
 bool CEditorCommandManager::IsRegistered(const char* cmdLine_) const
 {
-    string cmdTxt, argsTxt, cmdLine(cmdLine_);
+    AZStd::string cmdTxt, argsTxt, cmdLine(cmdLine_);
     size_t argStart = cmdLine.find_first_of(' ');
     cmdTxt = cmdLine.substr(0, argStart);
     CommandTable::const_iterator iter = m_commands.find(cmdTxt);
@@ -402,9 +402,9 @@ bool CEditorCommandManager::IsRegistered(int commandId) const
     return false;
 }
 
-void CEditorCommandManager::SetCommandAvailableInScripting(const string& module, const string& name)
+void CEditorCommandManager::SetCommandAvailableInScripting(const AZStd::string& module, const AZStd::string& name)
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
     CommandTable::iterator iter = m_commands.find(fullName);
 
     if (iter != m_commands.end())
@@ -413,7 +413,7 @@ void CEditorCommandManager::SetCommandAvailableInScripting(const string& module,
     }
 }
 
-bool CEditorCommandManager::IsCommandAvailableInScripting(const string& fullCmdName) const
+bool CEditorCommandManager::IsCommandAvailableInScripting(const AZStd::string& fullCmdName) const
 {
     CommandTable::const_iterator iter = m_commands.find(fullCmdName);
 
@@ -425,16 +425,16 @@ bool CEditorCommandManager::IsCommandAvailableInScripting(const string& fullCmdN
     return false;
 }
 
-bool CEditorCommandManager::IsCommandAvailableInScripting(const string& module, const string& name) const
+bool CEditorCommandManager::IsCommandAvailableInScripting(const AZStd::string& module, const AZStd::string& name) const
 {
-    string fullName = GetFullCommandName(module, name);
+    AZStd::string fullName = GetFullCommandName(module, name);
 
     return IsCommandAvailableInScripting(fullName);
 }
 
-void CEditorCommandManager::LogCommand(const string& fullCmdName, const CCommand::CArgs& args) const
+void CEditorCommandManager::LogCommand(const AZStd::string& fullCmdName, const CCommand::CArgs& args) const
 {
-    string cmdLine = fullCmdName;
+    AZStd::string cmdLine = fullCmdName;
 
     for (int i = 0; i < args.GetArgCount(); ++i)
     {
@@ -509,7 +509,7 @@ void CEditorCommandManager::LogCommand(const string& fullCmdName, const CCommand
 
     if (pScriptTermDialog)
     {
-        string text = "> ";
+        AZStd::string text = "> ";
         text += cmdLine;
         text += "\r\n";
         pScriptTermDialog->AppendText(text.c_str());
@@ -526,14 +526,14 @@ QString CEditorCommandManager::ExecuteAndLogReturn(CCommand* pCommand, const CCo
     return result;
 }
 
-void CEditorCommandManager::GetArgsFromString(const string& argsTxt, CCommand::CArgs& argList)
+void CEditorCommandManager::GetArgsFromString(const AZStd::string& argsTxt, CCommand::CArgs& argList)
 {
     const char quoteSymbol = '\'';
     int curPos = 0;
     int prevPos = 0;
-    string arg = argsTxt.Tokenize(" ", curPos);
-
-    while (!arg.empty())
+    AZStd::vector tokens;
+    AZ::StringFunc::Tokenize(argsTxt, tokens, ' ');
+    for(AZStd::string& arg : tokens)
     {
         if (arg[0] == quoteSymbol)   // A special consideration for a quoted string
         {
@@ -542,11 +542,11 @@ void CEditorCommandManager::GetArgsFromString(const string& argsTxt, CCommand::C
                 size_t openingQuotePos = argsTxt.find(quoteSymbol, prevPos);
                 size_t closingQuotePos = argsTxt.find(quoteSymbol, curPos);
 
-                if (closingQuotePos != string::npos)
+                if (closingQuotePos != AZStd::string::npos)
                 {
                     arg = argsTxt.substr(openingQuotePos + 1, closingQuotePos - openingQuotePos - 1);
                     size_t nextArgPos = argsTxt.find(' ', closingQuotePos + 1);
-                    curPos = nextArgPos != string::npos ? nextArgPos + 1 : argsTxt.length();
+                    curPos = nextArgPos != AZStd::string::npos ? nextArgPos + 1 : argsTxt.length();
 
                     for (; curPos < argsTxt.length(); ++curPos)    // Skip spaces.
                     {
@@ -565,6 +565,5 @@ void CEditorCommandManager::GetArgsFromString(const string& argsTxt, CCommand::C
 
         argList.Add(arg.c_str());
         prevPos = curPos;
-        arg = argsTxt.Tokenize(" ", curPos);
     }
 }
diff --git a/Code/Editor/Commands/CommandManager.h b/Code/Editor/Commands/CommandManager.h
index a76df830d0..0af744ac72 100644
--- a/Code/Editor/Commands/CommandManager.h
+++ b/Code/Editor/Commands/CommandManager.h
@@ -53,9 +53,9 @@ public:
     QString Execute(const AZStd::string& cmdLine);
     QString Execute(const AZStd::string& module, const AZStd::string& name, const CCommand::CArgs& args);
     void Execute(int commandId);
-    void GetCommandList(std::vector& cmds) const;
+    void GetCommandList(std::vector& cmds) const;
     //! Used in the console dialog
-    string AutoComplete(const AZStd::string& substr) const;
+    AZStd::string AutoComplete(const AZStd::string& substr) const;
     bool IsRegistered(const char* module, const char* name) const;
     bool IsRegistered(const char* cmdLine) const;
     bool IsRegistered(int commandId) const;
@@ -74,7 +74,7 @@ protected:
     };
 
     //! A full command name to an actual command mapping
-    typedef std::map CommandTable;
+    typedef std::map CommandTable;
     AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING
     CommandTable m_commands;
 
@@ -86,7 +86,7 @@ protected:
     bool m_bWarnDuplicate;
 
     static int GenNewCommandId();
-    static string GetFullCommandName(const AZStd::string& module, const AZStd::string& name);
+    static AZStd::string GetFullCommandName(const AZStd::string& module, const AZStd::string& name);
     static void GetArgsFromString(const AZStd::string& argsTxt, CCommand::CArgs& argList);
     void LogCommand(const AZStd::string& fullCmdName, const CCommand::CArgs& args) const;
     QString ExecuteAndLogReturn(CCommand* pCommand, const CCommand::CArgs& args);
diff --git a/Code/Editor/ConfigGroup.cpp b/Code/Editor/ConfigGroup.cpp
index 4e61c38f4b..04c92ff155 100644
--- a/Code/Editor/ConfigGroup.cpp
+++ b/Code/Editor/ConfigGroup.cpp
@@ -127,9 +127,9 @@ namespace Config
 
                     case IConfigVar::eType_STRING:
                     {
-                        string currentValue = 0;
+                        AZStd::string currentValue = 0;
                         var->Get(¤tValue);
-                        node->setAttr(szName, currentValue);
+                        node->setAttr(szName, currentValue.c_str());
                         break;
                     }
                     }
@@ -186,7 +186,7 @@ namespace Config
 
                 case IConfigVar::eType_STRING:
                 {
-                    string currentValue = 0;
+                    AZStd::string currentValue = 0;
                     var->GetDefault(¤tValue);
                     QString readValue(currentValue.c_str());
                     if (node->getAttr(szName, readValue))
diff --git a/Code/Editor/ConfigGroup.h b/Code/Editor/ConfigGroup.h
index 5d9b22b2b9..aa379d4445 100644
--- a/Code/Editor/ConfigGroup.h
+++ b/Code/Editor/ConfigGroup.h
@@ -76,8 +76,8 @@ namespace Config
     protected:
         EType m_type;
         uint8 m_flags;
-        string m_name;
-        string m_description;
+        AZStd::string m_name;
+        AZStd::string m_description;
         void* m_ptr;
         ICVar* m_pCVar;
     };
diff --git a/Code/Editor/Controls/ConsoleSCB.cpp b/Code/Editor/Controls/ConsoleSCB.cpp
index 9f1921395c..0c664bbc59 100644
--- a/Code/Editor/Controls/ConsoleSCB.cpp
+++ b/Code/Editor/Controls/ConsoleSCB.cpp
@@ -180,7 +180,7 @@ bool ConsoleLineEdit::event(QEvent* ev)
 
         if (newStr.isEmpty())
         {
-            newStr = GetIEditor()->GetCommandManager()->AutoComplete(cstring.toUtf8().data());
+            newStr = GetIEditor()->GetCommandManager()->AutoComplete(cstring.toUtf8().data()).c_str();
         }
     }
 
@@ -211,7 +211,7 @@ void ConsoleLineEdit::keyPressEvent(QKeyEvent* ev)
         {
             if (commandManager->IsRegistered(str.toUtf8().data()))
             {
-                commandManager->Execute(QtUtil::ToString(str));
+                commandManager->Execute(str.toUtf8().data());
             }
             else
             {
diff --git a/Code/Editor/Controls/FolderTreeCtrl.cpp b/Code/Editor/Controls/FolderTreeCtrl.cpp
index 17b6dccac7..b1cbb9414e 100644
--- a/Code/Editor/Controls/FolderTreeCtrl.cpp
+++ b/Code/Editor/Controls/FolderTreeCtrl.cpp
@@ -400,7 +400,7 @@ void CFolderTreeCtrl::RemoveEmptyFolderItems(const QString& folder)
 
 void CFolderTreeCtrl::Edit(const QString& path)
 {
-    CFileUtil::EditTextFile(QtUtil::ToString(path), 0, IFileUtil::FILE_TYPE_SCRIPT);
+    CFileUtil::EditTextFile(path.toUtf8().data(), 0, IFileUtil::FILE_TYPE_SCRIPT);
 }
 
 void CFolderTreeCtrl::ShowInExplorer(const QString& path)
diff --git a/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp b/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp
index 1916ce5e16..a2c66b8b10 100644
--- a/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp
+++ b/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp
@@ -132,7 +132,9 @@ void LocalStringPropertyEditor::onEditClicked()
         if (pMgr->GetLocalizedInfoByIndex(i, sInfo))
         {
             item.desc = tr("English Text:\r\n");
-            item.desc += QString::fromWCharArray(Unicode::Convert(sInfo.sUtf8TranslatedText).c_str());
+            AZStd::wstring utf8TranslatedTextW;
+            AZStd::to_wstring(utf8TranslatedTextW, sInfo.sUtf8TranslatedText);
+            item.desc += QString::fromWCharArray(utf8TranslatedTextW.c_str());
             item.name = sInfo.sKey;
             items.push_back(item);
         }
diff --git a/Code/Editor/Controls/SplineCtrlEx.cpp b/Code/Editor/Controls/SplineCtrlEx.cpp
index 2afc3f16aa..73ede63951 100644
--- a/Code/Editor/Controls/SplineCtrlEx.cpp
+++ b/Code/Editor/Controls/SplineCtrlEx.cpp
@@ -127,7 +127,7 @@ private:
         std::vector keySelectionFlags;
         _smart_ptr undo;
         _smart_ptr redo;
-        string id;
+        AZStd::string id;
         ISplineInterpolator* pSpline;
     };
 
diff --git a/Code/Editor/Controls/SplineCtrlEx.h b/Code/Editor/Controls/SplineCtrlEx.h
index de07c4214b..add4bcb0a9 100644
--- a/Code/Editor/Controls/SplineCtrlEx.h
+++ b/Code/Editor/Controls/SplineCtrlEx.h
@@ -54,7 +54,7 @@ class ISplineSet
 {
 public:
     virtual ISplineInterpolator* GetSplineFromID(const AZStd::string& id) = 0;
-    virtual string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
+    virtual AZStd::string GetIDFromSpline(ISplineInterpolator* pSpline) = 0;
     virtual int GetSplineCount() const = 0;
     virtual int GetKeyCountAtTime(float time, float threshold) const = 0;
 };
diff --git a/Code/Editor/Core/QtEditorApplication.cpp b/Code/Editor/Core/QtEditorApplication.cpp
index 9ec3b57e29..11f65bfaa5 100644
--- a/Code/Editor/Core/QtEditorApplication.cpp
+++ b/Code/Editor/Core/QtEditorApplication.cpp
@@ -206,7 +206,7 @@ namespace
 
     static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message)
     {
-        AZ::Debug::Platform::OutputToDebugger("Qt", message.utf8());
+        AZ::Debug::Platform::OutputToDebugger("Qt", message.toUtf8().data());
         AZ::Debug::Platform::OutputToDebugger(nullptr, "\n");
     }
 }
diff --git a/Code/Editor/Core/Tests/test_Main.cpp b/Code/Editor/Core/Tests/test_Main.cpp
index c0772753c6..c0e34311ec 100644
--- a/Code/Editor/Core/Tests/test_Main.cpp
+++ b/Code/Editor/Core/Tests/test_Main.cpp
@@ -52,7 +52,7 @@ protected:
     }
 
 private:
-    AZ::AllocatorScope m_allocatorScope;
+    AZ::AllocatorScope m_allocatorScope;
     SSystemGlobalEnvironment m_stubEnv;
     AZ::IO::LocalFileIO m_fileIO;
     NiceMock* m_cryPak;
diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp
index 973a818b92..b69bfa78f3 100644
--- a/Code/Editor/CryEdit.cpp
+++ b/Code/Editor/CryEdit.cpp
@@ -272,8 +272,8 @@ void CCryDocManager::OnFileNew()
     m_pDefTemplate->OpenDocumentFile(NULL);
     // if returns NULL, the user has already been alerted
 }
-BOOL CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT nIDSTitle,
-    [[maybe_unused]] DWORD lFlags, BOOL bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate)
+bool CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT nIDSTitle,
+    [[maybe_unused]] DWORD lFlags, bool bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate)
 {
     CLevelFileDialog levelFileDialog(bOpenFileDialog);
     levelFileDialog.show();
@@ -287,7 +287,7 @@ BOOL CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT n
 
     return false;
 }
-CCryEditDoc* CCryDocManager::OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU)
+CCryEditDoc* CCryDocManager::OpenDocumentFile(const char* lpszFileName, bool bAddToMRU)
 {
     assert(lpszFileName != NULL);
 
@@ -657,7 +657,7 @@ struct SharedData
 //
 //      This function uses a technique similar to that described in KB
 //      article Q141752 to locate the previous instance of the application. .
-BOOL CCryEditApp::FirstInstance(bool bForceNewInstance)
+bool CCryEditApp::FirstInstance(bool bForceNewInstance)
 {
     QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1);
     sem.acquire();
@@ -805,12 +805,12 @@ void CCryEditApp::InitDirectory()
 // Needed to work with custom memory manager.
 //////////////////////////////////////////////////////////////////////////
 
-CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL bMakeVisible /*= true*/)
+CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bMakeVisible /*= true*/)
 {
     return OpenDocumentFile(lpszPathName, true, bMakeVisible);
 }
 
-CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL bAddToMRU, [[maybe_unused]] BOOL bMakeVisible)
+CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bAddToMRU, [[maybe_unused]] bool bMakeVisible)
 {
     CCryEditDoc* pCurDoc = GetIEditor()->GetDocument();
 
@@ -849,7 +849,7 @@ CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL
     return pCurDoc;
 }
 
-CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(LPCTSTR lpszPathName, CCryEditDoc*& rpDocMatch)
+CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(const char* lpszPathName, CCryEditDoc*& rpDocMatch)
 {
     assert(lpszPathName != NULL);
     rpDocMatch = NULL;
@@ -1059,7 +1059,7 @@ AZ::Outcome CCryEditApp::InitGameSystem(HWND hwndForInputSy
 }
 
 /////////////////////////////////////////////////////////////////////////////
-BOOL CCryEditApp::CheckIfAlreadyRunning()
+bool CCryEditApp::CheckIfAlreadyRunning()
 {
     bool bForceNewInstance = false;
 
@@ -1303,7 +1303,7 @@ void CCryEditApp::InitLevel(const CEditCommandLineInfo& cmdInfo)
 }
 
 /////////////////////////////////////////////////////////////////////////////
-BOOL CCryEditApp::InitConsole()
+bool CCryEditApp::InitConsole()
 {
     // Execute command from cmdline -exec_line if applicable
     if (!m_execLineCmd.isEmpty())
@@ -1593,7 +1593,7 @@ void CCryEditApp::RunInitPythonScript(CEditCommandLineInfo& cmdInfo)
 
 /////////////////////////////////////////////////////////////////////////////
 // CCryEditApp initialization
-BOOL CCryEditApp::InitInstance()
+bool CCryEditApp::InitInstance()
 {
     QElapsedTimer startupTimer;
     startupTimer.start();
@@ -2281,7 +2281,7 @@ void CCryEditApp::EnableIdleProcessing()
     AZ_Assert(m_disableIdleProcessingCounter >= 0, "m_disableIdleProcessingCounter must be nonnegative");
 }
 
-BOOL CCryEditApp::OnIdle([[maybe_unused]] LONG lCount)
+bool CCryEditApp::OnIdle([[maybe_unused]] LONG lCount)
 {
     if (0 == m_disableIdleProcessingCounter)
     {
@@ -3226,7 +3226,7 @@ void CCryEditApp::OnCreateLevel()
 //////////////////////////////////////////////////////////////////////////
 bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
 {
-    BOOL bIsDocModified = GetIEditor()->GetDocument()->IsModified();
+    bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
     if (GetIEditor()->GetDocument()->IsDocumentReady() && bIsDocModified)
     {
         QString str = QObject::tr("Level %1 has been changed. Save Level?").arg(GetIEditor()->GetGameEngine()->GetLevelName());
@@ -3280,7 +3280,7 @@ bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
         GetIEditor()->GetDocument()->DeleteTemporaryLevel();
     }
 
-    if (levelName.length() == 0 || !CryStringUtils::IsValidFileName(levelName.toUtf8().data()))
+    if (levelName.length() == 0 || !AZ::StringFunc::Path::IsValid(levelName.toUtf8().data()))
     {
         QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level name is invalid, please choose another name."));
         return false;
@@ -3313,13 +3313,15 @@ bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
         DWORD dw = GetLastError();
 
 #ifdef WIN32
-        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+        wchar_t windowsErrorMessageW[ERROR_LEN] = { 0 };
+        FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
             NULL,
             dw,
             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-            windowsErrorMessage.data(),
-            windowsErrorMessage.length(), NULL);
+            windowsErrorMessageW,
+            ERROR_LEN - 1, NULL);
         _getcwd(cwd.data(), cwd.length());
+        AZStd::to_string(windowsErrorMessage.data(), ERROR_LEN, windowsErrorMessageW);
 #else
         windowsErrorMessage = strerror(dw);
         cwd = QDir::currentPath().toUtf8();
@@ -3393,7 +3395,7 @@ void CCryEditApp::OnOpenSlice()
 }
 
 //////////////////////////////////////////////////////////////////////////
-CCryEditDoc* CCryEditApp::OpenDocumentFile(LPCTSTR lpszFileName)
+CCryEditDoc* CCryEditApp::OpenDocumentFile(const char* lpszFileName)
 {
     if (m_openingLevel)
     {
@@ -4250,7 +4252,7 @@ extern "C" int AZ_DLL_EXPORT CryEditMain(int argc, char* argv[])
 
         int exitCode = 0;
 
-        BOOL didCryEditStart = CCryEditApp::instance()->InitInstance();
+        bool didCryEditStart = CCryEditApp::instance()->InitInstance();
         AZ_Error("Editor", didCryEditStart, "O3DE Editor did not initialize correctly, and will close."
             "\nThis could be because of incorrectly configured components, or missing required gems."
             "\nSee other errors for more details.");
diff --git a/Code/Editor/CryEdit.h b/Code/Editor/CryEdit.h
index af0fbb0971..431a9cb817 100644
--- a/Code/Editor/CryEdit.h
+++ b/Code/Editor/CryEdit.h
@@ -135,16 +135,16 @@ public:
     virtual void AddToRecentFileList(const QString& lpszPathName);
     ECreateLevelResult CreateLevel(const QString& levelName, QString& fullyQualifiedLevelName);
     static void InitDirectory();
-    BOOL FirstInstance(bool bForceNewInstance = false);
+    bool FirstInstance(bool bForceNewInstance = false);
     void InitFromCommandLine(CEditCommandLineInfo& cmdInfo);
-    BOOL CheckIfAlreadyRunning();
+    bool CheckIfAlreadyRunning();
     //! @return successful outcome if initialization succeeded. or failed outcome with error message.
     AZ::Outcome InitGameSystem(HWND hwndForInputSystem);
     void CreateSplashScreen();
     void InitPlugins();
     bool InitGame();
 
-    BOOL InitConsole();
+    bool InitConsole();
     int IdleProcessing(bool bBackground);
     bool IsWindowInForeground();
     void RunInitPythonScript(CEditCommandLineInfo& cmdInfo);
@@ -171,10 +171,10 @@ public:
     // Overrides
     // ClassWizard generated virtual function overrides
 public:
-    virtual BOOL InitInstance();
+    virtual bool InitInstance();
     virtual int ExitInstance(int exitCode = 0);
-    virtual BOOL OnIdle(LONG lCount);
-    virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszFileName);
+    virtual bool OnIdle(LONG lCount);
+    virtual CCryEditDoc* OpenDocumentFile(const char* lpszFileName);
 
     CCryDocManager* GetDocManager() { return m_pDocManager; }
 
@@ -454,9 +454,9 @@ public:
     ~CCrySingleDocTemplate() {};
     // avoid creating another CMainFrame
     // close other type docs before opening any things
-    virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszPathName, BOOL bAddToMRU, BOOL bMakeVisible);
-    virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszPathName, BOOL bMakeVisible = TRUE);
-    virtual Confidence MatchDocType(LPCTSTR lpszPathName, CCryEditDoc*& rpDocMatch);
+    virtual CCryEditDoc* OpenDocumentFile(const char* lpszPathName, bool bAddToMRU, bool bMakeVisible);
+    virtual CCryEditDoc* OpenDocumentFile(const char* lpszPathName, bool bMakeVisible = TRUE);
+    virtual Confidence MatchDocType(const char* lpszPathName, CCryEditDoc*& rpDocMatch);
 
 private:
     const QMetaObject* m_documentClass = nullptr;
@@ -471,9 +471,9 @@ public:
     CCrySingleDocTemplate* SetDefaultTemplate(CCrySingleDocTemplate* pNew);
     // Copied from MFC to get rid of the silly ugly unoverridable doc-type pick dialog
     virtual void OnFileNew();
-    virtual BOOL DoPromptFileName(QString& fileName, UINT nIDSTitle,
-        DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate);
-    virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU);
+    virtual bool DoPromptFileName(QString& fileName, UINT nIDSTitle,
+        DWORD lFlags, bool bOpenFileDialog, CDocTemplate* pTemplate);
+    virtual CCryEditDoc* OpenDocumentFile(const char* lpszFileName, bool bAddToMRU);
 
     QVector m_templateList;
 };
diff --git a/Code/Editor/CryEditDoc.cpp b/Code/Editor/CryEditDoc.cpp
index 43f599b191..5438f44f37 100644
--- a/Code/Editor/CryEditDoc.cpp
+++ b/Code/Editor/CryEditDoc.cpp
@@ -426,8 +426,8 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename)
         Audio::AudioSystemRequestBus::BroadcastResult(controlsPath, &Audio::AudioSystemRequestBus::Events::GetControlsPath);
         QString sAudioLevelPath(controlsPath);
         sAudioLevelPath += "levels/";
-        string const sLevelNameOnly = PathUtil::GetFileName(fileName.toUtf8().data());
-        sAudioLevelPath += sLevelNameOnly;
+        AZStd::string const sLevelNameOnly = PathUtil::GetFileName(fileName.toUtf8().data());
+        sAudioLevelPath += sLevelNameOnly.c_str();
         QByteArray path = sAudioLevelPath.toUtf8();
         Audio::SAudioManagerRequestData oAMData(path, Audio::eADS_LEVEL_SPECIFIC);
         Audio::SAudioRequest oAudioRequestData;
@@ -1919,7 +1919,7 @@ void CCryEditDoc::LogLoadTime(int time)
 
     CLogFile::FormatLine("[LevelLoadTime] Level %s loaded in %d seconds", level.toUtf8().data(), time / 1000);
 #if defined(AZ_PLATFORM_WINDOWS)
-    SetFileAttributes(filename.toUtf8().data(), FILE_ATTRIBUTE_ARCHIVE);
+    SetFileAttributesW(filename.toStdWString().c_str(), FILE_ATTRIBUTE_ARCHIVE);
 #endif
 
     FILE* file = nullptr;
@@ -2152,7 +2152,7 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar)
     }
 }
 
-QString CCryEditDoc::GetCryIndexPath(const LPCTSTR levelFilePath)
+QString CCryEditDoc::GetCryIndexPath(const char* levelFilePath)
 {
     QString levelPath = Path::GetPath(levelFilePath);
     QString levelName = Path::GetFileName(levelFilePath);
diff --git a/Code/Editor/CryEditDoc.h b/Code/Editor/CryEditDoc.h
index 574f8eb7da..9d86f62489 100644
--- a/Code/Editor/CryEditDoc.h
+++ b/Code/Editor/CryEditDoc.h
@@ -180,7 +180,7 @@ protected:
     void OnStartLevelResourceList();
     static void OnValidateSurfaceTypesChanged(ICVar*);
 
-    QString GetCryIndexPath(const LPCTSTR levelFilePath);
+    QString GetCryIndexPath(const char* levelFilePath);
 
     //////////////////////////////////////////////////////////////////////////
     // SliceEditorEntityOwnershipServiceNotificationBus::Handler
diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp
index e65af3a19b..6abaf933fe 100644
--- a/Code/Editor/CryEditPy.cpp
+++ b/Code/Editor/CryEditPy.cpp
@@ -210,7 +210,7 @@ namespace
     const char* PyGetCurrentLevelName()
     {
         // Using static member to capture temporary data
-        static string tempLevelName;
+        static AZStd::string tempLevelName;
         tempLevelName = GetIEditor()->GetGameEngine()->GetLevelName().toUtf8().data();
         return tempLevelName.c_str();
     }
@@ -218,7 +218,7 @@ namespace
     const char* PyGetCurrentLevelPath()
     {
         // Using static member to capture temporary data
-        static string tempLevelPath;
+        static AZStd::string tempLevelPath;
         tempLevelPath = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data();
         return tempLevelPath.c_str();
     }
diff --git a/Code/Editor/EditorFileMonitor.cpp b/Code/Editor/EditorFileMonitor.cpp
index 96dc883ab0..ae5d900f2d 100644
--- a/Code/Editor/EditorFileMonitor.cpp
+++ b/Code/Editor/EditorFileMonitor.cpp
@@ -55,10 +55,10 @@ bool CEditorFileMonitor::RegisterListener(IFileChangeListener* pListener, const
 
 
 //////////////////////////////////////////////////////////////////////////
-static string CanonicalizePath(const char* path)
+static AZStd::string CanonicalizePath(const char* path)
 {
     auto canon = QFileInfo(path).canonicalFilePath();
-    return canon.isEmpty() ? string(path) : string(canon.toUtf8());
+    return canon.isEmpty() ? AZStd::string(path) : AZStd::string(canon.toUtf8());
 }
 
 //////////////////////////////////////////////////////////////////////////
@@ -66,8 +66,8 @@ bool CEditorFileMonitor::RegisterListener(IFileChangeListener* pListener, const
 {
     bool success = true;
 
-    string gameFolder = Path::GetEditingGameDataFolder().c_str();
-    string naivePath;
+    AZStd::string gameFolder = Path::GetEditingGameDataFolder().c_str();
+    AZStd::string naivePath;
     CFileChangeMonitor* fileChangeMonitor = CFileChangeMonitor::Instance();
     AZ_Assert(fileChangeMonitor, "CFileChangeMonitor singleton missing.");
 
@@ -75,12 +75,12 @@ bool CEditorFileMonitor::RegisterListener(IFileChangeListener* pListener, const
     // Append slash in preparation for appending the second part.
     naivePath = PathUtil::AddSlash(naivePath);
     naivePath += sFolderRelativeToGame;
-    naivePath.replace('/', '\\');
+    AZ::StringFunc::Replace(naivePath, '/', '\\');
 
     // Remove the final slash if the given item is a folder so the file change monitor correctly picks up on it.
     naivePath = PathUtil::RemoveSlash(naivePath);
 
-    string canonicalizedPath = CanonicalizePath(naivePath.c_str());
+    AZStd::string canonicalizedPath = CanonicalizePath(naivePath.c_str());
 
     if (fileChangeMonitor->IsDirectory(canonicalizedPath.c_str()) || fileChangeMonitor->IsFile(canonicalizedPath.c_str()))
     {
diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp
index 006eb9189c..4c9031f08d 100644
--- a/Code/Editor/GameExporter.cpp
+++ b/Code/Editor/GameExporter.cpp
@@ -378,11 +378,11 @@ void CGameExporter::ExportFileList(const QString& path, const QString& levelName
 {
     // process the folder of the specified map name, producing a filelist.xml file
     //  that can later be used for map downloads
-    string newpath;
+    AZStd::string newpath;
 
     QString filename = levelName;
-    string mapname = (filename + ".dds").toUtf8().data();
-    string metaname = (filename + ".xml").toUtf8().data();
+    AZStd::string mapname = (filename + ".dds").toUtf8().data();
+    AZStd::string metaname = (filename + ".xml").toUtf8().data();
 
     XmlNodeRef rootNode = gEnv->pSystem->CreateXmlNode("download");
     rootNode->setAttr("name", filename.toUtf8().data());
@@ -434,9 +434,9 @@ void CGameExporter::ExportFileList(const QString& path, const QString& levelName
                     newFileNode->setAttr("size", handle.m_fileDesc.nSize);
 
                     unsigned char md5[16];
-                    string filenameToHash = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data();
+                    AZStd::string filenameToHash = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data();
                     filenameToHash += "/";
-                    filenameToHash += string{ handle.m_filename.data(), handle.m_filename.size() };
+                    filenameToHash += AZStd::string{ handle.m_filename.data(), handle.m_filename.size() };
                     if (gEnv->pCryPak->ComputeMD5(filenameToHash.data(), md5))
                     {
                         char md5string[33];
diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp
index 2e755bd36a..65d5792aa5 100644
--- a/Code/Editor/IEditorImpl.cpp
+++ b/Code/Editor/IEditorImpl.cpp
@@ -26,6 +26,7 @@ AZ_POP_DISABLE_WARNING
 #include 
 #include 
 #include 
+#include 
 
 // AzFramework
 #include 
@@ -1107,16 +1108,18 @@ void CEditorImpl::DetectVersion()
     DWORD dwHandle;
     UINT len;
 
-    char ver[1024 * 8];
+    wchar_t ver[1024 * 8];
 
     AZ::Utils::GetExecutablePath(exe, _MAX_PATH);
+    AZStd::wstring exeW;
+    AZStd::to_wstring(exeW, exe);
 
-    int verSize = GetFileVersionInfoSize(exe, &dwHandle);
+    int verSize = GetFileVersionInfoSizeW(exeW.c_str(), &dwHandle);
     if (verSize > 0)
     {
-        GetFileVersionInfo(exe, dwHandle, 1024 * 8, ver);
+        GetFileVersionInfoW(exeW.c_str(), dwHandle, 1024 * 8, ver);
         VS_FIXEDFILEINFO* vinfo;
-        VerQueryValue(ver, "\\", (void**)&vinfo, &len);
+        VerQueryValueW(ver, L"\\", (void**)&vinfo, &len);
 
         m_fileVersion.v[0] = vinfo->dwFileVersionLS & 0xFFFF;
         m_fileVersion.v[1] = vinfo->dwFileVersionLS >> 16;
@@ -1557,31 +1560,31 @@ IExportManager* CEditorImpl::GetExportManager()
 void CEditorImpl::AddUIEnums()
 {
     // Spec settings for shadow casting lights
-    string SpecString[4];
+    AZStd::string SpecString[4];
     QStringList types;
     types.push_back("Never=0");
-    SpecString[0].Format("VeryHigh Spec=%d", CONFIG_VERYHIGH_SPEC);
+    SpecString[0] = AZStd::string::format("VeryHigh Spec=%d", CONFIG_VERYHIGH_SPEC);
     types.push_back(SpecString[0].c_str());
-    SpecString[1].Format("High Spec=%d", CONFIG_HIGH_SPEC);
+    SpecString[1] = AZStd::string::format("High Spec=%d", CONFIG_HIGH_SPEC);
     types.push_back(SpecString[1].c_str());
-    SpecString[2].Format("Medium Spec=%d", CONFIG_MEDIUM_SPEC);
+    SpecString[2] = AZStd::string::format("Medium Spec=%d", CONFIG_MEDIUM_SPEC);
     types.push_back(SpecString[2].c_str());
-    SpecString[3].Format("Low Spec=%d", CONFIG_LOW_SPEC);
+    SpecString[3] = AZStd::string::format("Low Spec=%d", CONFIG_LOW_SPEC);
     types.push_back(SpecString[3].c_str());
     m_pUIEnumsDatabase->SetEnumStrings("CastShadows", types);
 
     // Power-of-two percentages
-    string percentStringPOT[5];
+    AZStd::string percentStringPOT[5];
     types.clear();
-    percentStringPOT[0].Format("Default=%d", 0);
+    percentStringPOT[0] = AZStd::string::format("Default=%d", 0);
     types.push_back(percentStringPOT[0].c_str());
-    percentStringPOT[1].Format("12.5=%d", 1);
+    percentStringPOT[1] = AZStd::string::format("12.5=%d", 1);
     types.push_back(percentStringPOT[1].c_str());
-    percentStringPOT[2].Format("25=%d", 2);
+    percentStringPOT[2] = AZStd::string::format("25=%d", 2);
     types.push_back(percentStringPOT[2].c_str());
-    percentStringPOT[3].Format("50=%d", 3);
+    percentStringPOT[3] = AZStd::string::format("50=%d", 3);
     types.push_back(percentStringPOT[3].c_str());
-    percentStringPOT[4].Format("100=%d", 4);
+    percentStringPOT[4] = AZStd::string::format("100=%d", 4);
     types.push_back(percentStringPOT[4].c_str());
     m_pUIEnumsDatabase->SetEnumStrings("ShadowMinResPercent", types);
 }
diff --git a/Code/Editor/Include/Command.h b/Code/Editor/Include/Command.h
index 92a7736446..e4fea5a3e7 100644
--- a/Code/Editor/Include/Command.h
+++ b/Code/Editor/Include/Command.h
@@ -18,7 +18,7 @@
 
 #include "Util/EditorUtils.h"
 
-inline string ToString(const QString& s)
+inline AZStd::string ToString(const QString& s)
 {
     return s.toUtf8().data();
 }
@@ -85,7 +85,7 @@ public:
             return m_args[i];
         }
     private:
-        DynArray m_args;
+        DynArray m_args;
         unsigned char m_stringFlags;    // This is needed to quote string parameters when logging a command.
     };
 
@@ -104,15 +104,15 @@ public:
 
 protected:
     friend class CEditorCommandManager;
-    string m_module;
-    string m_name;
-    string m_description;
-    string m_example;
+    AZStd::string m_module;
+    AZStd::string m_name;
+    AZStd::string m_description;
+    AZStd::string m_example;
     bool m_bAlsoAvailableInScripting;
 
     template 
-    static string ToString_(T t) { return ::ToString(t); }
-    static inline string ToString_(const char* val)
+    static AZStd::string ToString_(T t) { return ::ToString(t); }
+    static inline AZStd::string ToString_(const char* val)
     { return val; }
     template 
     static bool FromString_(T& t, const char* s) { return ::FromString(t, s); }
@@ -146,10 +146,10 @@ public:
     // UI metadata for this command, if any
     struct SUIInfo
     {
-        string caption;
-        string tooltip;
-        string description;
-        string iconFilename;
+        AZStd::string caption;
+        AZStd::string tooltip;
+        AZStd::string description;
+        AZStd::string iconFilename;
         int iconIndex;
         int commandId; // Windows command id
 
diff --git a/Code/Editor/LevelFileDialog.cpp b/Code/Editor/LevelFileDialog.cpp
index 41bb4d6faa..cefa1330eb 100644
--- a/Code/Editor/LevelFileDialog.cpp
+++ b/Code/Editor/LevelFileDialog.cpp
@@ -98,7 +98,7 @@ CLevelFileDialog::CLevelFileDialog(bool openDialog, QWidget* parent)
         connect(ui->nameLineEdit, &QLineEdit::textChanged, this, &CLevelFileDialog::OnNameChanged);
     }
 
-    // reject invalid file names (see CryStringUtils::IsValidFileName)
+    // reject invalid file names
     ui->nameLineEdit->setValidator(new QRegExpValidator(QRegExp("^[a-zA-Z0-9_\\-./]*$"), ui->nameLineEdit));
 
     ReloadTree();
@@ -315,7 +315,7 @@ void CLevelFileDialog::OnNewFolder()
             const QString newFolderName = inputDlg.textValue();
             const QString newFolderPath = parentFullPath + "/" + newFolderName;
 
-            if (!CryStringUtils::IsValidFileName(newFolderName.toUtf8().data()))
+            if (!AZ::StringFunc::Path::IsValid(newFolderName.toUtf8().data()))
             {
                 QMessageBox box(this);
                 box.setText(tr("Please enter a single, valid folder name(standard English alphanumeric characters only)"));
@@ -416,7 +416,7 @@ bool CLevelFileDialog::ValidateSaveLevelPath(QString& errorMessage) const
     const QString enteredPath = GetEnteredPath();
     const QString levelPath = GetLevelPath();
 
-    if (!CryStringUtils::IsValidFileName(Path::GetFileName(levelPath).toUtf8().data()))
+    if (!AZ::StringFunc::Path::IsValid(Path::GetFileName(levelPath).toUtf8().data()))
     {
         errorMessage = tr("Please enter a valid level name (standard English alphanumeric characters only)");
         return false;
diff --git a/Code/Editor/LogFile.cpp b/Code/Editor/LogFile.cpp
index 8c04eab58c..76c6f34181 100644
--- a/Code/Editor/LogFile.cpp
+++ b/Code/Editor/LogFile.cpp
@@ -180,14 +180,14 @@ void CLogFile::FormatLineV(const char * format, va_list argList)
 void CLogFile::AboutSystem()
 {
     char szBuffer[MAX_LOGBUFFER_SIZE];
+    wchar_t szBufferW[MAX_LOGBUFFER_SIZE];
 #if defined(AZ_PLATFORM_WINDOWS) || defined(AZ_PLATFORM_LINUX)
     //////////////////////////////////////////////////////////////////////
     // Write the system informations to the log
     //////////////////////////////////////////////////////////////////////
 
-    char szProfileBuffer[128];
-    char szLanguageBuffer[64];
-    //char szCPUModel[64];
+    wchar_t szLanguageBufferW[64];
+    //wchar_t szCPUModel[64];
     MEMORYSTATUS MemoryStatus;
 #endif // defined(AZ_PLATFORM_WINDOWS) || defined(AZ_PLATFORM_LINUX)
 
@@ -201,11 +201,13 @@ void CLogFile::AboutSystem()
     //////////////////////////////////////////////////////////////////////
 
     // Get system language
-    GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SENGLANGUAGE,
-        szLanguageBuffer, sizeof(szLanguageBuffer));
+    GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SENGLANGUAGE,
+        szLanguageBufferW, sizeof(szLanguageBufferW));
+    AZStd::string szLanguageBuffer;
+    AZStd::to_string(szLanguageBuffer, szLanguageBufferW);
 
     // Format and send OS information line
-    azsnprintf(szBuffer, MAX_LOGBUFFER_SIZE, "Current Language: %s ", szLanguageBuffer);
+    azsnprintf(szBuffer, MAX_LOGBUFFER_SIZE, "Current Language: %s ", szLanguageBuffer.c_str());
     CryLog("%s", szBuffer);
 #else
     QLocale locale;
@@ -294,7 +296,8 @@ AZ_POP_DISABLE_WARNING
     //////////////////////////////////////////////////////////////////////
 
     str += " (";
-    GetWindowsDirectory(szBuffer, sizeof(szBuffer));
+    GetWindowsDirectoryW(szBufferW, sizeof(szBufferW));
+    AZStd::to_string(szBuffer, MAX_LOGBUFFER_SIZE, szBufferW);
     str += szBuffer;
     str += ")";
     CryLog("%s", str.toUtf8().data());
@@ -381,12 +384,13 @@ AZ_POP_DISABLE_WARNING
 
 #if defined(AZ_PLATFORM_WINDOWS)
     EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &DisplayConfig);
-    GetPrivateProfileString("boot.description", "display.drv",
-        "(Unknown graphics card)", szProfileBuffer, sizeof(szProfileBuffer),
-        "system.ini");
+    GetPrivateProfileStringW(L"boot.description", L"display.drv",
+        L"(Unknown graphics card)", szLanguageBufferW, sizeof(szLanguageBufferW),
+        L"system.ini");
+    AZStd::to_string(szLanguageBuffer, szLanguageBufferW);
     azsnprintf(szBuffer, MAX_LOGBUFFER_SIZE, "Current display mode is %dx%dx%d, %s",
         DisplayConfig.dmPelsWidth, DisplayConfig.dmPelsHeight,
-        DisplayConfig.dmBitsPerPel, szProfileBuffer);
+        DisplayConfig.dmBitsPerPel, szLanguageBuffer.c_str());
     CryLog("%s", szBuffer);
 #else
     auto screen = QGuiApplication::primaryScreen();
diff --git a/Code/Editor/MainWindow.cpp b/Code/Editor/MainWindow.cpp
index ff322b79ac..c5352cbc4c 100644
--- a/Code/Editor/MainWindow.cpp
+++ b/Code/Editor/MainWindow.cpp
@@ -1634,7 +1634,7 @@ void MainWindow::OnUpdateConnectionStatus()
 
         status = tr("Pending Jobs : %1  Failed Jobs : %2").arg(m_connectionListener->GetJobsCount()).arg(failureCount);
 
-        statusBar->SetItem(QtUtil::ToQString("connection"), status, tooltip, icon);
+        statusBar->SetItem("connection", status, tooltip, icon);
 
         if (m_showAPDisconnectDialog && m_connectionListener->GetState() != EConnectionState::Connected)
         {
diff --git a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
index e7cc8658f0..0b33caed88 100644
--- a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
+++ b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
@@ -60,11 +60,11 @@ bool CMailer::SendMail(const char* subject,
     // Handle Recipients
     MapiRecipDesc* recipients = new MapiRecipDesc[numRecipients];
 
-    std::vector addresses;
+    std::vector addresses;
     addresses.resize(numRecipients);
     for (i = 0; i < numRecipients; i++)
     {
-        addresses[i] = string("SMTP:") + _recipients[i];
+        addresses[i] = AZStd::string("SMTP:") + _recipients[i];
     }
 
     for (i = 0; i < numRecipients; i++)
diff --git a/Code/Editor/PluginManager.cpp b/Code/Editor/PluginManager.cpp
index f03cb54fce..3432ca33ba 100644
--- a/Code/Editor/PluginManager.cpp
+++ b/Code/Editor/PluginManager.cpp
@@ -126,8 +126,8 @@ namespace
 
 bool CPluginManager::LoadPlugins(const char* pPathWithMask)
 {
-    QString strPath = QtUtil::ToQString(PathUtil::GetPath(pPathWithMask));
-    QString strMask = QString::fromUtf8(PathUtil::GetFile(pPathWithMask));
+    QString strPath = PathUtil::GetPath(pPathWithMask).c_str();
+    QString strMask = PathUtil::GetFile(pPathWithMask);
 
     CLogFile::WriteLine("[Plugin Manager] Loading plugins...");
 
diff --git a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
index 8bdfb48774..d78e6cab4e 100644
--- a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
+++ b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterPlugin.h
@@ -88,7 +88,7 @@ private:
     IEditor* const m_editor;
 
     // Tool name
-    string m_toolName;
+    AZStd::string m_toolName;
 
     // Context provider for the Asset Browser
     AZ::AssetBrowserContextProvider m_assetBrowserContextProvider;
diff --git a/Code/Editor/ResourceSelectorHost.cpp b/Code/Editor/ResourceSelectorHost.cpp
index d265b3ffbe..edab4be57c 100644
--- a/Code/Editor/ResourceSelectorHost.cpp
+++ b/Code/Editor/ResourceSelectorHost.cpp
@@ -101,10 +101,10 @@ public:
     }
 
 private:
-    typedef std::map > TTypeMap;
+    typedef std::map > TTypeMap;
     TTypeMap m_typeMap;
 
-    std::map m_globallySelectedResources;
+    std::map m_globallySelectedResources;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/Code/Editor/SelectSequenceDialog.cpp b/Code/Editor/SelectSequenceDialog.cpp
index 2566a8be82..11e30b91d7 100644
--- a/Code/Editor/SelectSequenceDialog.cpp
+++ b/Code/Editor/SelectSequenceDialog.cpp
@@ -37,7 +37,7 @@ CSelectSequenceDialog::GetItems(std::vector& outItems)
     {
         IAnimSequence* pSeq = pMovieSys->GetSequence(i);
         SItem item;
-        string fullname = pSeq->GetName();
+        AZStd::string fullname = pSeq->GetName();
         item.name = fullname.c_str();
         outItems.push_back(item);
     }
diff --git a/Code/Editor/ToolBox.cpp b/Code/Editor/ToolBox.cpp
index 77cb479873..0a1752a509 100644
--- a/Code/Editor/ToolBox.cpp
+++ b/Code/Editor/ToolBox.cpp
@@ -350,7 +350,7 @@ void CToolBoxManager::LoadShelves(QString scriptPath, QString shelvesPath, Actio
             continue;
         }
 
-        QString shelfName(PathUtil::GetFileName(files[idx].filename.toUtf8().data()));
+        QString shelfName(PathUtil::GetFileName(files[idx].filename.toUtf8().data()).c_str());
 
         AmazonToolbar toolbar(shelfName, shelfName);
         Load(shelvesPath + QString("/") + files[idx].filename, &toolbar, false, actionManager);
@@ -408,7 +408,7 @@ void CToolBoxManager::Load(QString xmlpath, AmazonToolbar* pToolbar, bool bToolb
     AZ::IO::FixedMaxPathString engineRoot = AZ::Utils::GetEnginePath();
     QDir engineDir = !engineRoot.empty() ? QDir(QString(engineRoot.c_str())) : QDir::current();
 
-    string enginePath = PathUtil::AddSlash(engineDir.absolutePath().toUtf8().data());
+    AZStd::string enginePath = PathUtil::AddSlash(engineDir.absolutePath().toUtf8().data());
 
     for (int i = 0; i < toolBoxNode->getChildCount(); ++i)
     {
@@ -434,11 +434,11 @@ void CToolBoxManager::Load(QString xmlpath, AmazonToolbar* pToolbar, bool bToolb
             continue;
         }
 
-        string shelfPath = PathUtil::GetParentDirectory(xmlpath.toUtf8().data());
-        string fullIconPath = enginePath + PathUtil::AddSlash(shelfPath.c_str());
+        AZStd::string shelfPath = PathUtil::GetParentDirectory(xmlpath.toUtf8().data());
+        AZStd::string fullIconPath = enginePath + PathUtil::AddSlash(shelfPath.c_str());
         fullIconPath.append(iconPath.toUtf8().data());
 
-        pMacro->SetIconPath(fullIconPath);
+        pMacro->SetIconPath(fullIconPath.c_str());
 
         QString toolTip(macroNode->getAttr("tooltip"));
         pMacro->action()->setToolTip(toolTip);
diff --git a/Code/Editor/TrackView/CommentKeyUIControls.cpp b/Code/Editor/TrackView/CommentKeyUIControls.cpp
index 4c5dc10bfa..91fa969e20 100644
--- a/Code/Editor/TrackView/CommentKeyUIControls.cpp
+++ b/Code/Editor/TrackView/CommentKeyUIControls.cpp
@@ -52,7 +52,7 @@ public:
         CFileUtil::ScanDirectory((Path::GetEditingGameDataFolder() + "/Fonts/").c_str(), "*.xml", fa, true);
         for (size_t i = 0; i < fa.size(); ++i)
         {
-            string name = fa[i].filename.toUtf8().data();
+            AZStd::string name = fa[i].filename.toUtf8().data();
             PathUtil::RemoveExtension(name);
             mv_font->AddEnumItem(name.c_str(), name.c_str());
         }
diff --git a/Code/Editor/TrackView/SequenceKeyUIControls.cpp b/Code/Editor/TrackView/SequenceKeyUIControls.cpp
index 5ef5a9c4ab..e280f06dc7 100644
--- a/Code/Editor/TrackView/SequenceKeyUIControls.cpp
+++ b/Code/Editor/TrackView/SequenceKeyUIControls.cpp
@@ -91,7 +91,7 @@ bool CSequenceKeyUIControls::OnKeySelectionChange(CTrackViewKeyBundle& selectedK
                 bool bNotParent = !bNotMe || pCurrentSequence->IsAncestorOf(pSequence) == false;
                 if (bNotMe && bNotParent)
                 {
-                    string seqName = pCurrentSequence->GetName();
+                    AZStd::string seqName = pCurrentSequence->GetName();
 
                     QString ownerIdString = CTrackViewDialog::GetEntityIdAsString(pCurrentSequence->GetSequenceComponentEntityId());
                     mv_sequence->AddEnumItem(seqName.c_str(), ownerIdString);
diff --git a/Code/Editor/TrackView/TrackViewAnimNode.cpp b/Code/Editor/TrackView/TrackViewAnimNode.cpp
index c66ea5635c..abff423ab7 100644
--- a/Code/Editor/TrackView/TrackViewAnimNode.cpp
+++ b/Code/Editor/TrackView/TrackViewAnimNode.cpp
@@ -1010,13 +1010,13 @@ bool CTrackViewAnimNode::SetName(const char* pName)
         }
     }
 
-    string oldName = GetName();
+    AZStd::string oldName = GetName();
     m_animNode->SetName(pName);
 
     CTrackViewSequence* sequence = GetSequence();
     AZ_Assert(sequence, "Nodes should never have a null sequence.");
 
-    sequence->OnNodeRenamed(this, oldName);
+    sequence->OnNodeRenamed(this, oldName.c_str());
 
     return true;
 }
diff --git a/Code/Editor/TrackView/TrackViewFindDlg.cpp b/Code/Editor/TrackView/TrackViewFindDlg.cpp
index 3d6e93fb05..18d574bf0b 100644
--- a/Code/Editor/TrackView/TrackViewFindDlg.cpp
+++ b/Code/Editor/TrackView/TrackViewFindDlg.cpp
@@ -61,7 +61,7 @@ void CTrackViewFindDlg::FillData()
             ObjName obj;
             obj.m_objName = pNode->GetName();
             obj.m_directorName = pNode->HasDirectorAsParent() ? pNode->HasDirectorAsParent()->GetName() : "";
-            string fullname = seq->GetName();
+            AZStd::string fullname = seq->GetName();
             obj.m_seqName = fullname.c_str();
             m_objs.push_back(obj);
         }
diff --git a/Code/Editor/TrackView/TrackViewNodes.cpp b/Code/Editor/TrackView/TrackViewNodes.cpp
index 90e5598876..000bdf21d0 100644
--- a/Code/Editor/TrackView/TrackViewNodes.cpp
+++ b/Code/Editor/TrackView/TrackViewNodes.cpp
@@ -2516,7 +2516,7 @@ int CTrackViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, cons
     if (const char* pCh = strstr(nodeName, ".["))
     {
         char matPath[MAX_PATH];
-        azstrcpy(matPath, nodeName, (size_t)(pCh - nodeName));
+        azstrncpy(matPath, nodeName, (size_t)(pCh - nodeName));
         matName = matPath;
         pCh += 2;
         if ((*pCh) != 0)
diff --git a/Code/Editor/TrackView/TrackViewSequence.cpp b/Code/Editor/TrackView/TrackViewSequence.cpp
index 7ccecd7292..3647c554dc 100644
--- a/Code/Editor/TrackView/TrackViewSequence.cpp
+++ b/Code/Editor/TrackView/TrackViewSequence.cpp
@@ -1073,7 +1073,7 @@ std::deque CTrackViewSequence::GetMatchingTracks(CTrackViewAni
 {
     std::deque matchingTracks;
 
-    const string trackName = trackNode->getAttr("name");
+    const AZStd::string trackName = trackNode->getAttr("name");
 
     CAnimParamType animParamType;
     animParamType.LoadFromXml(trackNode);
@@ -1133,11 +1133,11 @@ void CTrackViewSequence::GetMatchedPasteLocationsRec(std::vectorgetChild(nodeIndex);
-        const string tagName = xmlChildNode->getTag();
+        const AZStd::string tagName = xmlChildNode->getTag();
 
         if (tagName == "Node")
         {
-            const string nodeName = xmlChildNode->getAttr("name");
+            const AZStd::string nodeName = xmlChildNode->getAttr("name");
 
             int nodeType = static_cast(AnimNodeType::Invalid);
             xmlChildNode->getAttr("type", nodeType);
@@ -1159,7 +1159,7 @@ void CTrackViewSequence::GetMatchedPasteLocationsRec(std::vectorgetAttr("name");
+            const AZStd::string trackName = xmlChildNode->getAttr("name");
 
             CAnimParamType trackParamType;
             trackParamType.Serialize(xmlChildNode, true);
diff --git a/Code/Editor/TrackViewNewSequenceDialog.cpp b/Code/Editor/TrackViewNewSequenceDialog.cpp
index 30691b0215..0efc7a932e 100644
--- a/Code/Editor/TrackViewNewSequenceDialog.cpp
+++ b/Code/Editor/TrackViewNewSequenceDialog.cpp
@@ -81,7 +81,7 @@ void CTVNewSequenceDialog::OnOK()
     for (int k = 0; k < GetIEditor()->GetSequenceManager()->GetCount(); ++k)
     {
         CTrackViewSequence* pSequence = GetIEditor()->GetSequenceManager()->GetSequenceByIndex(k);
-        QString fullname = QtUtil::ToQString(pSequence->GetName());
+        QString fullname = pSequence->GetName();
 
         if (fullname.compare(m_sequenceName, Qt::CaseInsensitive) == 0)
         {
diff --git a/Code/Editor/Util/AutoDirectoryRestoreFileDialog.cpp b/Code/Editor/Util/AutoDirectoryRestoreFileDialog.cpp
index f5ba0c507d..a14303cd69 100644
--- a/Code/Editor/Util/AutoDirectoryRestoreFileDialog.cpp
+++ b/Code/Editor/Util/AutoDirectoryRestoreFileDialog.cpp
@@ -45,7 +45,7 @@ int CAutoDirectoryRestoreFileDialog::exec()
         foreach(const QString&fileName, selectedFiles())
         {
             QFileInfo info(fileName);
-            if (!CryStringUtils::IsValidFileName(info.fileName().toStdString().c_str()))
+            if (!AZ::StringFunc::Path::IsValid(info.fileName().toStdString().c_str()))
             {
                 QMessageBox::warning(this, tr("Error"), tr("Please select a valid file name (standard English alphanumeric characters only)"));
                 problem = true;
diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp
index d57d690154..f5535f5590 100644
--- a/Code/Editor/Util/FileUtil.cpp
+++ b/Code/Editor/Util/FileUtil.cpp
@@ -264,7 +264,7 @@ void CFileUtil::EditTextureFile(const char* textureFile, [[maybe_unused]] bool b
     }
 
     bool failedToLaunch = true;
-    QByteArray textureEditorPath = gSettings.textureEditor.toUtf8();
+    const QString& textureEditorPath = gSettings.textureEditor;
 
     // Give the user a warning if they don't have a texture editor configured
     if (textureEditorPath.isEmpty())
@@ -278,8 +278,7 @@ void CFileUtil::EditTextureFile(const char* textureFile, [[maybe_unused]] bool b
     // Use the Win32 API calls to open the right editor; the OS knows how to do this even better than
     // Qt does.
     QString fullTexturePathFixedForWindows = QString(fullTexturePath.data()).replace('/', '\\');
-    QByteArray fullTexturePathFixedForWindowsUtf8 = fullTexturePathFixedForWindows.toUtf8();
-    HINSTANCE hInst = ShellExecute(NULL, "open", textureEditorPath.data(), fullTexturePathFixedForWindowsUtf8.data(), NULL, SW_SHOWNORMAL);
+    HINSTANCE hInst = ShellExecuteW(NULL, L"open", textureEditorPath.toStdWString().c_str(), fullTexturePathFixedForWindows.toStdWString().c_str(), NULL, SW_SHOWNORMAL);
     failedToLaunch = ((DWORD_PTR)hInst <= 32);
 #elif defined(AZ_PLATFORM_MAC)
     failedToLaunch = QProcess::execute(QString("/usr/bin/open"), {"-a", gSettings.textureEditor, QString(fullTexturePath.data()) }) != 0;
@@ -298,7 +297,7 @@ void CFileUtil::EditTextureFile(const char* textureFile, [[maybe_unused]] bool b
 //////////////////////////////////////////////////////////////////////////
 bool CFileUtil::EditMayaFile(const char* filepath, const bool bExtractFromPak, const bool bUseGameFolder)
 {
-    QString dosFilepath = QtUtil::ToQString(PathUtil::ToDosPath(filepath));
+    QString dosFilepath = PathUtil::ToDosPath(filepath).c_str();
     if (bExtractFromPak)
     {
         ExtractFile(dosFilepath);
@@ -313,7 +312,7 @@ bool CFileUtil::EditMayaFile(const char* filepath, const bool bExtractFromPak, c
             dosFilepath = sGameFolder + '\\' + filepath;
         }
 
-        dosFilepath = PathUtil::ToDosPath(dosFilepath.toUtf8().data());
+        dosFilepath = PathUtil::ToDosPath(dosFilepath.toUtf8().data()).c_str();
     }
 
     const char* engineRoot;
@@ -1304,7 +1303,7 @@ IFileUtil::ECopyTreeResult CFileUtil::CopyTree(const QString& strSourceDirectory
     // all with the same names and all with the same files names inside. If you would make a depth-first search
     // you could end up with the files from the deepest folder in ALL your folders.
 
-    std::vector ignoredPatterns;
+    std::vector ignoredPatterns;
     StringHelpers::Split(ignoreFilesAndFolders, "|", false, ignoredPatterns);
 
     QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags;
@@ -2218,7 +2217,9 @@ uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*=
         return SCC_FILE_ATTRIBUTE_READONLY | SCC_FILE_ATTRIBUTE_INPAK;
     }
 
-    DWORD dwAttrib = ::GetFileAttributes(file.GetAdjustedFilename());
+    AZStd::wstring fileW;
+    AZStd::to_wstring(fileW, file.GetAdjustedFilename());
+    DWORD dwAttrib = ::GetFileAttributesW(fileW.c_str());
     if (dwAttrib == INVALID_FILE_ATTRIBUTES)
     {
         return SCC_FILE_ATTRIBUTE_INVALID;
diff --git a/Code/Editor/Util/ImageASC.cpp b/Code/Editor/Util/ImageASC.cpp
index 69a6892c65..e6e947f342 100644
--- a/Code/Editor/Util/ImageASC.cpp
+++ b/Code/Editor/Util/ImageASC.cpp
@@ -24,8 +24,7 @@ bool CImageASC::Save(const QString& fileName, const CFloatImage& image)
     uint32 height = image.GetHeight();
     float* pixels = image.GetData();
 
-    string fileHeader;
-    fileHeader.Format(
+    AZStd::string fileHeader = AZStd::string::format(
         // Number of columns and rows in the data
         "ncols %d\n"
         "nrows %d\n"
diff --git a/Code/Editor/Util/ImageTIF.cpp b/Code/Editor/Util/ImageTIF.cpp
index 9040306a44..7029609825 100644
--- a/Code/Editor/Util/ImageTIF.cpp
+++ b/Code/Editor/Util/ImageTIF.cpp
@@ -399,8 +399,8 @@ bool CImageTIF::SaveRAW(const QString& fileName, const void* pData, int width, i
 
         if (preset && preset[0])
         {
-            string tiffphotoshopdata, valueheader;
-            string presetkeyvalue = string("/preset=") + string(preset);
+            AZStd::string tiffphotoshopdata, valueheader;
+            AZStd::string presetkeyvalue = AZStd::string("/preset=") + AZStd::string(preset);
 
             valueheader.push_back('\x1C');
             valueheader.push_back('\x02');
@@ -472,7 +472,7 @@ const char* CImageTIF::GetPreset(const QString& fileName)
             libtiffDummyWriteProc, libtiffDummySeekProc,
             libtiffDummyCloseProc, libtiffDummySizeProc, libtiffDummyMapFileProc, libtiffDummyUnmapFileProc);
 
-    string strReturn;
+    AZStd::string strReturn;
     char* preset = NULL;
     int size;
     if (tif)
diff --git a/Code/Editor/Util/ImageUtil.cpp b/Code/Editor/Util/ImageUtil.cpp
index 1b985c82f9..3ac15495cc 100644
--- a/Code/Editor/Util/ImageUtil.cpp
+++ b/Code/Editor/Util/ImageUtil.cpp
@@ -86,8 +86,7 @@ bool CImageUtil::SavePGM(const QString& fileName, const CImageEx& image)
     uint32* pixels = image.GetData();
 
     // Create the file header.
-    string fileHeader;
-    fileHeader.Format(
+    AZStd::string fileHeader = AZStd::string::format(
         // P2 = PGM header for ASCII output.  (P5 is PGM header for binary output)
         "P2\n"
         // width and height of the image
diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp
index bf607e475e..a1e2b4ae08 100644
--- a/Code/Editor/Util/StringHelpers.cpp
+++ b/Code/Editor/Util/StringHelpers.cpp
@@ -7,117 +7,10 @@
  */
 
 
-#include 
 #include "StringHelpers.h"
 #include "Util.h"
-#include "StringUtils.h" // From CryCommon
-#include "UnicodeFunctions.h"
-#include 
-#include 
-
-#include  // WideCharToMultibyte(), CP_UTF8, etc.
-#include 
-
-static inline char ToLower(const char c)
-{
-    return tolower(c);
-}
-
-static inline wchar_t ToLower(const wchar_t c)
-{
-    return towlower(c);
-}
-
-
-static inline char ToUpper(const char c)
-{
-    return toupper(c);
-}
-
-static inline wchar_t ToUpper(const wchar_t c)
-{
-    return towupper(c);
-}
-
-
-static inline int Vscprintf(const char* format, va_list argList)
-{
-#if defined(AZ_PLATFORM_WINDOWS)
-    return _vscprintf(format, argList);
-#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX)
-    int retval;
-    va_list argcopy;
-    va_copy(argcopy, argList);
-    retval = azvsnprintf(NULL, 0, format, argcopy);
-    va_end(argcopy);
-    return retval;
-#else
-    #error Not supported!
-#endif
-}
-
-static inline int Vscprintf(const wchar_t* format, va_list argList)
-{
-#if defined(AZ_PLATFORM_WINDOWS)
-    return _vscwprintf(format, argList);
-#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX)
-    int retval;
-    va_list argcopy;
-    va_copy(argcopy, argList);
-    retval = azvsnwprintf(NULL, 0, format, argcopy);
-    va_end(argcopy);
-    return retval;
-#else
-    #error Not supported!
-#endif
-}
-
-
-static inline int Vsnprintf_s(char* str, size_t sizeInBytes, [[maybe_unused]] size_t count, const char* format, va_list argList)
-{
-    return azvsnprintf(str, sizeInBytes, format, argList);
-}
-
-static inline int Vsnprintf_s(wchar_t* str, size_t sizeInBytes, [[maybe_unused]] size_t count, const wchar_t* format, va_list argList)
-{
-    return azvsnwprintf(str, sizeInBytes, format, argList);
-}
-
-
-int StringHelpers::Compare(const AZStd::string& str0, const AZStd::string& str1)
-{
-    const size_t minLength = Util::getMin(str0.length(), str1.length());
-    const int result = std::memcmp(str0.c_str(), str1.c_str(), minLength);
-    if (result)
-    {
-        return result;
-    }
-    else
-    {
-        return (str0.length() == str1.length())
-               ? 0
-               : ((str0.length() < str1.length()) ? -1 : +1);
-    }
-}
-
-int StringHelpers::Compare(const wstring& str0, const wstring& str1)
-{
-    const size_t minLength = Util::getMin(str0.length(), str1.length());
-    for (size_t i = 0; i < minLength; ++i)
-    {
-        const wchar_t c0 = str0[i];
-        const wchar_t c1 = str1[i];
-        if (c0 != c1)
-        {
-            return (c0 < c1) ? -1 : 1;
-        }
-    }
-
-    return (str0.length() == str1.length())
-           ? 0
-           : ((str0.length() < str1.length()) ? -1 : +1);
-}
 
+#include 
 
 int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
 {
@@ -135,7 +28,7 @@ int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::str
     }
 }
 
-int StringHelpers::CompareIgnoreCase(const wstring& str0, const wstring& str1)
+int StringHelpers::CompareIgnoreCase(const AZStd::wstring& str0, const AZStd::wstring& str1)
 {
     const size_t minLength = Util::getMin(str0.length(), str1.length());
     for (size_t i = 0; i < minLength; ++i)
@@ -153,402 +46,6 @@ int StringHelpers::CompareIgnoreCase(const wstring& str0, const wstring& str1)
            : ((str0.length() < str1.length()) ? -1 : +1);
 }
 
-
-bool StringHelpers::Equals(const AZStd::string& str0, const AZStd::string& str1)
-{
-    if (str0.length() != str1.length())
-    {
-        return false;
-    }
-    return std::memcmp(str0.c_str(), str1.c_str(), str1.length()) == 0;
-}
-
-bool StringHelpers::Equals(const wstring& str0, const wstring& str1)
-{
-    if (str0.length() != str1.length())
-    {
-        return false;
-    }
-    return std::memcmp(str0.c_str(), str1.c_str(), str1.length() * sizeof(wstring::value_type)) == 0;
-}
-
-
-bool StringHelpers::EqualsIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
-{
-    if (str0.length() != str1.length())
-    {
-        return false;
-    }
-    return azmemicmp(str0.c_str(), str1.c_str(), str1.length()) == 0;
-}
-
-bool StringHelpers::EqualsIgnoreCase(const wstring& str0, const wstring& str1)
-{
-    const size_t str1Length = str1.length();
-    if (str0.length() != str1Length)
-    {
-        return false;
-    }
-    for (size_t i = 0; i < str1Length; ++i)
-    {
-        if (towlower(str0[i]) != towlower(str1[i]))
-        {
-            return false;
-        }
-    }
-    return true;
-}
-
-
-bool StringHelpers::StartsWith(const AZStd::string& str, const AZStd::string& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return std::memcmp(str.c_str(), pattern.c_str(), pattern.length()) == 0;
-}
-
-bool StringHelpers::StartsWith(const wstring& str, const wstring& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return std::memcmp(str.c_str(), pattern.c_str(), pattern.length() * sizeof(wstring::value_type)) == 0;
-}
-
-
-bool StringHelpers::StartsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return azmemicmp(str.c_str(), pattern.c_str(), pattern.length()) == 0;
-}
-
-bool StringHelpers::StartsWithIgnoreCase(const wstring& str, const wstring& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    for (size_t i = 0; i < patternLength; ++i)
-    {
-        if (towlower(str[i]) != towlower(pattern[i]))
-        {
-            return false;
-        }
-    }
-    return true;
-}
-
-
-bool StringHelpers::EndsWith(const AZStd::string& str, const AZStd::string& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return std::memcmp(str.c_str() + str.length() - pattern.length(), pattern.c_str(), pattern.length()) == 0;
-}
-
-bool StringHelpers::EndsWith(const wstring& str, const wstring& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return std::memcmp(str.c_str() + str.length() - pattern.length(), pattern.c_str(), pattern.length() * sizeof(wstring::value_type)) == 0;
-}
-
-
-bool StringHelpers::EndsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
-{
-    if (str.length() < pattern.length())
-    {
-        return false;
-    }
-    return azmemicmp(str.c_str() + str.length() - pattern.length(), pattern.c_str(), pattern.length()) == 0;
-}
-
-bool StringHelpers::EndsWithIgnoreCase(const wstring& str, const wstring& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    for (size_t i = str.length() - patternLength, j = 0; i < patternLength; ++i, ++j)
-    {
-        if (towlower(str[i]) != towlower(pattern[j]))
-        {
-            return false;
-        }
-    }
-    return true;
-}
-
-
-bool StringHelpers::Contains(const AZStd::string& str, const AZStd::string& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    const size_t n = str.length() - patternLength + 1;
-    for (size_t i = 0; i < n; ++i)
-    {
-        if (std::memcmp(str.c_str() + i, pattern.c_str(), patternLength) == 0)
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-bool StringHelpers::Contains(const wstring& str, const wstring& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    const size_t n = str.length() - patternLength + 1;
-    for (size_t i = 0; i < n; ++i)
-    {
-        if (std::memcmp(str.c_str() + i, pattern.c_str(), patternLength * sizeof(wstring::value_type)) == 0)
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-
-bool StringHelpers::ContainsIgnoreCase(const AZStd::string& str, const AZStd::string& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-    const size_t n = str.length() - patternLength + 1;
-    for (size_t i = 0; i < n; ++i)
-    {
-        if (azmemicmp(str.c_str() + i, pattern.c_str(), patternLength) == 0)
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-bool StringHelpers::ContainsIgnoreCase(const wstring& str, const wstring& pattern)
-{
-    const size_t patternLength = pattern.length();
-    if (patternLength == 0)
-    {
-        return true;
-    }
-    if (str.length() < patternLength)
-    {
-        return false;
-    }
-
-    const wstring::value_type firstPatternLetter = towlower(pattern[0]);
-    const size_t n = str.length() - patternLength + 1;
-    for (size_t i = 0; i < n; ++i)
-    {
-        bool match = true;
-        for (size_t j = 0; j < patternLength; ++j)
-        {
-            if (towlower(str[i + j]) != towlower(pattern[j]))
-            {
-                match = false;
-                break;
-            }
-        }
-        if (match)
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-string StringHelpers::TrimLeft(const AZStd::string& s)
-{
-    const size_t first = s.find_first_not_of(" \r\t");
-    return (first == s.npos) ? string() : s.substr(first);
-}
-
-wstring StringHelpers::TrimLeft(const wstring& s)
-{
-    const size_t first = s.find_first_not_of(L" \r\t");
-    return (first == s.npos) ? wstring() : s.substr(first);
-}
-
-
-string StringHelpers::TrimRight(const AZStd::string& s)
-{
-    const size_t last = s.find_last_not_of(" \r\t");
-    return (last == s.npos) ? s : s.substr(0, last + 1);
-}
-
-wstring StringHelpers::TrimRight(const wstring& s)
-{
-    const size_t last = s.find_last_not_of(L" \r\t");
-    return (last == s.npos) ? s : s.substr(0, last + 1);
-}
-
-
-string StringHelpers::Trim(const AZStd::string& s)
-{
-    return TrimLeft(TrimRight(s));
-}
-
-wstring StringHelpers::Trim(const wstring& s)
-{
-    return TrimLeft(TrimRight(s));
-}
-
-
-template 
-static inline TS RemoveDuplicateSpaces_Tpl(const TS& s)
-{
-    TS res;
-    bool spaceFound = false;
-
-    for (size_t i = 0, n = s.length(); i < n; ++i)
-    {
-        if ((s[i] == ' ') || (s[i] == '\r') || (s[i] == '\t'))
-        {
-            spaceFound = true;
-        }
-        else
-        {
-            if (spaceFound)
-            {
-                res += ' ';
-                spaceFound = false;
-            }
-            res += s[i];
-        }
-    }
-
-    if (spaceFound)
-    {
-        res += ' ';
-    }
-    return res;
-}
-
-string StringHelpers::RemoveDuplicateSpaces(const AZStd::string& s)
-{
-    return RemoveDuplicateSpaces_Tpl(s);
-}
-
-wstring StringHelpers::RemoveDuplicateSpaces(const wstring& s)
-{
-    return RemoveDuplicateSpaces_Tpl(s);
-}
-
-
-template 
-static inline TS MakeLowerCase_Tpl(const TS& s)
-{
-    TS copy;
-    copy.reserve(s.length());
-    for (typename TS::const_iterator it = s.begin(), end = s.end(); it != end; ++it)
-    {
-        copy.append(1, ToLower(*it));
-    }
-    return copy;
-}
-
-string StringHelpers::MakeLowerCase(const AZStd::string& s)
-{
-    return MakeLowerCase_Tpl(s);
-}
-
-wstring StringHelpers::MakeLowerCase(const wstring& s)
-{
-    return MakeLowerCase_Tpl(s);
-}
-
-
-template 
-static inline TS MakeUpperCase_Tpl(const TS& s)
-{
-    TS copy;
-    copy.reserve(s.length());
-    for (typename TS::const_iterator it = s.begin(), end = s.end(); it != end; ++it)
-    {
-        copy.append(1, ToUpper(*it));
-    }
-    return copy;
-}
-
-string StringHelpers::MakeUpperCase(const AZStd::string& s)
-{
-    return MakeUpperCase_Tpl(s);
-}
-
-wstring StringHelpers::MakeUpperCase(const wstring& s)
-{
-    return MakeUpperCase_Tpl(s);
-}
-
-
-template 
-static inline TS Replace_Tpl(const TS& s, const typename TS::value_type oldChar, const typename TS::value_type newChar)
-{
-    TS copy;
-    copy.reserve(s.length());
-    for (typename TS::const_iterator it = s.begin(), end = s.end(); it != end; ++it)
-    {
-        const typename TS::value_type c = (*it);
-        copy.append(1, ((c == oldChar) ? newChar : c));
-    }
-    return copy;
-}
-
-string StringHelpers::Replace(const AZStd::string& s, char oldChar, char newChar)
-{
-    return Replace_Tpl(s, oldChar, newChar);
-}
-
-wstring StringHelpers::Replace(const wstring& s, wchar_t oldChar, wchar_t newChar)
-{
-    return Replace_Tpl(s, oldChar, newChar);
-}
-
-
-void StringHelpers::ConvertStringByRef(string& out, const AZStd::string& in)
-{
-    out = in;
-}
-
-void StringHelpers::ConvertStringByRef(wstring& out, const AZStd::string& in)
-{
-    Unicode::Convert(out, in);
-}
-
-void StringHelpers::ConvertStringByRef(string& out, const wstring& in)
-{
-    Unicode::Convert(out, in);
-}
-
-void StringHelpers::ConvertStringByRef(wstring& out, const wstring& in)
-{
-    out = in;
-}
-
-
 template 
 static inline void Split_Tpl(const TS& str, const TS& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
@@ -588,348 +85,12 @@ static inline void Split_Tpl(const TS& str, const TS& separator, bool bReturnEmp
     }
 }
 
-
-template 
-static inline void SplitByAnyOf_Tpl(const TS& str, const TS& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
-{
-    if (str.empty())
-    {
-        return;
-    }
-
-    if (separators.empty())
-    {
-        for (size_t i = 0; i < str.length(); ++i)
-        {
-            outParts.push_back(str.substr(i, 1));
-        }
-        return;
-    }
-
-    size_t partStart = 0;
-
-    for (;; )
-    {
-        const size_t pos = str.find_first_of(separators, partStart);
-        if (pos == TS::npos)
-        {
-            break;
-        }
-        if (bReturnEmptyPartsToo || (pos > partStart))
-        {
-            outParts.push_back(str.substr(partStart, pos - partStart));
-        }
-        partStart = pos + 1;
-    }
-
-    if (bReturnEmptyPartsToo || (partStart < str.length()))
-    {
-        outParts.push_back(str.substr(partStart, str.length() - partStart));
-    }
-}
-
-
-
-void StringHelpers::Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
+void StringHelpers::Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
     Split_Tpl(str, separator, bReturnEmptyPartsToo, outParts);
 }
 
-void StringHelpers::Split(const wstring& str, const wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
+void StringHelpers::Split(const AZStd::wstring& str, const AZStd::wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts)
 {
     Split_Tpl(str, separator, bReturnEmptyPartsToo, outParts);
 }
-
-
-void StringHelpers::SplitByAnyOf(const AZStd::string& str, const AZStd::string& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
-{
-    SplitByAnyOf_Tpl(str, separators, bReturnEmptyPartsToo, outParts);
-}
-
-void StringHelpers::SplitByAnyOf(const wstring& str, const wstring& separators, bool bReturnEmptyPartsToo, std::vector& outParts)
-{
-    SplitByAnyOf_Tpl(str, separators, bReturnEmptyPartsToo, outParts);
-}
-
-
-template 
-static inline TS FormatVA_Tpl(const typename TS::value_type* const format, va_list parg)
-{
-    if ((format == 0) || (format[0] == 0))
-    {
-        return TS();
-    }
-
-    std::vector bf;
-    size_t capacity = 0;
-
-    size_t wantedCapacity = Vscprintf(format, parg);
-    wantedCapacity += 2;  // '+ 2' to prevent uncertainty when Vsnprintf_s() returns 'size - 1'
-
-    for (;; )
-    {
-        if (wantedCapacity > capacity)
-        {
-            capacity = wantedCapacity;
-            bf.resize(capacity + 1);
-        }
-
-        const int countWritten = Vsnprintf_s(&bf[0], capacity + 1, _TRUNCATE, format, parg);
-
-        if ((countWritten >= 0) && (capacity > (size_t)countWritten + 1))
-        {
-            bf[countWritten] = 0;
-            return TS(&bf[0]);
-        }
-
-        wantedCapacity = capacity * 2;
-    }
-}
-
-string StringHelpers::FormatVA(const char* const format, va_list parg)
-{
-    return FormatVA_Tpl(format, parg);
-}
-
-wstring StringHelpers::FormatVA(const wchar_t* const format, va_list parg)
-{
-    return FormatVA_Tpl(format, parg);
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-template 
-static inline void SafeCopy_Tpl(TC* const pDstBuffer, const size_t dstBufferSizeInBytes, const TC* const pSrc)
-{
-    if (dstBufferSizeInBytes >= sizeof(TC))
-    {
-        const size_t n = dstBufferSizeInBytes / sizeof(TC) - 1;
-        size_t i;
-        for (i = 0; i < n && pSrc[i]; ++i)
-        {
-            pDstBuffer[i] = pSrc[i];
-        }
-        pDstBuffer[i] = 0;
-    }
-}
-
-template 
-static inline void SafeCopyPadZeros_Tpl(TC* const pDstBuffer, const size_t dstBufferSizeInBytes, const TC* const pSrc)
-{
-    if (dstBufferSizeInBytes > 0)
-    {
-        const size_t n = (dstBufferSizeInBytes < sizeof(TC)) ? 0 : dstBufferSizeInBytes / sizeof(TC) - 1;
-        size_t i;
-        for (i = 0; i < n && pSrc[i]; ++i)
-        {
-            pDstBuffer[i] = pSrc[i];
-        }
-        memset(&pDstBuffer[i], 0, dstBufferSizeInBytes - i * sizeof(TC));
-    }
-}
-
-
-void StringHelpers::SafeCopy(char* const pDstBuffer, const size_t dstBufferSizeInBytes, const char* const pSrc)
-{
-    SafeCopy_Tpl(pDstBuffer, dstBufferSizeInBytes, pSrc);
-}
-
-void StringHelpers::SafeCopy(wchar_t* const pDstBuffer, const size_t dstBufferSizeInBytes, const wchar_t* const pSrc)
-{
-    SafeCopy_Tpl(pDstBuffer, dstBufferSizeInBytes, pSrc);
-}
-
-
-void StringHelpers::SafeCopyPadZeros(char* const pDstBuffer, const size_t dstBufferSizeInBytes, const char* const pSrc)
-{
-    SafeCopyPadZeros_Tpl(pDstBuffer, dstBufferSizeInBytes, pSrc);
-}
-
-void StringHelpers::SafeCopyPadZeros(wchar_t* const pDstBuffer, const size_t dstBufferSizeInBytes, const wchar_t* const pSrc)
-{
-    SafeCopyPadZeros_Tpl(pDstBuffer, dstBufferSizeInBytes, pSrc);
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-bool StringHelpers::Utf16ContainsAsciiOnly(const wchar_t* wstr)
-{
-    while (*wstr)
-    {
-        if (*wstr > 127 || *wstr < 0)
-        {
-            return false;
-        }
-        ++wstr;
-    }
-    return true;
-}
-
-
-string StringHelpers::ConvertAsciiUtf16ToAscii(const wchar_t* wstr)
-{
-    const size_t len = wcslen(wstr);
-
-    string result;
-    result.reserve(len);
-
-    for (size_t i = 0; i < len; ++i)
-    {
-        result.push_back(wstr[i] & 0x7F);
-    }
-
-    return result;
-}
-
-
-wstring StringHelpers::ConvertAsciiToUtf16(const char* str)
-{
-    const size_t len = strlen(str);
-
-    wstring result;
-    result.reserve(len);
-
-    for (size_t i = 0; i < len; ++i)
-    {
-        result.push_back(str[i] & 0x7F);
-    }
-
-    return result;
-}
-
-#if defined(AZ_PLATFORM_WINDOWS)
-static string ConvertUtf16ToMultibyte(const wchar_t* wstr, uint codePage, char badChar)
-{
-    if (wstr[0] == 0)
-    {
-        return string();
-    }
-
-    const int len = aznumeric_caster(wcslen(wstr));
-
-    // Request needed buffer size, in bytes
-    int neededByteCount = WideCharToMultiByte(
-            codePage,
-            0,
-            wstr,
-            len,
-            0,
-            0,
-            ((badChar && codePage != CP_UTF8) ? &badChar : NULL),
-            NULL);
-    if (neededByteCount <= 0)
-    {
-        return string();
-    }
-    ++neededByteCount; // extra space for terminating zero
-
-    std::vector buffer(neededByteCount);
-
-    const int byteCount = WideCharToMultiByte(
-            codePage,
-            0,
-            wstr,
-            len,
-            &buffer[0], // output buffer
-            neededByteCount - 1, // size of the output buffer in bytes
-            ((badChar && codePage != CP_UTF8) ? &badChar : NULL),
-            NULL);
-    if (byteCount != neededByteCount - 1)
-    {
-        return string();
-    }
-
-    buffer[byteCount] = 0;
-
-    return string(&buffer[0]);
-}
-
-
-static wstring ConvertMultibyteToUtf16(const char* str, uint codePage)
-{
-    if (str[0] == 0)
-    {
-        return wstring();
-    }
-
-    const int len = aznumeric_caster(strlen(str));
-
-    // Request needed buffer size, in characters
-    int neededCharCount = MultiByteToWideChar(
-            codePage,
-            0,
-            str,
-            len,
-            0,
-            0);
-    if (neededCharCount <= 0)
-    {
-        return wstring();
-    }
-    ++neededCharCount; // extra space for terminating zero
-
-    std::vector wbuffer(neededCharCount);
-
-    const int charCount = MultiByteToWideChar(
-            codePage,
-            0,
-            str,
-            len,
-            &wbuffer[0], // output buffer
-            neededCharCount - 1); // size of the output buffer in characters
-    if (charCount != neededCharCount - 1)
-    {
-        return wstring();
-    }
-
-    wbuffer[charCount] = 0;
-
-    return wstring(&wbuffer[0]);
-}
-
-
-wstring StringHelpers::ConvertUtf8ToUtf16(const char* str)
-{
-    return ConvertMultibyteToUtf16(str, CP_UTF8);
-}
-
-
-string StringHelpers::ConvertUtf16ToUtf8(const wchar_t* wstr)
-{
-    return ConvertUtf16ToMultibyte(wstr, CP_UTF8, 0);
-}
-
-
-wstring StringHelpers::ConvertAnsiToUtf16(const char* str)
-{
-    return ConvertMultibyteToUtf16(str, CP_ACP);
-}
-
-
-string StringHelpers::ConvertUtf16ToAnsi(const wchar_t* wstr, char badChar)
-{
-    return ConvertUtf16ToMultibyte(wstr, CP_ACP, badChar);
-}
-#endif  //AZ_PLATFORM_WINDOWS
-
-string StringHelpers::ConvertAnsiToAscii(const char* str, char badChar)
-{
-    const size_t len = strlen(str);
-
-    string result;
-    result.reserve(len);
-
-    for (size_t i = 0; i < len; ++i)
-    {
-        char c = str[i];
-        if (c < 0 || c > 127)
-        {
-            c = badChar;
-        }
-        result.push_back(c);
-    }
-
-    return result;
-}
-
-// eof
diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h
index ec5515fbc9..0e393e92dd 100644
--- a/Code/Editor/Util/StringHelpers.h
+++ b/Code/Editor/Util/StringHelpers.h
@@ -13,193 +13,13 @@
 
 namespace StringHelpers
 {
-    // compares two strings to see if they are the same or different, case sensitive
-    // returns 0 if the strings are the same, a -1 if the first string is bigger, or a 1 if the second string is bigger
-    int Compare(const AZStd::string& str0, const AZStd::string& str1);
-    int Compare(const wstring& str0, const wstring& str1);
-
     // compares two strings to see if they are the same or different, case is ignored
     // returns 0 if the strings are the same, a -1 if the first string is bigger, or a 1 if the second string is bigger
     int CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1);
-    int CompareIgnoreCase(const wstring& str0, const wstring& str1);
+    int CompareIgnoreCase(const AZStd::wstring& str0, const AZStd::wstring& str1);
+  
+    void Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
+    void Split(const AZStd::wstring& str, const AZStd::wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
 
-    // compares two strings to see if they are the same, case senstive
-    // returns true if they are the same or false if they are different
-    bool Equals(const AZStd::string& str0, const AZStd::string& str1);
-    bool Equals(const wstring& str0, const wstring& str1);
-
-    // compares two strings to see if they are the same, case is ignored
-    // returns true if they are the same or false if they are different
-    bool EqualsIgnoreCase(const AZStd::string& str0, const AZStd::string& str1);
-    bool EqualsIgnoreCase(const wstring& str0, const wstring& str1);
-
-    // checks to see if a string starts with a specified string, case sensitive
-    // returns true if the string does start with a specified string or false if it does not
-    bool StartsWith(const AZStd::string& str, const AZStd::string& pattern);
-    bool StartsWith(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string starts with a specified string, case is ignored
-    // returns true if the string does start with a specified string or false if it does not
-    bool StartsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
-    bool StartsWithIgnoreCase(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string ends with a specified string, case sensitive
-    // returns true if the string does end with a specified string or false if it does not
-    bool EndsWith(const AZStd::string& str, const AZStd::string& pattern);
-    bool EndsWith(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string ends with a specified string, case is ignored
-    // returns true if the string does end with a specified string or false if it does not
-    bool EndsWithIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
-    bool EndsWithIgnoreCase(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string contains a specified string, case sensitive
-    // returns true if the string does contain the specified string or false if it does not
-    bool Contains(const AZStd::string& str, const AZStd::string& pattern);
-    bool Contains(const wstring& str, const wstring& pattern);
-
-    // checks to see if a string contains a specified string, case is ignored
-    // returns true if the string does contain the specified string or false if it does not
-    bool ContainsIgnoreCase(const AZStd::string& str, const AZStd::string& pattern);
-    bool ContainsIgnoreCase(const wstring& str, const wstring& pattern);
-
-    string TrimLeft(const AZStd::string& s);
-    wstring TrimLeft(const wstring& s);
-
-    string TrimRight(const AZStd::string& s);
-    wstring TrimRight(const wstring& s);
-
-    string Trim(const AZStd::string& s);
-    wstring Trim(const wstring& s);
-
-    string RemoveDuplicateSpaces(const AZStd::string& s);
-    wstring RemoveDuplicateSpaces(const wstring& s);
-
-    // converts a string with upper case characters to be all lower case
-    // returns the string in all lower case
-    string MakeLowerCase(const AZStd::string& s);
-    wstring MakeLowerCase(const wstring& s);
-
-    // converts a string with lower case characters to be all upper case
-    // returns the string in all upper case
-    string MakeUpperCase(const AZStd::string& s);
-    wstring MakeUpperCase(const wstring& s);
-
-    // replace a specified character in a string with a specified replacement character
-    // returns string with specified character replaced
-    string Replace(const AZStd::string& s, char oldChar, char newChar);
-    wstring Replace(const wstring& s, wchar_t oldChar, wchar_t newChar);
-
-    void ConvertStringByRef(string& out, const AZStd::string& in);
-    void ConvertStringByRef(wstring& out, const AZStd::string& in);
-    void ConvertStringByRef(string& out, const wstring& in);
-    void ConvertStringByRef(wstring& out, const wstring& in);
-
-    template 
-    O ConvertString(const I& in)
-    {
-        O out;
-        ConvertStringByRef(out, in);
-        return out;
-    }
-    
-    void Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
-    void Split(const wstring& str, const wstring& separator, bool bReturnEmptyPartsToo, std::vector& outParts);
-
-    void SplitByAnyOf(const AZStd::string& str, const AZStd::string& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
-    void SplitByAnyOf(const wstring& str, const wstring& separators, bool bReturnEmptyPartsToo, std::vector& outParts);
-
-    string FormatVA(const char* const format, va_list parg);
-    wstring FormatVA(const wchar_t* const format, va_list parg);
-
-    inline string Format(const char* const format, ...)
-    {
-        if ((format == 0) || (format[0] == 0))
-        {
-            return string();
-        }
-        va_list parg;
-        va_start(parg, format);
-        const string result = FormatVA(format, parg);
-        va_end(parg);
-        return result;
-    }
-
-    inline wstring Format(const wchar_t* const format, ...)
-    {
-        if ((format == 0) || (format[0] == 0))
-        {
-            return wstring();
-        }
-        va_list parg;
-        va_start(parg, format);
-        const wstring result = FormatVA(format, parg);
-        va_end(parg);
-        return result;
-    }
-
-    //////////////////////////////////////////////////////////////////////////
-
-    void SafeCopy(char* const pDstBuffer, const size_t dstBufferSizeInBytes, const char* const pSrc);
-    void SafeCopy(wchar_t* const pDstBuffer, const size_t dstBufferSizeInBytes, const wchar_t* const pSrc);
-
-    void SafeCopyPadZeros(char* const pDstBuffer, const size_t dstBufferSizeInBytes, const char* const pSrc);
-    void SafeCopyPadZeros(wchar_t* const pDstBuffer, const size_t dstBufferSizeInBytes, const wchar_t* const pSrc);
-
-    //////////////////////////////////////////////////////////////////////////
-
-    // ASCII
-    // ANSI (system default Windows ANSI code page)
-    // UTF-8
-    // UTF-16
-
-    // ASCII -> UTF-16
-
-    bool Utf16ContainsAsciiOnly(const wchar_t* wstr);
-    string ConvertAsciiUtf16ToAscii(const wchar_t* wstr);
-    wstring ConvertAsciiToUtf16(const char* str);
-
-    // UTF-8 <-> UTF-16
-#if defined(AZ_PLATFORM_WINDOWS)
-    wstring ConvertUtf8ToUtf16(const char* str);
-    string ConvertUtf16ToUtf8(const wchar_t* wstr);
-
-    inline string ConvertUtfToUtf8(const char* str)
-    {
-        return string(str);
-    }
-
-    inline string ConvertUtfToUtf8(const wchar_t* wstr)
-    {
-        return ConvertUtf16ToUtf8(wstr);
-    }
-
-    inline wstring ConvertUtfToUtf16(const char* str)
-    {
-        return ConvertUtf8ToUtf16(str);
-    }
-
-    inline wstring ConvertUtfToUtf16(const wchar_t* wstr)
-    {
-        return wstring(wstr);
-    }
-
-    // ANSI <-> UTF-8, UTF-16
-
-    wstring ConvertAnsiToUtf16(const char* str);
-    string ConvertUtf16ToAnsi(const wchar_t* wstr, char badChar);
-
-    inline string ConvertAnsiToUtf8(const char* str)
-    {
-        return ConvertUtf16ToUtf8(ConvertAnsiToUtf16(str).c_str());
-    }
-    inline string ConvertUtf8ToAnsi(const char* str, char badChar)
-    {
-        return ConvertUtf16ToAnsi(ConvertUtf8ToUtf16(str).c_str(), badChar);
-    }
-#endif
-
-    // ANSI -> ASCII
-    string ConvertAnsiToAscii(const char* str, char badChar);
 }
 #endif // CRYINCLUDE_CRYCOMMONTOOLS_STRINGHELPERS_H
diff --git a/Code/Editor/Util/XmlHistoryManager.cpp b/Code/Editor/Util/XmlHistoryManager.cpp
index 5a1bc237bb..b642929af1 100644
--- a/Code/Editor/Util/XmlHistoryManager.cpp
+++ b/Code/Editor/Util/XmlHistoryManager.cpp
@@ -427,7 +427,7 @@ const AZStd::string& CXmlHistoryManager::GetVersionDesc(int number) const
         return it->second.HistoryDescription;
     }
 
-    static string undef("UNDEFINED");
+    static AZStd::string undef("UNDEFINED");
     return undef;
 }
 
@@ -493,7 +493,7 @@ void CXmlHistoryManager::SetActiveGroupInt(const SXmlHistoryGroup* pGroup, const
     UnloadInt();
 
     TEventHandlerList eventHandler;
-    string undoDesc;
+    AZStd::string undoDesc;
 
     if (pGroup)
     {
@@ -534,7 +534,7 @@ void CXmlHistoryManager::SetActiveGroupInt(const SXmlHistoryGroup* pGroup, const
                 }
             }
         }
-        undoDesc.Format("Changed View to \"%s\"", displayName ? displayName : "UNDEFINED");
+        undoDesc = AZStd::string::format("Changed View to \"%s\"", displayName ? displayName : "UNDEFINED");
     }
     else
     {
diff --git a/Code/Editor/Util/XmlHistoryManager.h b/Code/Editor/Util/XmlHistoryManager.h
index 12699536e5..176f0a8d83 100644
--- a/Code/Editor/Util/XmlHistoryManager.h
+++ b/Code/Editor/Util/XmlHistoryManager.h
@@ -161,7 +161,7 @@ private:
 
         const SXmlHistoryGroup* CurrGroup;
         TGroupIndexMap CurrUserIndex;
-        string HistoryDescription;
+        AZStd::string HistoryDescription;
         bool IsNullUndo;
         bool HistoryInvalidated;
         TXmlHistotyGroupPtrList ActiveGroups;
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index 0f67e4ffd9..252ab8137d 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -2907,14 +2907,13 @@ void CXConsole::Paste()
         Utf8::Unchecked::octet_iterator end(data.end());
         for (Utf8::Unchecked::octet_iterator it(data.begin()); it != end; ++it)
         {
-            const uint32 cp = *it;
+            const wchar_t cp = *it;
             if (cp != '\r')
             {
                 // Convert UCS code-point into UTF-8 string
                 AZStd::fixed_string<5> utf8_buf = {0};
-                size_t size = 5;
-                it.to_utf8_sequence(cp, utf8_buf.data(), size);
-                AddInputUTF8(utf8_buf);
+                AZStd::to_string(utf8_buf.data(), 5, &cp, 1);
+                AddInputUTF8(utf8_buf.c_str());
             }
         }
     }

From 963cbcaf6184092aade9924475b530ed70523087 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 3 Aug 2021 10:31:43 -0700
Subject: [PATCH 042/205] Remove A version of some fw declarations and macro
 defines since those are error prone to define, if someone were to include
 windows.h after that header, it would cause issues

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzCore/AzCore/std/parallel/binary_semaphore.h         | 4 ++--
 .../Common/WinAPI/AzCore/std/parallel/config_WinAPI.h     | 8 --------
 .../AzCore/std/parallel/internal/semaphore_WinAPI.h       | 4 ++--
 3 files changed, 4 insertions(+), 12 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/std/parallel/binary_semaphore.h b/Code/Framework/AzCore/AzCore/std/parallel/binary_semaphore.h
index 797de5fceb..f9d0cdbe4d 100644
--- a/Code/Framework/AzCore/AzCore/std/parallel/binary_semaphore.h
+++ b/Code/Framework/AzCore/AzCore/std/parallel/binary_semaphore.h
@@ -38,13 +38,13 @@ namespace AZStd
 
         binary_semaphore(bool initialState = false)
         {
-            m_event = CreateEvent(nullptr, false, initialState, nullptr);
+            m_event = CreateEventW(nullptr, false, initialState, nullptr);
             AZ_Assert(m_event != NULL, "CreateEvent error: %d\n", GetLastError());
         }
         binary_semaphore(const char* name, bool initialState = false)
         {
             (void)name; // name is used only for debug, if we pass it to the semaphore it will become named semaphore
-            m_event = CreateEvent(nullptr, false, initialState, nullptr);
+            m_event = CreateEventW(nullptr, false, initialState, nullptr);
             AZ_Assert(m_event != NULL, "CreateEvent error: %d\n", GetLastError());
         }
 
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h
index fb91e4d503..86117c0539 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/config_WinAPI.h
@@ -71,19 +71,11 @@ extern "C"
     using LPSECURITY_ATTRIBUTES = SECURITY_ATTRIBUTES*;
 
     // Semaphore
-    AZ_DLL_IMPORT HANDLE _stdcall CreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCSTR lpName);
     AZ_DLL_IMPORT HANDLE _stdcall CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCWSTR lpName);
     AZ_DLL_IMPORT BOOL _stdcall ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount);
-    #ifndef CreateSemaphore
-        #define CreateSemaphore CreateSemaphoreW
-    #endif
 
     // Event
-    AZ_DLL_IMPORT HANDLE _stdcall CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName);
     AZ_DLL_IMPORT HANDLE _stdcall CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCWSTR lpName);
-    #ifndef CreateEvent
-        #define CreateEvent CreateEventW
-    #endif
     AZ_DLL_IMPORT BOOL _stdcall SetEvent(HANDLE);
 }
 
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/internal/semaphore_WinAPI.h b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/internal/semaphore_WinAPI.h
index cca90787e6..cd6b216057 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/internal/semaphore_WinAPI.h
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/std/parallel/internal/semaphore_WinAPI.h
@@ -15,14 +15,14 @@ namespace AZStd
 {
     inline semaphore::semaphore(unsigned int initialCount, unsigned int maximumCount)
     {
-        m_semaphore = CreateSemaphore(NULL, initialCount, maximumCount, 0);
+        m_semaphore = CreateSemaphoreW(NULL, initialCount, maximumCount, 0);
         AZ_Assert(m_semaphore != NULL, "CreateSemaphore error: %d\n", GetLastError());
     }
 
     inline semaphore::semaphore(const char* name, unsigned int initialCount, unsigned int maximumCount)
     {
         (void)name; // name is used only for debug, if we pass it to the semaphore it will become named semaphore
-        m_semaphore = CreateSemaphore(NULL, initialCount, maximumCount, 0);
+        m_semaphore = CreateSemaphoreW(NULL, initialCount, maximumCount, 0);
         AZ_Assert(m_semaphore != NULL, "CreateSemaphore error: %d\n", GetLastError());
     }
 

From 928c8ff16c74121c5d80e9de7988fae806f6b483 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 3 Aug 2021 10:50:58 -0700
Subject: [PATCH 043/205] add unit tests

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Framework/AzCore/Tests/AZStd/String.cpp | 21 ++++++++++++++++++++
 1 file changed, 21 insertions(+)

diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp
index 2d2602e456..c0d378bd39 100644
--- a/Code/Framework/AzCore/Tests/AZStd/String.cpp
+++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp
@@ -686,6 +686,27 @@ namespace UnitTest
         wstr1 = wstring::format(L"%hs", str.c_str());
         AZ_TEST_ASSERT(wstr1 == L"BLABLA 5");
 
+        // wstring to char buffer
+        char strBuffer[9];
+        to_string(strBuffer, 9, wstr1.c_str());
+        AZ_TEST_ASSERT(0 == azstricmp(strBuffer, "BLABLA 5"));
+
+        // wchar_t buffer to char buffer
+        wchar_t wstrBuffer[9] = L"BLABLA 5";
+        memset(strBuffer, 0, AZ_ARRAY_SIZE(strBuffer));
+        to_string(strBuffer, 9, wstrBuffer);
+        AZ_TEST_ASSERT(0 == azstricmp(strBuffer, "BLABLA 5"));
+
+        // string to wchar_t buffer
+        memset(wstrBuffer, 0, AZ_ARRAY_SIZE(wstrBuffer));
+        to_wstring(wstrBuffer, 9, str1.c_str());
+        AZ_TEST_ASSERT(0 == azwcsicmp(wstrBuffer, L"BlaBla 5"));
+
+        // char buffer to wchar_t buffer
+        memset(wstrBuffer, 0, AZ_ARRAY_SIZE(wstrBuffer));
+        to_wstring(wstrBuffer, 9, strBuffer);
+        AZ_TEST_ASSERT(0 == azwcsicmp(wstrBuffer, L"BLABLA 5"));
+
         // wchar UTF16/UTF32 to/from Utf8
         wstr1 = L"this is a \u20AC \u00A3 test"; // that's a euro and a pound sterling
         AZStd::to_string(str, wstr1);

From a92ed42829dc74d092fe8a189ed7c008ed70d879 Mon Sep 17 00:00:00 2001
From: evanchia 
Date: Tue, 3 Aug 2021 16:51:19 -0700
Subject: [PATCH 044/205] minor fixes for c++ retry command

Signed-off-by: evanchia 
---
 Code/Tools/AzTestRunner/src/main.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Code/Tools/AzTestRunner/src/main.cpp b/Code/Tools/AzTestRunner/src/main.cpp
index 96832c3fed..225975b654 100644
--- a/Code/Tools/AzTestRunner/src/main.cpp
+++ b/Code/Tools/AzTestRunner/src/main.cpp
@@ -229,7 +229,7 @@ namespace AzTestRunner
         // Construct a retry command if the test fails
         if (result != 0)
         {
-            std::cout << "Retry command: " << std::string(argv[0]) << " " << lib << " " << symbol << std::endl;
+            std::cout << "Retry command:\n " << argv[0] << " " << lib << " " << symbol << std::endl;
         }
 
         // unload and reset the module here, because it needs to release resources that were used / activated in

From cbfdf99a9efab15a79cdc7ed790291921afcf706 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 3 Aug 2021 17:59:09 -0700
Subject: [PATCH 045/205] More github cleanup

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../GridMate/GridMate/Carrier/Carrier.cpp     | 14 ++++----
 .../GridMate/GridMate/Carrier/Carrier.h       |  7 ++--
 .../GridMate/Carrier/DefaultTrafficControl.h  |  2 +-
 .../GridMate/GridMate/Carrier/Driver.h        | 11 +++---
 .../GridMate/GridMate/Carrier/Handshake.h     |  1 -
 .../GridMate/Carrier/SecureSocketDriver.cpp   |  6 ++--
 .../GridMate/Carrier/SecureSocketDriver.h     |  6 ++--
 .../GridMate/Carrier/SocketDriver.cpp         | 27 +++++++-------
 .../GridMate/GridMate/Carrier/SocketDriver.h  | 12 +++----
 .../GridMate/Carrier/TrafficControl.h         |  1 -
 .../GridMate/GridMate/Carrier/Utils.h         |  4 +--
 .../GridMate/Drillers/CarrierDriller.cpp      |  2 +-
 .../GridMate/Drillers/CarrierDriller.h        |  2 +-
 .../GridMate/Drillers/ReplicaDriller.cpp      |  1 -
 .../GridMate/Online/UserServiceTypes.h        |  1 -
 .../GridMate/GridMate/Replica/ReplicaStatus.h |  3 +-
 .../GridMate/GridMate/Session/LANSession.cpp  | 28 +++++++--------
 .../GridMate/Session/LANSessionServiceTypes.h |  2 +-
 .../GridMate/GridMate/Session/Session.cpp     | 36 +++++++++----------
 .../GridMate/GridMate/Session/Session.h       | 20 +++++------
 .../GridMate/GridMate/String/StringUtils.h    | 10 ------
 .../GridMate/GridMate/String/string.h         | 26 --------------
 .../GridMate/VoiceChat/VoiceChatServiceBus.h  |  1 -
 .../GridMate/GridMate/gridmate_files.cmake    |  1 -
 .../GridMate/Session/LANSession_Android.cpp   |  5 ++-
 .../GridMate/Carrier/Utils_UnixLike.cpp       |  4 +--
 .../WinAPI/GridMate/Carrier/Utils_WinAPI.cpp  |  4 +--
 .../GridMate/Session/LANSession_Linux.cpp     |  5 ++-
 .../GridMate/String/StringUtils_Platform.h    |  8 -----
 .../Mac/GridMate/Session/LANSession_Mac.cpp   |  5 ++-
 .../GridMate/Session/LANSession_Windows.cpp   |  6 ++--
 .../iOS/GridMate/Session/LANSession_iOS.cpp   |  5 ++-
 Code/Framework/GridMate/Tests/Carrier.cpp     |  8 ++---
 .../Tests/CarrierStreamSocketDriverTests.cpp  |  6 ++--
 Code/Framework/GridMate/Tests/Replica.cpp     |  4 +--
 Code/Framework/GridMate/Tests/Serialize.cpp   |  4 +--
 .../Framework/GridMate/Tests/TestProfiler.cpp | 20 +++++------
 37 files changed, 125 insertions(+), 183 deletions(-)
 delete mode 100644 Code/Framework/GridMate/GridMate/String/StringUtils.h
 delete mode 100644 Code/Framework/GridMate/GridMate/String/string.h
 delete mode 100644 Code/Framework/GridMate/Platform/Linux/GridMate/String/StringUtils_Platform.h

diff --git a/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp b/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
index 23e967c3fa..0285a7fc02 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/Carrier.cpp
@@ -422,7 +422,7 @@ namespace GridMate
 
         CarrierThread*              m_threadOwner;                                  ///< Pointer to the carrier thread that operates with this connection.
         AZStd::atomic m_threadConn;                       ///< Pointer to a thread connection. You can use it in the main thread only for a reference.
-        string                      m_fullAddress;                                  ///< Connection full address.
+        AZStd::string               m_fullAddress;                                  ///< Connection full address.
 
         Carrier::ConnectionStates   m_state;
 
@@ -604,7 +604,7 @@ namespace GridMate
         Connection*             m_connection;
         ThreadConnection*       m_threadConnection;
 
-        string                  m_newConnectionAddress;
+        AZStd::string           m_newConnectionAddress;
         CarrierErrorCode        m_errorCode;
         AZ::u32                 m_newRateBytesPerSec;           ///< new send rate
         AZStd::vector > m_ackCallbacks;
@@ -1007,7 +1007,7 @@ namespace GridMate
 
         unsigned int    GetMessageMTU() override                    { return m_maxMsgDataSizeBytes; }
 
-        string          ConnectionToAddress(ConnectionID id) override;
+        AZStd::string   ConnectionToAddress(ConnectionID id) override;
 
         void            SendWithCallback(const char* data, unsigned int dataSize, AZStd::unique_ptr ackCallback, ConnectionID target = AllConnections, DataReliability reliability = SEND_RELIABLE, DataPriority priority = PRIORITY_NORMAL, unsigned char channel = 0) override;
         void            Send(const char* data, unsigned int dataSize, ConnectionID target = AllConnections, DataReliability reliability = SEND_RELIABLE, DataPriority priority = PRIORITY_NORMAL, unsigned char channel = 0) override
@@ -3902,10 +3902,10 @@ CarrierImpl::DeleteConnection(Connection* conn, CarrierDisconnectReason reason)
 // Carrier
 // [9/14/2010]
 //=========================================================================
-string
+AZStd::string
 CarrierImpl::ConnectionToAddress(ConnectionID id)
 {
-    string str;
+    AZStd::string str;
     AZ_Assert(id != InvalidConnectionID, "Invalid connection id!");
     if (id != InvalidConnectionID)
     {
@@ -4911,7 +4911,7 @@ DefaultCarrier::Create(const CarrierDesc& desc, IGridMate* gridMate)
 // ReasonToString
 // [4/11/2011]
 //=========================================================================
-string
+AZStd::string
 CarrierEventsBase::ReasonToString(CarrierDisconnectReason reason)
 {
     const char* reasonStr = 0;
@@ -4951,5 +4951,5 @@ CarrierEventsBase::ReasonToString(CarrierDisconnectReason reason)
         reasonStr = "Unknown reason";
     }
 
-    return string(reasonStr);
+    return AZStd::string(reasonStr);
 }
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Carrier.h b/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
index 2968582c0d..94c31ed6d2 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Carrier.h
@@ -9,7 +9,6 @@
 #define GM_CARRIER_H
 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -100,7 +99,7 @@ namespace GridMate
         /// Returns maximum message size (with splitting or without). Splitting will make your message reliable, which might not be optimal for Unreliable messages. It's better to send two unreliable.
         //virtual unsigned int  GetMaxMessageSize(bool withSplitting = true) = 0;
 
-        virtual string          ConnectionToAddress(ConnectionID id) = 0;
+        virtual AZStd::string   ConnectionToAddress(ConnectionID id) = 0;
 
         /**
         * Sends buffer with an ACK callback. When the transport layer recieves an ACK it will run the callback.
@@ -401,7 +400,7 @@ namespace GridMate
     public:
         virtual ~CarrierEventsBase() {}
 
-        string ReasonToString(CarrierDisconnectReason reason);
+        AZStd::string ReasonToString(CarrierDisconnectReason reason);
     };
 
     class CarrierEvents
@@ -517,7 +516,7 @@ namespace GridMate
             // Traffic control
 
             /// Called every second when you update last second statistics
-            virtual void OnUpdateStatistics(const GridMate::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) = 0;
+            virtual void OnUpdateStatistics(const AZStd::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) = 0;
 
             // Simulator
             /// Enable/Disable
diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h
index 525009b015..1d8a1f6b46 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h
@@ -145,7 +145,7 @@ namespace GridMate
             StatisticData   m_sdEffectiveLastSecond;        ///< Last second statistics for effective data.
             StatisticData   m_sdEffectiveCurrentSecond; ///< Elapsing second statistics for effective data.
 
-            string          m_address;          ///< Full address for this connection. (we need for debug only)
+            AZStd::string   m_address;          ///< Full address for this connection. (we need for debug only)
             unsigned int    m_recvPacketAllowance; ///< Current allowance for number of incoming packets
             bool            m_canReceiveData; ///< Able to receive data on this connection
 
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Driver.h b/Code/Framework/GridMate/GridMate/Carrier/Driver.h
index 2c806be5e0..d6d47fc491 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Driver.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Driver.h
@@ -10,10 +10,9 @@
 
 #include 
 
-#include 
-
 #include 
 #include 
+#include 
 
 namespace GridMate
 {
@@ -139,7 +138,7 @@ namespace GridMate
 
         /// @{ Address conversion functionality. They MUST implemented thread safe. Generally this is not a problem since they just part local data.
         ///  Create address from ip and port. If ip == NULL we will assign a broadcast address.
-        virtual string          IPPortToAddress(const char* ip, unsigned int port) const = 0;
+        virtual AZStd::string   IPPortToAddress(const char* ip, unsigned int port) const = 0;
         virtual bool            AddressToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) const = 0;
         /// @}
 
@@ -188,11 +187,11 @@ namespace GridMate
 
         virtual ~DriverAddress() {}
 
-        virtual string ToString() const = 0;
+        virtual AZStd::string ToString() const = 0;
 
-        virtual string ToAddress() const = 0;
+        virtual AZStd::string ToAddress() const = 0;
 
-        virtual string GetIP() const = 0;
+        virtual AZStd::string GetIP() const = 0;
 
         virtual unsigned int  GetPort() const = 0;
 
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
index ffd332b65c..0f825da49b 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
@@ -10,7 +10,6 @@
 
 #include 
 #include 
-#include 
 
 namespace GridMate
 {
diff --git a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp
index 7d0d5644b3..031e8561ec 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp
@@ -1712,7 +1712,7 @@ namespace GridMate
         }
 
         // Calculate HMAC of buffer using the secret and peer address
-        GridMate::string addrStr = endpoint->ToAddress();
+        AZStd::string addrStr = endpoint->ToAddress();
         unsigned char result[EVP_MAX_MD_SIZE];
         unsigned int resultLen = 0;
         HMAC(EVP_sha1(), m_cookieSecret.m_currentSecret, sizeof(m_cookieSecret.m_currentSecret),
@@ -1745,7 +1745,7 @@ namespace GridMate
         }
 
         // Calculate HMAC of buffer using the secret and peer address
-        GridMate::string addrStr = endpoint->ToAddress();
+        AZStd::string addrStr = endpoint->ToAddress();
         unsigned char result[EVP_MAX_MD_SIZE];
         unsigned int resultLen = 0;
         HMAC(EVP_sha1(), m_cookieSecret.m_currentSecret, COOKIE_SECRET_LENGTH,
@@ -1809,7 +1809,7 @@ namespace GridMate
 #ifdef AZ_DebugUseSocketDebugLog
                 if (handshake)
                 {
-                    GridMate::string line = GridMate::string::format("%lld | [%08x] RawRecv %s size %d connection exists\n", AZStd::chrono::system_clock::now().time_since_epoch().count(), this, type, bytesReceived);
+                    AZStd::string line = AZStd::string::format("%lld | [%08x] RawRecv %s size %d connection exists\n", AZStd::chrono::system_clock::now().time_since_epoch().count(), this, type, bytesReceived);
                     connection->m_dbgLog += line;
             }
 #endif
diff --git a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.h b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.h
index 529ccea408..76b7958085 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.h
@@ -23,7 +23,7 @@
 //#define AZ_DebugSecureSocket AZ_TracePrintf
 //#define AZ_DebugSecureSocketConnection(window, fmt, ...) \
 //{\
-//    GridMate::string line = GridMate::string::format(fmt, __VA_ARGS__);\
+//    AZStd::string line = AZStd::string::format(fmt, __VA_ARGS__);\
 //    this->m_dbgLog += line;\
 //}
 
@@ -226,7 +226,7 @@ namespace GridMate
             int m_dbgDgramsReceived;
             int m_dbgPort;
 #ifdef AZ_DebugUseSocketDebugLog
-            GridMate::string m_dbgLog;
+            AZStd::string m_dbgLog;
 #endif
         };
 
@@ -262,7 +262,7 @@ namespace GridMate
         AZ::u32 m_maxTempBufferSize;
         AZStd::queue m_globalInQueue;
         AZStd::unordered_map m_connections;
-        AZStd::unordered_map m_ipToNumConnections;
+        AZStd::unordered_map m_ipToNumConnections;
         SecureSocketDesc m_desc;
         AZStd::chrono::system_clock::time_point m_lastTimerCheck;       ///Time last timers were checked
     };
diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
index fc3062062c..6acf778798 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
@@ -18,7 +18,6 @@
 //#define AZ_LOG_UNBOUND_SEND_RECEIVE
 
 #include 
-#include 
 #include 
 
 #include 
@@ -575,7 +574,7 @@ namespace GridMate
         return !(*this == rhs);
     }
 
-    string SocketDriverAddress::ToString() const
+    AZStd::string SocketDriverAddress::ToString() const
     {
         char ip[64];
         unsigned short port;
@@ -590,15 +589,15 @@ namespace GridMate
             port = ntohs(m_sockAddr.sin_port);
         }
 
-        return string::format("%s|%d", ip, port);
+        return AZStd::string::format("%s|%d", ip, port);
     }
 
-    string SocketDriverAddress::ToAddress() const
+    AZStd::string SocketDriverAddress::ToAddress() const
     {
         return ToString();
     }
 
-    string SocketDriverAddress::GetIP() const
+    AZStd::string SocketDriverAddress::GetIP() const
     {
         char ip[64];
         if (m_sockAddr.sin_family == AF_INET6)
@@ -609,7 +608,7 @@ namespace GridMate
         {
             inet_ntop(AF_INET, const_cast(reinterpret_cast(&m_sockAddr.sin_addr)), ip, AZ_ARRAY_SIZE(ip));
         }
-        return string(ip);
+        return AZStd::string(ip);
     }
 
     unsigned int SocketDriverAddress::GetPort() const
@@ -1144,11 +1143,11 @@ namespace GridMate
     // CreateSocketDriver
     // [3/4/2013]
     //=========================================================================
-    string
+    AZStd::string
     SocketDriverCommon::IPPortToAddressString(const char* ip, unsigned int port)
     {
         AZ_Assert(ip != nullptr, "Invalid address!");
-        return string::format("%s|%d", ip, port);
+        return AZStd::string::format("%s|%d", ip, port);
     }
 
     //=========================================================================
@@ -1159,14 +1158,14 @@ namespace GridMate
     SocketDriverCommon::AddressStringToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port)
     {
         AZStd::size_t pos = address.find('|');
-        AZ_Assert(pos != string::npos, "Invalid driver address!");
-        if (pos == string::npos)
+        AZ_Assert(pos != AZStd::string::npos, "Invalid driver address!");
+        if (pos == AZStd::string::npos)
         {
             return false;
         }
 
-        ip = string(address.begin(), address.begin() + pos);
-        port = AZStd::stoi(string(address.begin() + pos + 1, address.end()));
+        ip = AZStd::string(address.begin(), address.begin() + pos);
+        port = AZStd::stoi(AZStd::string(address.begin() + pos + 1, address.end()));
 
         return true;
     }
@@ -1180,12 +1179,12 @@ namespace GridMate
     {
         // TODO: We can/should use inet_ntop() to detect the family type
         AZStd::size_t pos = ip.find(".");
-        if (pos != string::npos)
+        if (pos != AZStd::string::npos)
         {
             return BSD_AF_INET;
         }
         pos = ip.find("::");
-        if (pos != string::npos)
+        if (pos != AZStd::string::npos)
         {
             return BSD_AF_INET6;
         }
diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
index 7555c92639..835414b374 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.h
@@ -88,9 +88,9 @@ namespace GridMate
         bool operator==(const SocketDriverAddress& rhs) const;
         bool operator!=(const SocketDriverAddress& rhs) const;
 
-        virtual string ToString() const;
-        virtual string ToAddress() const;
-        virtual string GetIP() const;
+        virtual AZStd::string ToString() const;
+        virtual AZStd::string ToAddress() const;
+        virtual AZStd::string GetIP() const;
         virtual unsigned int  GetPort() const;
         virtual const void* GetTargetAddress(unsigned int& addressSize) const;
 
@@ -163,15 +163,15 @@ namespace GridMate
 
         /// @{ Address conversion functionality. They MUST implemented thread safe. Generally this is not a problem since they just part local data.
         ///  Create address from ip and port. If ip == NULL we will assign a broadcast address.
-        virtual string  IPPortToAddress(const char* ip, unsigned int port) const                        { return IPPortToAddressString(ip, port); }
+        virtual AZStd::string  IPPortToAddress(const char* ip, unsigned int port) const                               { return IPPortToAddressString(ip, port); }
         virtual bool    AddressToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port) const    { return AddressStringToIPPort(address, ip, port); }
         /// Create address for the socket driver from IP and port
-        static string   IPPortToAddressString(const char* ip, unsigned int port);
+        static AZStd::string   IPPortToAddressString(const char* ip, unsigned int port);
         /// Decompose an address to IP and port
         static bool     AddressStringToIPPort(const AZStd::string& address, AZStd::string& ip, unsigned int& port);
         /// Return the family type of the address (AF_INET,AF_INET6 AF_UNSPEC)
         static BSDSocketFamilyType  AddressFamilyType(const AZStd::string& ip);
-        static BSDSocketFamilyType  AddressFamilyType(const char* ip)           { return AddressFamilyType(string(ip)); }
+        static BSDSocketFamilyType  AddressFamilyType(const char* ip)           { return AddressFamilyType(AZStd::string(ip)); }
         /// @}
 
         virtual AZStd::intrusive_ptr CreateDriverAddress(const AZStd::string& address) = 0;
diff --git a/Code/Framework/GridMate/GridMate/Carrier/TrafficControl.h b/Code/Framework/GridMate/GridMate/Carrier/TrafficControl.h
index 2b49f320b5..7b79124a73 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/TrafficControl.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/TrafficControl.h
@@ -9,7 +9,6 @@
 #define GM_TRAFFIC_CONTROL_H
 
 #include 
-#include 
 
 #include 
 
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Utils.h b/Code/Framework/GridMate/GridMate/Carrier/Utils.h
index 2b15696ac2..db58ec979e 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Utils.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Utils.h
@@ -8,14 +8,14 @@
 #ifndef GM_CARRIER_UTILS_H
 #define GM_CARRIER_UTILS_H
 
-#include 
+#include 
 
 namespace GridMate
 {
     namespace Utils
     {
         ///< Returns the machines address(ip) in a string. familyType is platform dependent.
-        string GetMachineAddress(int familyType = 0);
+        AZStd::string GetMachineAddress(int familyType = 0);
         ///< Returns a broadcast address based on a family type. On ipv6 we emulate broadbast using the multicast on the all nodes address (FF02::1). familyType is platform dependent.
         const char* GetBroadcastAddress(int familyType = 0);
     }
diff --git a/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.cpp b/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.cpp
index 528afa6cce..38f029f0f5 100644
--- a/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.cpp
+++ b/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.cpp
@@ -64,7 +64,7 @@ namespace GridMate
         // OnUpdateStatistics
         // [4/14/2011]
         //=========================================================================
-        void CarrierDriller::OnUpdateStatistics(const GridMate::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime)
+        void CarrierDriller::OnUpdateStatistics(const AZStd::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime)
         {
             m_output->BeginTag(m_drillerTag);
             m_output->BeginTag(AZ_CRC("Statistics", 0xe2d38b22));
diff --git a/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.h b/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.h
index bb3cb1e3b2..b12441e6fa 100644
--- a/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.h
+++ b/Code/Framework/GridMate/GridMate/Drillers/CarrierDriller.h
@@ -42,7 +42,7 @@ namespace GridMate
 
             //////////////////////////////////////////////////////////////////////////
             // Carrier Driller Bus
-            void OnUpdateStatistics(const GridMate::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) override;
+            void OnUpdateStatistics(const AZStd::string& address, const TrafficControl::Statistics& lastSecond, const TrafficControl::Statistics& lifeTime, const TrafficControl::Statistics& effectiveLastSecond, const TrafficControl::Statistics& effectiveLifeTime) override;
             void OnConnectionStateChanged(Carrier* carrier, ConnectionID id, Carrier::ConnectionStates newState) override;
             //////////////////////////////////////////////////////////////////////////
 
diff --git a/Code/Framework/GridMate/GridMate/Drillers/ReplicaDriller.cpp b/Code/Framework/GridMate/GridMate/Drillers/ReplicaDriller.cpp
index e70aceabc9..cb48578255 100644
--- a/Code/Framework/GridMate/GridMate/Drillers/ReplicaDriller.cpp
+++ b/Code/Framework/GridMate/GridMate/Drillers/ReplicaDriller.cpp
@@ -9,7 +9,6 @@
 #include 
 #include 
 #include 
-#include 
 
 using namespace AZ::Debug;
 
diff --git a/Code/Framework/GridMate/GridMate/Online/UserServiceTypes.h b/Code/Framework/GridMate/GridMate/Online/UserServiceTypes.h
index 2617d98d73..c1753b3bb2 100644
--- a/Code/Framework/GridMate/GridMate/Online/UserServiceTypes.h
+++ b/Code/Framework/GridMate/GridMate/Online/UserServiceTypes.h
@@ -9,7 +9,6 @@
 #define GM_USER_SERVICE_TYPES_H
 
 #include 
-#include 
 
 namespace GridMate
 {
diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h
index 019a595f6f..aeb5c1b2bb 100644
--- a/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h
+++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h
@@ -12,7 +12,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 
 namespace GridMate
@@ -102,7 +101,7 @@ namespace GridMate
             };
 
             AZ::u8 m_flags;
-            string m_replicaName;
+            AZStd::string m_replicaName;
         };
 
         DataSet m_options; // Flags and debug info
diff --git a/Code/Framework/GridMate/GridMate/Session/LANSession.cpp b/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
index 0127d8fa23..e4e1c9e9b6 100644
--- a/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
+++ b/Code/Framework/GridMate/GridMate/Session/LANSession.cpp
@@ -52,17 +52,17 @@ namespace GridMate
 
         MemberIDCompact GetID() const { return m_id; }
 
-        virtual string ToString() const
+        virtual AZStd::string ToString() const
         {
-            return string::format("%x", m_id);
+            return AZStd::string::format("%x", m_id);
         }
-        virtual string ToAddress() const        { return m_address; }
+        virtual AZStd::string ToAddress() const        { return m_address; }
         virtual MemberIDCompact Compact() const { return m_id; }
         virtual bool IsValid() const            { return m_id != 0; }
 
     private:
         MemberIDCompact m_id;
-        string m_address;
+        AZStd::string m_address;
     };
 
     class LANMemberIDMarshaler
@@ -141,7 +141,7 @@ namespace GridMate
 
         bool    MatchMake(const LANSearchParams& sp);
 
-        string  MakeSessionId();
+        AZStd::string  MakeSessionId();
 
         Driver* m_driver;   ///< Driver for network searches
 
@@ -199,7 +199,7 @@ namespace GridMate
         : public CtorContextBase
     {
         CtorDataSet m_memberId;
-        CtorDataSet m_memberAddress; ///< As the server/host sees it!
+        CtorDataSet m_memberAddress; ///< As the server/host sees it!
         CtorDataSet m_peerMode;
         CtorDataSet m_isHost;
     };
@@ -232,7 +232,7 @@ namespace GridMate
                 AZ_Assert(session, "We need to have a valid session!");
                 LANMember* member;
                 MemberIDCompact memberId = ctorContext.m_memberId.Get();
-                string memberAddress = ctorContext.m_memberAddress.Get();
+                AZStd::string memberAddress = ctorContext.m_memberAddress.Get();
                 RemotePeerMode remotePeerMode = ctorContext.m_peerMode.Get();
                 bool isMemberHost = ctorContext.m_isHost.Get();
 
@@ -349,7 +349,7 @@ namespace GridMate
 {
     namespace Platform
     {
-        void AssignExtendedName(GridMate::string& extendedName);
+        void AssignExtendedName(AZStd::string& extendedName);
     }
 }
 
@@ -364,7 +364,7 @@ LANMember::LANMember(const LANMemberID& id, LANSession* session)
     : GridMember(id.Compact())
     , m_memberId(id)
 {
-    string extendedName;
+    AZStd::string extendedName;
     Platform::AssignExtendedName(extendedName);
 
     m_session = session;
@@ -741,8 +741,8 @@ LANSession::CreateLocalMember(bool isHost, bool isInvited, RemotePeerMode peerMo
 {
     AZ_Assert(m_myMember == nullptr, "We already have added a local member!");
 
-    string ip = Utils::GetMachineAddress(m_carrierDesc.m_familyType);
-    string address = SocketDriverCommon::IPPortToAddressString(ip.c_str(), m_carrierDesc.m_port);
+    AZStd::string ip = Utils::GetMachineAddress(m_carrierDesc.m_familyType);
+    AZStd::string address = SocketDriverCommon::IPPortToAddressString(ip.c_str(), m_carrierDesc.m_port);
     /////////////////////////////////////////////////////////////////////////////
     // TODO: Use the UUID as an ID, we will need to add marshalers and so on
     AZ::Uuid uuid = AZ::Uuid::CreateRandom();
@@ -881,7 +881,7 @@ LANSession::OnStateHostMigrateSession(AZ::HSM& sm, const AZ::HSM::Event& e)
                 if (m_driver->Initialize(Driver::BSD_AF_INET, nullptr, hostPort, true) != Driver::EC_OK)
                 {
                     // check the output for more info
-                    string errorMsg = string::format("Failed to initialize socket at port %d!", hostPort);
+                    AZStd::string errorMsg = AZStd::string::format("Failed to initialize socket at port %d!", hostPort);
                     EBUS_DBG_EVENT(Debug::SessionDrillerBus, OnSessionError, this, errorMsg);
                     EBUS_EVENT_ID(m_gridMate, SessionEventBus, OnSessionError, this, errorMsg);
                     // We can't be a real host if we failed to provide matching services.
@@ -899,7 +899,7 @@ LANSession::OnStateHostMigrateSession(AZ::HSM& sm, const AZ::HSM::Event& e)
 // MakeSessionId
 // [3/7/2013]
 //=========================================================================
-string
+AZStd::string
 LANSession::MakeSessionId()
 {
     char temp[64];
@@ -990,7 +990,7 @@ LANSearch::Update()
             wb.Write(m_searchParams.m_params[i].m_type);
         }
 
-        string serverAddress = m_searchParams.m_serverAddress;
+        AZStd::string serverAddress = m_searchParams.m_serverAddress;
         if (serverAddress.empty())
         {
             serverAddress = Utils::GetBroadcastAddress(m_searchParams.m_familyType);
diff --git a/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h b/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
index 20ade42a6e..42524e034a 100644
--- a/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
+++ b/Code/Framework/GridMate/GridMate/Session/LANSessionServiceTypes.h
@@ -20,7 +20,7 @@ namespace GridMate
             : m_port (0) // by default session can't be found (searched for)
         {}
 
-        string m_address; /// empty to accept any address otherwise you can provide a specific bind address.
+        AZStd::string m_address; /// empty to accept any address otherwise you can provide a specific bind address.
         /**
          * Use 0 if you don't want you session to be searchable (default)
          * Port on which we will register the LAN session (it will be used for session communication and should be different than the game/carrier one).
diff --git a/Code/Framework/GridMate/GridMate/Session/Session.cpp b/Code/Framework/GridMate/GridMate/Session/Session.cpp
index 8a9bdea273..471e21127c 100644
--- a/Code/Framework/GridMate/GridMate/Session/Session.cpp
+++ b/Code/Framework/GridMate/GridMate/Session/Session.cpp
@@ -60,7 +60,7 @@ namespace GridMate
 
             typedef vector NewConnectionsType;
             typedef vector UserDataBufferType;
-            typedef unordered_set AddressSetType;
+            typedef unordered_set AddressSetType;
 
             GridSessionHandshake(unsigned int handshakeTimeoutMS, const VersionType& version);
             virtual ~GridSessionHandshake() {}
@@ -99,12 +99,12 @@ namespace GridMate
             virtual unsigned int    GetHandshakeTimeOutMS() const                   { return m_handshakeTimeOutMS; }
             //////////////////////////////////////////////////////////////////////////
 
-            void                    BanAddress(string address);
+            void                    BanAddress(AZStd::string address);
             void                    SetHost(bool isHost);
             void                    SetInvited(bool isInvited);
             void                    SetHostMigration(bool isMigrating);
             void                    SetUserData(const void* data, size_t dataSize);
-            void                    SetSessionId(string sessionId);
+            void                    SetSessionId(AZStd::string sessionId);
             bool                    IsNewConnections()                              { return !m_newConnections.empty(); }
             NewConnectionsType&     AcquireNewConnections();
             void                    ReleaseNewConnections();
@@ -117,7 +117,7 @@ namespace GridMate
             NewConnectionsType      m_newConnections;
             AddressSetType          m_banList;
             UserDataBufferType      m_userData;
-            string                  m_sessionId;
+            AZStd::string           m_sessionId;
             RemotePeerMode          m_peerMode;
             VersionType             m_version;
 
@@ -165,7 +165,7 @@ void GridSessionParam::SetValue(AZ::s32* values, size_t numElements)
     if (numElements > 0)
     {
         AZ_Assert(values != nullptr, "Invalid values pointer!");
-        string temp;
+        AZStd::string temp;
         for (size_t i = 0; i < numElements; ++i)
         {
             AZStd::to_string(temp, values[i]);
@@ -183,7 +183,7 @@ void GridSessionParam::SetValue(AZ::s64* values, size_t numElements)
     if (numElements > 0)
     {
         AZ_Assert(values != nullptr, "Invalid values pointer!");
-        string temp;
+        AZStd::string temp;
         for (size_t i = 0; i < numElements; ++i)
         {
             AZStd::to_string(temp, values[i]);
@@ -201,7 +201,7 @@ void GridSessionParam::SetValue(float* values, size_t numElements)
     if (numElements > 0)
     {
         AZ_Assert(values != nullptr, "Invalid values pointer!");
-        string temp;
+        AZStd::string temp;
         for (size_t i = 0; i < numElements; ++i)
         {
             AZStd::to_string(temp, values[i]);
@@ -219,7 +219,7 @@ void GridSessionParam::SetValue(double* values, size_t numElements)
     if (numElements > 0)
     {
         AZ_Assert(values != nullptr, "Invalid values pointer!");
-        string temp;
+        AZStd::string temp;
         for (size_t i = 0; i < numElements; ++i)
         {
             AZStd::to_string(temp, values[i]);
@@ -726,7 +726,7 @@ GridSession::RemoveParam(unsigned int index)
         {
             const GridSessionReplica::ParamContainer& curParams = m_state->m_params.Get();
             const GridSessionParam& foundParam = curParams.at(index);
-            string paramId = foundParam.m_id;
+            AZStd::string paramId = foundParam.m_id;
             m_state->m_params.Modify([=](Internal::GridSessionReplica::ParamContainer& params)
                 {
                     params.erase(¶ms.at(index));
@@ -1220,7 +1220,7 @@ GridSession::OnDriverError(Carrier* carrier, ConnectionID id, const DriverError&
         return; // not for us
     }
     uintptr_t idInt = reinterpret_cast(static_cast(id));
-    string errorMsg = string::format("Carrier driver error ConnectionID: %" PRIuPTR "ErrorCode: 0x%08x", idInt, error.m_errorCode);
+    AZStd::string errorMsg = AZStd::string::format("Carrier driver error ConnectionID: %" PRIuPTR "ErrorCode: 0x%08x", idInt, error.m_errorCode);
     EBUS_DBG_EVENT(Debug::SessionDrillerBus, OnSessionError, this, errorMsg);
     EBUS_EVENT_ID(m_gridMate, SessionEventBus, OnSessionError, this, errorMsg);
 
@@ -1248,7 +1248,7 @@ GridSession::OnSecurityError(Carrier* carrier, ConnectionID id, const SecurityEr
         return; // not for us
     }
     uintptr_t idInt = reinterpret_cast(static_cast(id));
-    string errorMsg = string::format("Carrier security error ConnectionID: %" PRIuPTR " ErrorCode: 0x%08x", idInt, error.m_errorCode);
+    AZStd::string errorMsg = AZStd::string::format("Carrier security error ConnectionID: %" PRIuPTR " ErrorCode: 0x%08x", idInt, error.m_errorCode);
     EBUS_DBG_EVENT(Debug::SessionDrillerBus, OnSessionError, this, errorMsg);
 }
 
@@ -1976,7 +1976,7 @@ GridMember::GetNatType() const
 //=========================================================================
 // GetName
 //=========================================================================
-string
+AZStd::string
 GridMember::GetName() const
 {
     return m_clientState ? m_clientState->m_name.Get().c_str() : "Unknown";
@@ -2244,7 +2244,7 @@ GridMember::GetProcessId() const
 //=========================================================================
 // GetMachineName
 //=========================================================================
-string
+AZStd::string
 GridMember::GetMachineName() const
 {
     if (m_clientState)
@@ -2253,7 +2253,7 @@ GridMember::GetMachineName() const
     }
     else
     {
-        return string();
+        return AZStd::string();
     }
 }
 
@@ -2688,7 +2688,7 @@ HandshakeErrorCode GridSessionHandshake::OnReceiveRequest(ConnectionID id, ReadB
 {
     (void)id;
     AZStd::lock_guard l(m_dataLock);
-    string sessionId;
+    AZStd::string sessionId;
     bool isInvited = false;
     RemotePeerMode peerMode;
     VersionType version;
@@ -2761,7 +2761,7 @@ bool GridSessionHandshake::OnConfirmRequest(ConnectionID id, ReadBuffer& rb)
     (void)id;
     AZStd::lock_guard l(m_dataLock);
 
-    string sessionId;
+    AZStd::string sessionId;
     if (!rb.Read(sessionId))
     {
         return false;
@@ -2818,7 +2818,7 @@ void GridSessionHandshake::OnDisconnect(ConnectionID id)
 //=========================================================================
 // BanAddress
 //=========================================================================
-void GridSessionHandshake::BanAddress(string address)
+void GridSessionHandshake::BanAddress(AZStd::string address)
 {
     AZStd::lock_guard l(m_dataLock);
     m_banList.insert(address);
@@ -2864,7 +2864,7 @@ void GridSessionHandshake::SetUserData(const void* data, size_t dataSize)
 //=========================================================================
 // SetSessionId
 //=========================================================================
-void GridSessionHandshake::SetSessionId(string sessionId)
+void GridSessionHandshake::SetSessionId(AZStd::string sessionId)
 {
     AZStd::lock_guard l(m_dataLock);
     m_sessionId = sessionId;
diff --git a/Code/Framework/GridMate/GridMate/Session/Session.h b/Code/Framework/GridMate/GridMate/Session/Session.h
index 03556756ba..5080570373 100644
--- a/Code/Framework/GridMate/GridMate/Session/Session.h
+++ b/Code/Framework/GridMate/GridMate/Session/Session.h
@@ -39,8 +39,8 @@ namespace GridMate
     struct MemberID
     {
         virtual ~MemberID() {}
-        virtual string ToString() const = 0;
-        virtual string ToAddress() const = 0;
+        virtual AZStd::string ToString() const = 0;
+        virtual AZStd::string ToAddress() const = 0;
         virtual MemberIDCompact Compact() const = 0;
         virtual bool IsValid() const = 0;
 
@@ -50,7 +50,7 @@ namespace GridMate
         AZ_FORCE_INLINE bool operator!=(const MemberIDCompact& rhs) const { return Compact() != rhs; }
     };
 
-    typedef string SessionID;
+    typedef AZStd::string SessionID;
 
     struct SearchInfo;
 
@@ -87,8 +87,8 @@ namespace GridMate
         void SetValue(float* values, size_t numElements);
         void SetValue(double* values, size_t numElements);
 
-        string m_id;
-        string m_value;
+        AZStd::string m_id;
+        AZStd::string m_value;
         AZ::u8 m_type;
 
         AZ_FORCE_INLINE bool operator==(const GridSessionParam& rhs) const { return m_type == rhs.m_type && m_id == rhs.m_id && m_value == rhs.m_value; }
@@ -303,7 +303,7 @@ namespace GridMate
         virtual const PlayerId* GetPlayerId() const = 0;
 
         NatType GetNatType() const;
-        string GetName() const;
+        AZStd::string GetName() const;
 
         GridSession* GetSession() const { return m_session; }
 
@@ -353,7 +353,7 @@ namespace GridMate
         //@{ Platform information
         AZ::PlatformID GetPlatformId() const;
         AZ::u32 GetProcessId() const;
-        string GetMachineName() const;
+        AZStd::string GetMachineName() const;
         //@}
 
     protected:
@@ -568,7 +568,7 @@ namespace GridMate
         Internal::GridSessionHandshake* m_handshake;
         typedef unordered_set ConnectionIDSet;
         ConnectionIDSet m_connections;
-        string m_hostAddress;
+        AZStd::string m_hostAddress;
         bool m_isShutdown;
 
         GridMember* m_myMember; ///< Created with the session and bound when the server replica arrives.
@@ -923,14 +923,14 @@ namespace GridMate
 
             DataSet m_numConnections;
             DataSet m_natType;
-            DataSet m_name;
+            DataSet m_name;
             DataSet m_memberId;
             DataSet m_newHostVote; ///< Used when in host migration, to cast machine's vote.
             MuteDataSetType m_muteList; ///< List of all players we have muted.
 
             // Platform and application informational data
             DataSet > m_platformId;
-            DataSet m_machineName;
+            DataSet m_machineName;
             DataSet m_processId;
             DataSet m_isInvited;
         };
diff --git a/Code/Framework/GridMate/GridMate/String/StringUtils.h b/Code/Framework/GridMate/GridMate/String/StringUtils.h
deleted file mode 100644
index 6f1ca89b0b..0000000000
--- a/Code/Framework/GridMate/GridMate/String/StringUtils.h
+++ /dev/null
@@ -1,10 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-#pragma once
-
-#include 
diff --git a/Code/Framework/GridMate/GridMate/String/string.h b/Code/Framework/GridMate/GridMate/String/string.h
deleted file mode 100644
index 779f5034c5..0000000000
--- a/Code/Framework/GridMate/GridMate/String/string.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-#ifndef GM_CONTAINERS_STRING_H
-#define GM_CONTAINERS_STRING_H
-
-#include 
-#include 
-#include   // for getting from string->wstring and backwards
-
-namespace GridMate
-{
-    /**
-     * All libs should use specialized allocators
-     */
-    typedef AZStd::basic_string, SysContAlloc > string;
-    typedef AZStd::basic_string, SysContAlloc > wstring;
-
-    typedef AZStd::basic_string, GridMateStdAlloc > gridmate_string;
-    typedef AZStd::basic_string, GridMateStdAlloc > gridmate_wstring;
-}
-#endif // GM_CONTAINERS_STRING_H
diff --git a/Code/Framework/GridMate/GridMate/VoiceChat/VoiceChatServiceBus.h b/Code/Framework/GridMate/GridMate/VoiceChat/VoiceChatServiceBus.h
index 98fcd48b85..b5c09a411a 100644
--- a/Code/Framework/GridMate/GridMate/VoiceChat/VoiceChatServiceBus.h
+++ b/Code/Framework/GridMate/GridMate/VoiceChat/VoiceChatServiceBus.h
@@ -10,7 +10,6 @@
 
 #include 
 #include 
-#include 
 
 namespace GridMate
 {
diff --git a/Code/Framework/GridMate/GridMate/gridmate_files.cmake b/Code/Framework/GridMate/GridMate/gridmate_files.cmake
index 8c94fe80ad..e318a8adcd 100644
--- a/Code/Framework/GridMate/GridMate/gridmate_files.cmake
+++ b/Code/Framework/GridMate/GridMate/gridmate_files.cmake
@@ -120,6 +120,5 @@ set(FILES
     Session/Session.cpp
     Session/Session.h
     Session/SessionServiceBus.h
-    String/string.h
     VoiceChat/VoiceChatServiceBus.h
 )
diff --git a/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp b/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp
index e70e839d42..05fb56dfc1 100644
--- a/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp
+++ b/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp
@@ -6,19 +6,18 @@
  *
  */
 
-#include 
 #include 
 
 namespace GridMate
 {
     namespace Platform
     {
-        void AssignExtendedName(GridMate::string& extendedName)
+        void AssignExtendedName(AZStd::string& extendedName)
         {
             char hostName[64];
             gethostname(hostName, AZ_ARRAY_SIZE(hostName));
 
-            extendedName = GridMate::string::format("%s", hostName);
+            extendedName = AZStd::string::format("%s", hostName);
         }
     }
 }
diff --git a/Code/Framework/GridMate/Platform/Common/UnixLike/GridMate/Carrier/Utils_UnixLike.cpp b/Code/Framework/GridMate/Platform/Common/UnixLike/GridMate/Carrier/Utils_UnixLike.cpp
index ea824e7564..7d04ff640b 100644
--- a/Code/Framework/GridMate/Platform/Common/UnixLike/GridMate/Carrier/Utils_UnixLike.cpp
+++ b/Code/Framework/GridMate/Platform/Common/UnixLike/GridMate/Carrier/Utils_UnixLike.cpp
@@ -18,9 +18,9 @@
 
 namespace GridMate
 {
-    string Utils::GetMachineAddress(int familyType)
+    AZStd::string Utils::GetMachineAddress(int familyType)
     {
-        string machineName;
+        AZStd::string machineName;
 
         struct ifaddrs* ifAddrStruct = nullptr;
         struct ifaddrs* ifa = nullptr;
diff --git a/Code/Framework/GridMate/Platform/Common/WinAPI/GridMate/Carrier/Utils_WinAPI.cpp b/Code/Framework/GridMate/Platform/Common/WinAPI/GridMate/Carrier/Utils_WinAPI.cpp
index dd9b737180..095f8ba6c7 100644
--- a/Code/Framework/GridMate/Platform/Common/WinAPI/GridMate/Carrier/Utils_WinAPI.cpp
+++ b/Code/Framework/GridMate/Platform/Common/WinAPI/GridMate/Carrier/Utils_WinAPI.cpp
@@ -16,9 +16,9 @@
 
 namespace GridMate
 {
-    string Utils::GetMachineAddress(int familyType)
+    AZStd::string Utils::GetMachineAddress(int familyType)
     {
-        string machineName;
+        AZStd::string machineName;
         char name[MAX_PATH];
         int result = gethostname(name, sizeof(name));
         AZ_Error("GridMate", result == 0, "Failed in gethostname with result=%d, WSAGetLastError=%d!", result, WSAGetLastError());
diff --git a/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp b/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp
index e70e839d42..05fb56dfc1 100644
--- a/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp
+++ b/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp
@@ -6,19 +6,18 @@
  *
  */
 
-#include 
 #include 
 
 namespace GridMate
 {
     namespace Platform
     {
-        void AssignExtendedName(GridMate::string& extendedName)
+        void AssignExtendedName(AZStd::string& extendedName)
         {
             char hostName[64];
             gethostname(hostName, AZ_ARRAY_SIZE(hostName));
 
-            extendedName = GridMate::string::format("%s", hostName);
+            extendedName = AZStd::string::format("%s", hostName);
         }
     }
 }
diff --git a/Code/Framework/GridMate/Platform/Linux/GridMate/String/StringUtils_Platform.h b/Code/Framework/GridMate/Platform/Linux/GridMate/String/StringUtils_Platform.h
deleted file mode 100644
index 03320d1dd8..0000000000
--- a/Code/Framework/GridMate/Platform/Linux/GridMate/String/StringUtils_Platform.h
+++ /dev/null
@@ -1,8 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-#pragma once
diff --git a/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp b/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp
index e70e839d42..05fb56dfc1 100644
--- a/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp
+++ b/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp
@@ -6,19 +6,18 @@
  *
  */
 
-#include 
 #include 
 
 namespace GridMate
 {
     namespace Platform
     {
-        void AssignExtendedName(GridMate::string& extendedName)
+        void AssignExtendedName(AZStd::string& extendedName)
         {
             char hostName[64];
             gethostname(hostName, AZ_ARRAY_SIZE(hostName));
 
-            extendedName = GridMate::string::format("%s", hostName);
+            extendedName = AZStd::string::format("%s", hostName);
         }
     }
 }
diff --git a/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp b/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
index 59a1c65781..8925746a79 100644
--- a/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
+++ b/Code/Framework/GridMate/Platform/Windows/GridMate/Session/LANSession_Windows.cpp
@@ -6,15 +6,15 @@
  *
  */
 
-#include 
 #include 
 #include 
+#include 
 
 namespace GridMate
 {
     namespace Platform
     {
-        void AssignExtendedName(GridMate::string& extendedName)
+        void AssignExtendedName(AZStd::string& extendedName)
         {
             char hostName[64];
             gethostname(hostName, AZ_ARRAY_SIZE(hostName));
@@ -31,7 +31,7 @@ namespace GridMate
                 azsnprintf(procName, AZ_ARRAY_SIZE(procName), "Unknown");
             }
 
-            extendedName = GridMate::string::format("%s::%s", hostName, procName);
+            extendedName = AZStd::string::format("%s::%s", hostName, procName);
         }
     }
 }
diff --git a/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp b/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp
index e70e839d42..05fb56dfc1 100644
--- a/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp
+++ b/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp
@@ -6,19 +6,18 @@
  *
  */
 
-#include 
 #include 
 
 namespace GridMate
 {
     namespace Platform
     {
-        void AssignExtendedName(GridMate::string& extendedName)
+        void AssignExtendedName(AZStd::string& extendedName)
         {
             char hostName[64];
             gethostname(hostName, AZ_ARRAY_SIZE(hostName));
 
-            extendedName = GridMate::string::format("%s", hostName);
+            extendedName = AZStd::string::format("%s", hostName);
         }
     }
 }
diff --git a/Code/Framework/GridMate/Tests/Carrier.cpp b/Code/Framework/GridMate/Tests/Carrier.cpp
index 45cb16dbb2..8d3ec4eef6 100644
--- a/Code/Framework/GridMate/Tests/Carrier.cpp
+++ b/Code/Framework/GridMate/Tests/Carrier.cpp
@@ -193,7 +193,7 @@ namespace UnitTest
             CarrierCallbacksHandler clientCB, serverCB;
             TestCarrierDesc serverCarrierDesc, clientCarrierDesc;
 
-            string str("Hello this is a carrier test!");
+            AZStd::string str("Hello this is a carrier test!");
 
             const char* targetAddress = "127.0.0.1";
 
@@ -377,7 +377,7 @@ namespace UnitTest
             CarrierCallbacksHandler clientCB, serverCB;
             TestCarrierDesc serverCarrierDesc, clientCarrierDesc;
 
-            string str("Hello this is a carrier test!");
+            AZStd::string str("Hello this is a carrier test!");
             clientCarrierDesc.m_driver = SocketProvider::CreateDriverForJoin();
             serverCarrierDesc.m_driver = SocketProvider::CreateDriverForHost();
 
@@ -469,7 +469,7 @@ namespace UnitTest
             CarrierCallbacksHandler clientCB, serverCB;
             TestCarrierDesc serverCarrierDesc, clientCarrierDesc;
 
-            string str("Hello this is a carrier stress test!");
+            AZStd::string str("Hello this is a carrier stress test!");
 
             clientCarrierDesc.m_enableDisconnectDetection = false;
             serverCarrierDesc.m_enableDisconnectDetection = false;
@@ -1401,7 +1401,7 @@ namespace UnitTest
             CarrierCallbacksHandler clientCB, serverCB;
             CarrierDesc serverCarrierDesc, clientCarrierDesc;
 
-            string str("Hello this is a carrier test!");
+            AZStd::string str("Hello this is a carrier test!");
 
             const char* targetAddress = "127.0.0.1";
 
diff --git a/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp b/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp
index aac15562df..6af6a6ab87 100644
--- a/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp
+++ b/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp
@@ -188,7 +188,7 @@ namespace UnitTest
             CarrierStreamCallbacksHandler clientCB, serverCB;
             TestCarrierDesc serverCarrierDesc, clientCarrierDesc;
 
-            string str("Hello this is a carrier test!");
+            AZStd::string str("Hello this is a carrier test!");
 
             const char* targetAddress = "127.0.0.1";
 
@@ -374,7 +374,7 @@ namespace UnitTest
             CarrierStreamCallbacksHandler clientCB, serverCB;
             TestCarrierDesc serverCarrierDesc, clientCarrierDesc;
 
-            string str("Hello this is a carrier test!");
+            AZStd::string str("Hello this is a carrier test!");
             clientCarrierDesc.m_driver = CreateDriverForJoin(clientCarrierDesc);
             serverCarrierDesc.m_driver = CreateDriverForHost(serverCarrierDesc);
 
@@ -475,7 +475,7 @@ namespace UnitTest
         CarrierStreamCallbacksHandler clientCB, serverCB;
         UnitTest::TestCarrierDesc serverCarrierDesc, clientCarrierDesc;
 
-        string str("Hello this is a carrier stress test!");
+        AZStd::string str("Hello this is a carrier stress test!");
 
         clientCarrierDesc.m_enableDisconnectDetection = /*false*/ true;
         serverCarrierDesc.m_enableDisconnectDetection = /*false*/ true;
diff --git a/Code/Framework/GridMate/Tests/Replica.cpp b/Code/Framework/GridMate/Tests/Replica.cpp
index 0b8fab10ce..83a3a1f5a1 100644
--- a/Code/Framework/GridMate/Tests/Replica.cpp
+++ b/Code/Framework/GridMate/Tests/Replica.cpp
@@ -3687,7 +3687,7 @@ public:
 
         void Touch()
         {
-            string randomStr;
+            AZStd::string randomStr;
             for (unsigned i = 0; i < k_strSize; ++i)
             {
                 randomStr += 'a' + (rand() % 26);
@@ -3698,7 +3698,7 @@ public:
         bool IsReplicaMigratable() override { return false; }
 
         static const unsigned k_strSize = 64;
-        DataSet m_value;
+        DataSet m_value;
     };
 
     void run()
diff --git a/Code/Framework/GridMate/Tests/Serialize.cpp b/Code/Framework/GridMate/Tests/Serialize.cpp
index 4c74e9526a..9a681dc018 100644
--- a/Code/Framework/GridMate/Tests/Serialize.cpp
+++ b/Code/Framework/GridMate/Tests/Serialize.cpp
@@ -471,12 +471,12 @@ namespace UnitTest
             // ------------------------------------
             // String
             {
-                string s = "hello";
+                AZStd::string s = "hello";
 
                 wb.Write(s);
                 AZ_TEST_ASSERT(wb.Size() == s.length() + sizeof(AZ::u16));
 
-                string rs;
+                AZStd::string rs;
                 rb = ReadBuffer(wb.GetEndianType(), wb.Get(), wb.Size());
                 rb.Read(rs);
                 AZ_TEST_ASSERT(rs == s);
diff --git a/Code/Framework/GridMate/Tests/TestProfiler.cpp b/Code/Framework/GridMate/Tests/TestProfiler.cpp
index 9f79d5a9fe..26e9312ecf 100644
--- a/Code/Framework/GridMate/Tests/TestProfiler.cpp
+++ b/Code/Framework/GridMate/Tests/TestProfiler.cpp
@@ -34,15 +34,15 @@ static bool CollectPerformanceCounters(const AZ::Debug::ProfilerRegister& reg, c
     return true;
 }
 
-static string FormatString(const AZStd::string& pre, const AZStd::string& name, const AZStd::string& post, AZ::u64 time, AZ::u64 calls)
+static AZStd::string FormatString(const AZStd::string& pre, const AZStd::string& name, const AZStd::string& post, AZ::u64 time, AZ::u64 calls)
 {
-    string units = "us";
+    AZStd::string units = "us";
     if (AZ::u64 divtime = time / 1000)
     {
         time = divtime;
         units = "ms";
     }
-    return string::format("%s%s %s %10llu%s (%llu calls)\n", pre.c_str(), name.c_str(), post.c_str(), time, units.c_str(), calls);
+    return AZStd::string::format("%s%s %s %10llu%s (%llu calls)\n", pre.c_str(), name.c_str(), post.c_str(), time, units.c_str(), calls);
 }
 
 struct TotalSortContainer
@@ -56,28 +56,28 @@ struct TotalSortContainer
     {
         if (m_self && level >= 0)
         {
-            string levelIndent;
+            AZStd::string levelIndent;
             for (AZ::s32 i = 0; i < level; i++)
             {
                 levelIndent += (i == level - 1) ? "+---" : "|   ";
             }
-            string name = m_self->m_name ? m_self->m_name : m_self->m_function;
-            string outputTotal = FormatString(levelIndent, name, " Total:", m_self->m_timeData.m_time, m_self->m_timeData.m_calls);
+            AZStd::string name = m_self->m_name ? m_self->m_name : m_self->m_function;
+            AZStd::string outputTotal = FormatString(levelIndent, name, " Total:", m_self->m_timeData.m_time, m_self->m_timeData.m_calls);
             AZ_Printf(systemId, outputTotal.c_str());
 
             if (m_self->m_timeData.m_childrenTime || m_self->m_timeData.m_childrenCalls)
             {
-                string childIndent = levelIndent;
+                AZStd::string childIndent = levelIndent;
                 for (auto i = name.begin(); i != name.end(); ++i)
                 {
                     childIndent += " ";
                 }
                 childIndent[level * 4] = '|';
 
-                string outputChild = FormatString(childIndent, "", "Child:", m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_childrenCalls);
+                AZStd::string outputChild = FormatString(childIndent, "", "Child:", m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_childrenCalls);
                 AZ_Printf(systemId, outputChild.c_str());
 
-                string outputSelf = FormatString(childIndent, "", "Self :", m_self->m_timeData.m_time - m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_calls);
+                AZStd::string outputSelf = FormatString(childIndent, "", "Self :", m_self->m_timeData.m_time - m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_calls);
                 AZ_Printf(systemId, outputSelf.c_str());
             }
         }
@@ -237,7 +237,7 @@ void TestProfiler::PrintProfilingSelf(const char* systemId)
     AZ_Printf(systemId, "Profiling timers by exclusive execution time:\n");
     for (auto profiler : selfSorted)
     {
-        string str = FormatString("", profiler->m_name ? profiler->m_name : profiler->m_function, "Self Time:",
+        AZStd::string str = FormatString("", profiler->m_name ? profiler->m_name : profiler->m_function, "Self Time:",
                 profiler->m_timeData.m_time - profiler->m_timeData.m_childrenTime, profiler->m_timeData.m_calls);
         AZ_Printf(systemId, str.c_str());
     }

From e28602dbbb4a09a389f0519ed680fc051a5d59cb Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 3 Aug 2021 17:59:35 -0700
Subject: [PATCH 046/205] linux fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/Export/ExportManager.cpp          |   6 +-
 Code/Editor/TrackView/CommentNodeAnimator.cpp |   2 +-
 .../TrackView/TrackViewDopeSheetBase.cpp      |   6 +-
 Code/Editor/TrackView/TrackViewNodes.cpp      |   2 +-
 Code/Editor/Util/FileUtil.cpp                 |   9 +-
 Code/Editor/Util/PathUtil.cpp                 |  13 +--
 Code/Editor/Util/PathUtil.h                   |   4 +-
 Code/Editor/Util/StringHelpers.cpp            |   2 +-
 Code/Editor/Util/StringHelpers.h              |   3 +
 Code/Framework/AzCore/AzCore/base.h           | 108 +++++++++---------
 .../AzCore/AzCore/std/string/conversions.h    |  34 +-----
 .../WinAPI/AzCore/Utils/Utils_WinAPI.cpp      |   7 +-
 .../AzFramework/IO/LocalFileIO_WinAPI.cpp     |   6 +-
 Code/Legacy/CryCommon/CryFile.h               |   8 +-
 Code/Legacy/CryCommon/CryListenerSet.h        |   2 +-
 Code/Legacy/CryCommon/CryName.h               |   8 +-
 Code/Legacy/CryCommon/CryPath.h               |   2 +-
 Code/Legacy/CryCommon/ISerialize.h            |   4 +-
 Code/Legacy/CryCommon/Linux_Win32Wrapper.h    |   4 +-
 Code/Legacy/CryCommon/WinBase.cpp             |  57 ++++-----
 Code/Legacy/CrySystem/DebugCallStack.cpp      |  22 ++--
 Code/Legacy/CrySystem/IDebugCallStack.cpp     |   2 +-
 Code/Legacy/CrySystem/IDebugCallStack.h       |   6 +-
 .../CrySystem/LevelSystem/LevelSystem.cpp     |   2 +-
 .../CrySystem/LocalizedStringManager.cpp      |   4 +-
 Code/Legacy/CrySystem/Log.cpp                 |   8 +-
 Code/Legacy/CrySystem/SystemWin32.cpp         |   2 +-
 Code/Legacy/CrySystem/XConsole.cpp            |  16 +--
 Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp |   2 +-
 Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp |   2 +-
 Code/Tools/GridHub/GridHub/gridhub.cpp        |   4 +-
 Code/Tools/GridHub/GridHub/gridhub.hxx        |   2 +-
 .../Process/TestImpactWin32_Process.cpp       |   7 +-
 .../Animation/UiAnimViewDopeSheetBase.cpp     |   6 +-
 .../UiClipboard_Unimplemented.cpp             |   7 +-
 .../Code/Source/Cinematics/CaptureTrack.cpp   |   2 +-
 .../Code/Source/Cinematics/CommentTrack.cpp   |   2 +-
 .../Source/Cinematics/CompoundSplineTrack.cpp |  10 +-
 .../Code/Source/Cinematics/EventTrack.cpp     |   6 +-
 .../Code/Source/Cinematics/SceneNode.cpp      |   4 +-
 .../Source/Cinematics/ScreenFaderTrack.cpp    |   2 +-
 .../Source/Cinematics/TrackEventTrack.cpp     |   6 +-
 42 files changed, 186 insertions(+), 225 deletions(-)

diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp
index 5ba250c960..981e38c029 100644
--- a/Code/Editor/Export/ExportManager.cpp
+++ b/Code/Editor/Export/ExportManager.cpp
@@ -46,7 +46,7 @@ namespace
         SEfResTexture* pTex = pRes->GetTextureResource(nSlot);
         if (pTex)
         {
-            azstrcat(outName, Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data());
+            azstrcat(outName, AZ_ARRAY_SIZE(outName), Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data());
         }
     }
 
@@ -88,7 +88,7 @@ Export::CObject::CObject(const char* pName)
 
     nParent = -1;
 
-    azstrcpy(name, pName);
+    azstrcpy(name, AZ_ARRAY_SIZE(name), pName);
 
     materialName[0] = '\0';
 
@@ -102,7 +102,7 @@ Export::CObject::CObject(const char* pName)
 
 void Export::CObject::SetMaterialName(const char* pName)
 {
-    azstrcpy(materialName, pName);
+    azstrcpy(materialName, AZ_ARRAY_SIZE(materialName), pName);
 }
 
 
diff --git a/Code/Editor/TrackView/CommentNodeAnimator.cpp b/Code/Editor/TrackView/CommentNodeAnimator.cpp
index 579bba00ef..cc3e7da972 100644
--- a/Code/Editor/TrackView/CommentNodeAnimator.cpp
+++ b/Code/Editor/TrackView/CommentNodeAnimator.cpp
@@ -92,7 +92,7 @@ void CCommentNodeAnimator::AnimateCommentTextTrack(CTrackViewTrack* pTrack, cons
         if (commentKey.m_duration > 0 && ac.time < keyHandle.GetTime() + commentKey.m_duration)
         {
             m_commentContext.m_strComment = commentKey.m_strComment;
-            azstrcpy(m_commentContext.m_strFont,  commentKey.m_strFont.c_str());
+            azstrcpy(m_commentContext.m_strFont, AZ_ARRAY_SIZE(m_commentContext.m_strFont), commentKey.m_strFont.c_str());
             m_commentContext.m_color = commentKey.m_color;
             m_commentContext.m_align = commentKey.m_align;
             m_commentContext.m_size = commentKey.m_size;
diff --git a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
index f66bb19bf3..bf2e39e64d 100644
--- a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
+++ b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp
@@ -2808,10 +2808,10 @@ void CTrackViewDopeSheetBase::DrawKeys(CTrackViewTrack* pTrack, QPainter* painte
                 }
                 else
                 {
-                    azstrcpy(keydesc, "{");
+                    azstrcpy(keydesc, AZ_ARRAY_SIZE(keydesc), "{");
                 }
-                azstrcat(keydesc, pDescription);
-                azstrcat(keydesc, "}");
+                azstrcat(keydesc, AZ_ARRAY_SIZE(keydesc), pDescription);
+                azstrcat(keydesc, AZ_ARRAY_SIZE(keydesc), "}");
                 // Draw key description text.
                 // Find next key.
                 const QRect textRect(QPoint(x + 10, rect.top()), QPoint(x1, rect.bottom()));
diff --git a/Code/Editor/TrackView/TrackViewNodes.cpp b/Code/Editor/TrackView/TrackViewNodes.cpp
index 000bdf21d0..9652de51ef 100644
--- a/Code/Editor/TrackView/TrackViewNodes.cpp
+++ b/Code/Editor/TrackView/TrackViewNodes.cpp
@@ -2516,7 +2516,7 @@ int CTrackViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, cons
     if (const char* pCh = strstr(nodeName, ".["))
     {
         char matPath[MAX_PATH];
-        azstrncpy(matPath, nodeName, (size_t)(pCh - nodeName));
+        azstrncpy(matPath, AZ_ARRAY_SIZE(matPath), nodeName, (size_t)(pCh - nodeName));
         matName = matPath;
         pCh += 2;
         if ((*pCh) != 0)
diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp
index f5535f5590..3157a04bd8 100644
--- a/Code/Editor/Util/FileUtil.cpp
+++ b/Code/Editor/Util/FileUtil.cpp
@@ -2217,15 +2217,14 @@ uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*=
         return SCC_FILE_ATTRIBUTE_READONLY | SCC_FILE_ATTRIBUTE_INPAK;
     }
 
-    AZStd::wstring fileW;
-    AZStd::to_wstring(fileW, file.GetAdjustedFilename());
-    DWORD dwAttrib = ::GetFileAttributesW(fileW.c_str());
-    if (dwAttrib == INVALID_FILE_ATTRIBUTES)
+    
+    const char* adjustedFile = file.GetAdjustedFilename();
+    if (!AZ::IO::SystemFile::Exists(adjustedFile))
     {
         return SCC_FILE_ATTRIBUTE_INVALID;
     }
 
-    if (dwAttrib & FILE_ATTRIBUTE_READONLY)
+    if (!AZ::IO::SystemFile::IsWritable(adjustedFile))
     {
         return SCC_FILE_ATTRIBUTE_NORMAL | SCC_FILE_ATTRIBUTE_READONLY;
     }
diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp
index e91d85e4d2..2f99f42188 100644
--- a/Code/Editor/Util/PathUtil.cpp
+++ b/Code/Editor/Util/PathUtil.cpp
@@ -16,6 +16,7 @@
 #include 
 #include 
 #include 
+#include 
 
 #include 
 
@@ -203,16 +204,7 @@ namespace Path
 
     bool IsFolder(const char* pPath)
     {
-        AZStd::wstring pPathW;
-        AZStd::to_wstring(pPathW, pPath);
-        DWORD attrs = GetFileAttributes(pPathW.c_str());
-
-        if (attrs == FILE_ATTRIBUTE_DIRECTORY)
-        {
-            return true;
-        }
-
-        return false;
+        return AZ::IO::FileIOBase::GetInstance()->IsDirectory(pPath);
     }
 
     //////////////////////////////////////////////////////////////////////////
@@ -256,7 +248,6 @@ namespace Path
         static AZStd::string s_currentModName;
         // query the editor root.  The bus exists in case we want tools to be able to override this.
 
-
         if (s_currentModName.empty())
         {
             return GetGameAssetsFolder();
diff --git a/Code/Editor/Util/PathUtil.h b/Code/Editor/Util/PathUtil.h
index 30887e698b..4ea30d1f74 100644
--- a/Code/Editor/Util/PathUtil.h
+++ b/Code/Editor/Util/PathUtil.h
@@ -106,7 +106,7 @@ namespace Path
         path = path_buffer;
         _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), 0, 0, fname, ext);
 #else
-        _splitpath(filepath, drive, dir, fname, ext);
+        _splitpath(filepath.c_str(), drive, dir, fname, ext);
         _makepath(path_buffer, drive, dir, 0, 0);
         path = path_buffer;
         _makepath(path_buffer, 0, 0, fname, ext);
@@ -148,7 +148,7 @@ namespace Path
         _splitpath_s(filepath.c_str(), drive, AZ_ARRAY_SIZE(drive), dir, AZ_ARRAY_SIZE(dir), fname, AZ_ARRAY_SIZE(fname), ext, AZ_ARRAY_SIZE(ext));
         _makepath_s(path_buffer, AZ_ARRAY_SIZE(path_buffer), drive, dir, 0, 0);
 #else
-        _splitpath(filepath, drive, dir, fname, ext);
+        _splitpath(filepath.c_str(), drive, dir, fname, ext);
         _makepath(path_buffer, drive, dir, 0, 0);
 #endif
         path = path_buffer;
diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp
index a1e2b4ae08..6c819270bd 100644
--- a/Code/Editor/Util/StringHelpers.cpp
+++ b/Code/Editor/Util/StringHelpers.cpp
@@ -15,7 +15,7 @@
 int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
 {
     const size_t minLength = Util::getMin(str0.length(), str1.length());
-    const int result = azmemicmp(str0.c_str(), str1.c_str(), minLength);
+    const int result = azstrnicmp(str0.c_str(), str1.c_str(), minLength);
     if (result)
     {
         return result;
diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h
index 0e393e92dd..b5c84d7fe3 100644
--- a/Code/Editor/Util/StringHelpers.h
+++ b/Code/Editor/Util/StringHelpers.h
@@ -11,6 +11,9 @@
 #define CRYINCLUDE_CRYCOMMONTOOLS_STRINGHELPERS_H
 #pragma once
 
+#include 
+#include 
+
 namespace StringHelpers
 {
     // compares two strings to see if they are the same or different, case is ignored
diff --git a/Code/Framework/AzCore/AzCore/base.h b/Code/Framework/AzCore/AzCore/base.h
index 252133e781..00fdbf515e 100644
--- a/Code/Framework/AzCore/AzCore/base.h
+++ b/Code/Framework/AzCore/AzCore/base.h
@@ -51,74 +51,72 @@
 #   define azvscprintf(_format, _va_list)                   _vscprintf(_format, _va_list)
 #   define azscwprintf                                      _scwprintf
 #   define azvscwprintf                                     _vscwprintf
-#   define azstrtok(_buffer, _size, _delim, _context)  strtok_s(_buffer, _delim, _context)
-#   define azstrcat         strcat_s
-#   define azstrncat        strncat_s
-#   define strtoll          _strtoi64
-#   define strtoull         _strtoui64
-#   define azsscanf         sscanf_s
-#   define azstrcpy         strcpy_s
-#   define azstrncpy        strncpy_s
-#   define azstricmp        _stricmp
-#   define azstrnicmp       _strnicmp
-#   define azisfinite       _finite
-#   define azltoa           _ltoa_s
-#   define azitoa           _itoa_s
-#   define azui64toa        _ui64toa_s
-#   define azswscanf        swscanf_s
-#   define azwcsicmp        _wcsicmp
-#   define azwcsnicmp       _wcsnicmp
-#   define azmemicmp        _memicmp
+#   define azstrtok(_buffer, _size, _delim, _context)       strtok_s(_buffer, _delim, _context)
+#   define azstrcat(_dest, _destSize, _src)                 strcat_s(_dest, _destSize, _src)
+#   define azstrncat(_dest, _destSize, _src, _count)        strncat_s(_dest, _destSize, _src, _count)
+#   define strtoll                                          _strtoi64
+#   define strtoull                                         _strtoui64
+#   define azsscanf                                         sscanf_s
+#   define azstrcpy(_dest, _destSize, _src)                 strcpy_s(_dest, _destSize, _src)
+#   define azstrncpy(_dest, _destSize, _src, _count)        strncpy_s(_dest, _destSize, _src, _count)
+#   define azstricmp                                        _stricmp
+#   define azstrnicmp                                       _strnicmp
+#   define azisfinite                                       _finite
+#   define azltoa                                           _ltoa_s
+#   define azitoa                                           _itoa_s
+#   define azui64toa                                        _ui64toa_s
+#   define azswscanf                                        swscanf_s
+#   define azwcsicmp                                        _wcsicmp
+#   define azwcsnicmp                                       _wcsnicmp
 
 // note: for cross-platform compatibility, do not use the return value of azfopen. On Windows, it's an errno_t and 0 indicates success. On other platforms, the return value is a FILE*, and a 0 value indicates failure.
-#   define azfopen          fopen_s
+#   define azfopen(_fp, _filename, _attrib)                 fopen_s(_fp, _filename, _attrib)
 #   define azfscanf         fscanf_s
 
-#   define azsprintf(_buffer, ...)      sprintf_s(_buffer, AZ_ARRAY_SIZE(_buffer), __VA_ARGS__)
-#   define azstrlwr         _strlwr_s
-#   define azvsprintf       vsprintf_s
-#   define azwcscpy         wcscpy_s
-#   define azstrtime        _strtime_s
-#   define azstrdate        _strdate_s
-#   define azlocaltime(time, result) localtime_s(result, time)
+#   define azsprintf(_buffer, ...)                          sprintf_s(_buffer, AZ_ARRAY_SIZE(_buffer), __VA_ARGS__)
+#   define azstrlwr                                         _strlwr_s
+#   define azvsprintf                                       vsprintf_s
+#   define azwcscpy                                         wcscpy_s
+#   define azstrtime                                        _strtime_s
+#   define azstrdate                                        _strdate_s
+#   define azlocaltime(time, result)                        localtime_s(result, time)
 #else
-#   define azsnprintf       snprintf
-#   define azvsnprintf      vsnprintf
+#   define azsnprintf                                       snprintf
+#   define azvsnprintf                                      vsnprintf
 #   if AZ_TRAIT_COMPILER_DEFINE_AZSWNPRINTF_AS_SWPRINTF
-#       define azsnwprintf  swprintf
-#       define azvsnwprintf vswprintf
+#       define azsnwprintf                                  swprintf
+#       define azvsnwprintf                                 vswprintf
 #   else
-#       define azsnwprintf  snwprintf
-#       define azvsnwprintf vsnwprintf
+#       define azsnwprintf                                  snwprintf
+#       define azvsnwprintf                                 vsnwprintf
 #   endif
-#   define azscprintf(...)                  azsnprintf(nullptr, static_cast(0), __VA_ARGS__);
-#   define azvscprintf(_format, _va_list)   azvsnprintf(nullptr, static_cast(0), _format, _va_list);
-#   define azscwprintf(...)                 azsnwprintf(nullptr, static_cast(0), __VA_ARGS__);
-#   define azvscwprintf(_format, _va_list)  azvsnwprintf(nullptr, static_cast(0), _format, _va_list);
-#   define azstrtok(_buffer, _size, _delim, _context)  strtok(_buffer, _delim)
-#   define azstrcat(_dest, _destSize, _src) strcat(_dest, _src)
-#   define azstrncat(_dest, _destSize, _src, _count) strncat(_dest, _src, _count)
-#   define azsscanf         sscanf
-#   define azstrcpy(_dest, _destSize, _src) strcpy(_dest, _src)
-#   define azstrncpy(_dest, _destSize, _src, _count) strncpy(_dest, _src, _count)
-#   define azstricmp        strcasecmp
-#   define azstrnicmp       strncasecmp
+#   define azscprintf(...)                                  azsnprintf(nullptr, static_cast(0), __VA_ARGS__);
+#   define azvscprintf(_format, _va_list)                   azvsnprintf(nullptr, static_cast(0), _format, _va_list);
+#   define azscwprintf(...)                                 azsnwprintf(nullptr, static_cast(0), __VA_ARGS__);
+#   define azvscwprintf(_format, _va_list)                  azvsnwprintf(nullptr, static_cast(0), _format, _va_list);
+#   define azstrtok(_buffer, _size, _delim, _context)       strtok(_buffer, _delim)
+#   define azstrcat(_dest, _destSize, _src)                 strcat(_dest, _src)
+#   define azstrncat(_dest, _destSize, _src, _count)        strncat(_dest, _src, _count)
+#   define azsscanf                                         sscanf
+#   define azstrcpy(_dest, _destSize, _src)                 strcpy(_dest, _src)
+#   define azstrncpy(_dest, _destSize, _src, _count)        strncpy(_dest, _src, _count)
+#   define azstricmp                                        strcasecmp
+#   define azstrnicmp                                       strncasecmp
 #   if defined(NDK_REV_MAJOR) && NDK_REV_MAJOR < 16
-#       define azisfinite   __isfinitef
+#       define azisfinite                                   __isfinitef
 #   else
-#       define azisfinite   isfinite
+#       define azisfinite                                   isfinite
 #   endif
-#   define azltoa(_value, _buffer, _size, _radix) ltoa(_value, _buffer, _radix)
-#   define azitoa(_value, _buffer, _size, _radix) itoa(_value, _buffer, _radix)
-#   define azui64toa(_value, _buffer, _size, _radix) _ui64toa(_value, _buffer, _radix)
-#   define azswscanf        swscanf
-#   define azwcsicmp        wcsicmp
-#   define azwcsnicmp       wcsnicmp
-#   define azmemicmp        memicmp
+#   define azltoa(_value, _buffer, _size, _radix)           ltoa(_value, _buffer, _radix)
+#   define azitoa(_value, _buffer, _size, _radix)           itoa(_value, _buffer, _radix)
+#   define azui64toa(_value, _buffer, _size, _radix)        _ui64toa(_value, _buffer, _radix)
+#   define azswscanf                                        swscanf
+#   define azwcsicmp                                        wcscasecmp
+#   define azwcsnicmp                                       wcsnicmp
 
 // note: for cross-platform compatibility, do not use the return value of azfopen. On Windows, it's an errno_t and 0 indicates success. On other platforms, the return value is a FILE*, and a 0 value indicates failure.
-#   define azfopen(_fp, _filename, _attrib) *(_fp) = fopen(_filename, _attrib)
-#   define azfscanf         fscanf
+#   define azfopen(_fp, _filename, _attrib)                 *(_fp) = fopen(_filename, _attrib)
+#   define azfscanf                                         fscanf
 
 #   define azsprintf       sprintf
 #   define azstrlwr(_buffer, _size)             strlwr(_buffer)
diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index fcfe82ba5f..91af1029b4 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -30,6 +30,8 @@ namespace AZStd
         template
         struct WCharTPlatformConverter
         {
+            static_assert(Size == size_t{ 2 } || Size == size_t{ 4 }, "only wchar_t types of size 2 or 4 can be converted to utf8");
+
             template
             static inline void to_string(AZStd::basic_string& dest, const wchar_t* first, const wchar_t* last)
             {
@@ -41,12 +43,6 @@ namespace AZStd
                 {
                     Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
-                else
-                {
-                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
-                    using StringType = AZStd::basic_string;
-                    static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8");
-                }
             }
 
             template
@@ -60,12 +56,6 @@ namespace AZStd
                 {
                     Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
-                else
-                {
-                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
-                    using StringType = AZStd::basic_string;
-                    static_assert(!AZStd::is_same_v, "only wchar_t types of size 2 or 4 can be converted to utf8");
-                }
             }
 
             static inline void to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last)
@@ -78,10 +68,6 @@ namespace AZStd
                 {
                     Utf8::Unchecked::utf32to8(first, last, dest, destSize);
                 }
-                else
-                {
-                    static_assert(false, "only wchar_t types of size 2 or 4 can be converted to utf8");
-                }
             }
 
             template
@@ -95,12 +81,6 @@ namespace AZStd
                 {
                     Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
-                else
-                {
-                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
-                    using StringType = AZStd::basic_string;
-                    static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
-                }
             }
 
             template
@@ -114,12 +94,6 @@ namespace AZStd
                 {
                     Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size());
                 }
-                else
-                {
-                    // Workaround to defer static_assert evaluation until this function is invoked by using the template parameter
-                    using StringType = AZStd::basic_string;
-                    static_assert(!AZStd::is_same_v, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
-                }
             }
 
             static inline void to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last)
@@ -132,10 +106,6 @@ namespace AZStd
                 {
                     Utf8::Unchecked::utf8to32(first, last, dest, destSize);
                 }
-                else
-                {
-                    static_assert(false, "Cannot convert a utf8 string to a wchar_t that isn't size 2 or 4");
-                }
             }
         };
     }
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
index c57f2b31f6..a4af19a2a4 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
@@ -30,9 +30,8 @@ namespace AZ
             result.m_pathIncludesFilename = true;
             // Platform specific get exe path: http://stackoverflow.com/a/1024937
             // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
-            AZStd::wstring pathBuffer;
-            pathBuffer.resize(exeStorageSize);
-            const DWORD pathLen = GetModuleFileName(nullptr, pathBuffer.data(), static_cast(exeStorageSize));
+            wchar_t pathBufferW[AZ_MAX_PATH_LEN] = { 0 };
+            const DWORD pathLen = GetModuleFileNameW(nullptr, pathBufferW, static_cast(exeStorageSize));
             const DWORD errorCode = GetLastError();
             if (pathLen == exeStorageSize && errorCode == ERROR_INSUFFICIENT_BUFFER)
             {
@@ -44,7 +43,7 @@ namespace AZ
             }
             else
             {
-                AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBuffer.c_str());
+                AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBufferW);
             }
 
             return result;
diff --git a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
index 58afebfb90..61957fced0 100644
--- a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
+++ b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/IO/LocalFileIO_WinAPI.cpp
@@ -20,7 +20,9 @@ namespace AZ
             char resolvedPath[AZ_MAX_PATH_LEN];
             ResolvePath(filePath, resolvedPath, AZ_MAX_PATH_LEN);
 
-            DWORD fileAttributes = GetFileAttributesA(resolvedPath);
+            wchar_t resolvedPathW[AZ_MAX_PATH_LEN];
+            AZStd::to_wstring(resolvedPathW, AZ_MAX_PATH_LEN, resolvedPath);
+            DWORD fileAttributes = GetFileAttributesW(resolvedPathW);
             if (fileAttributes == INVALID_FILE_ATTRIBUTES)
             {
                 return false;
@@ -174,7 +176,7 @@ namespace AZ
 
         bool LocalFileIO::IsAbsolutePath(const char* path) const
         {
-            char drive[16];
+            char drive[16] = { 0 };
             _splitpath_s(path, drive, 16, nullptr, 0, nullptr, 0, nullptr, 0);
             return strlen(drive) > 0;
         }
diff --git a/Code/Legacy/CryCommon/CryFile.h b/Code/Legacy/CryCommon/CryFile.h
index 0888216f9c..0d2dac7c16 100644
--- a/Code/Legacy/CryCommon/CryFile.h
+++ b/Code/Legacy/CryCommon/CryFile.h
@@ -221,7 +221,7 @@ inline CCryFile::~CCryFile()
 inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlagsEx)
 {
     char tempfilename[CRYFILE_MAX_PATH] = "";
-    azstrcpy(tempfilename, filename);
+    azstrcpy(tempfilename, CRYFILE_MAX_PATH, filename);
 
 #if !defined (_RELEASE)
     if (gEnv && gEnv->IsEditor() && gEnv->pConsole)
@@ -233,7 +233,7 @@ inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlag
             if (lowercasePaths)
             {
                 const AZStd::string lowerString = PathUtil::ToLower(tempfilename);
-                azstrcpy(tempfilename, lowerString.c_str());
+                azstrcpy(tempfilename, CRYFILE_MAX_PATH, lowerString.c_str());
             }
         }
     }
@@ -242,7 +242,7 @@ inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlag
     {
         Close();
     }
-    azstrcpy(m_filename, tempfilename);
+    azstrcpy(m_filename, CRYFILE_MAX_PATH, tempfilename);
 
     if (m_pIArchive)
     {
@@ -429,7 +429,7 @@ inline const char* CCryFile::GetAdjustedFilename() const
     // Returns standard path otherwise.
     if (gameUrl != &szAdjustedFile[0])
     {
-        azstrcpy(szAdjustedFile, gameUrl);
+        azstrcpy(szAdjustedFile, AZ::IO::IArchive::MaxPath, gameUrl);
     }
     return szAdjustedFile;
 }
diff --git a/Code/Legacy/CryCommon/CryListenerSet.h b/Code/Legacy/CryCommon/CryListenerSet.h
index 6857cf7e5d..e5be89aa9f 100644
--- a/Code/Legacy/CryCommon/CryListenerSet.h
+++ b/Code/Legacy/CryCommon/CryListenerSet.h
@@ -418,7 +418,7 @@ inline size_t CListenerSet::MemSize() const
     size += sizeof(typename TAllocatedNameVec::value_type);
     for (typename TAllocatedNameVec::const_iterator iter(m_allocatedNames.begin()); iter != m_allocatedNames.end(); ++iter)
     {
-        size += iter->GetAllocatedMemory();
+        size += iter->capacity() * sizeof(char) + sizeof(AZStd::string);
     }
 #endif
 
diff --git a/Code/Legacy/CryCommon/CryName.h b/Code/Legacy/CryCommon/CryName.h
index 8e62a52517..552391419a 100644
--- a/Code/Legacy/CryCommon/CryName.h
+++ b/Code/Legacy/CryCommon/CryName.h
@@ -397,11 +397,11 @@ inline bool CCryName::operator>(const CCryName& n) const
 
 inline bool operator==(const AZStd::string& s, const CCryName& n)
 {
-    return s == n;
+    return s == n.c_str();
 }
 inline bool operator!=(const AZStd::string& s, const CCryName& n)
 {
-    return s != n;
+    return s != n.c_str();
 }
 
 inline bool operator==(const char* s, const CCryName& n)
@@ -545,11 +545,11 @@ inline bool CCryNameCRC::operator>(const CCryNameCRC& n) const
 
 inline bool operator==(const AZStd::string& s, const CCryNameCRC& n)
 {
-    return s == n;
+    return n == s.c_str();
 }
 inline bool operator!=(const AZStd::string& s, const CCryNameCRC& n)
 {
-    return s != n;
+    return n != s.c_str();
 }
 
 inline bool operator==(const char* s, const CCryNameCRC& n)
diff --git a/Code/Legacy/CryCommon/CryPath.h b/Code/Legacy/CryCommon/CryPath.h
index e01e7a2e4b..046006f738 100644
--- a/Code/Legacy/CryCommon/CryPath.h
+++ b/Code/Legacy/CryCommon/CryPath.h
@@ -419,7 +419,7 @@ namespace PathUtil
     //! Makes a fully specified file path from path and file name.
     inline stack_string Make(const stack_string& dir, const stack_string& filename, const stack_string& ext)
     {
-        AZStd::string path = filename;
+        AZStd::string path = filename.c_str();
         AZ::StringFunc::Path::ReplaceExtension(path, ext.c_str());
         path = AddSlash(dir.c_str()) + path;
         return stack_string(path.c_str());
diff --git a/Code/Legacy/CryCommon/ISerialize.h b/Code/Legacy/CryCommon/ISerialize.h
index 84e665850f..d427e222bb 100644
--- a/Code/Legacy/CryCommon/ISerialize.h
+++ b/Code/Legacy/CryCommon/ISerialize.h
@@ -387,7 +387,7 @@ public:
 
     bool ValueChar(const char* name, char* buffer, int len)
     {
-        string temp;
+        AZStd::string temp;
         if (IsReading())
         {
             Value(name, temp);
@@ -400,7 +400,7 @@ public:
         }
         else
         {
-            temp = string(buffer, buffer + len);
+            temp = AZStd::string(buffer, buffer + len);
             Value(name, temp);
         }
         return true;
diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
index e47d16d1bc..6507d7c8ee 100644
--- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
+++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
@@ -14,6 +14,8 @@
 #include 
 #include 
 #include 
+#include 
+
 /* Memory block identification */
 #define _FREE_BLOCK      0
 #define _NORMAL_BLOCK    1
@@ -344,7 +346,7 @@ private:
     char                                m_DirectoryName[260];           //!< directory name, needed when getting file attributes on the fly
     char                                m_ToMatch[260];                     //!< pattern to match with
     DIR*                                m_Dir;                                  //!< directory handle
-    std::vector m_Entries;                      //!< all file entries in the current directories
+    std::vector m_Entries;                      //!< all file entries in the current directories
 public:
 
     inline __finddata64_t()
diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp
index fe9c539569..74d383b88d 100644
--- a/Code/Legacy/CryCommon/WinBase.cpp
+++ b/Code/Legacy/CryCommon/WinBase.cpp
@@ -38,6 +38,7 @@
 #include 
 #include 
 #include 
+#include 
 
 #ifdef APPLE
 #include 
@@ -77,8 +78,6 @@ unsigned int g_EnableMultipleAssert = 0;//set to something else than 0 if to ena
     #include 
 #endif
 
-#include "StringUtils.h"
-
 #if AZ_TRAIT_COMPILER_DEFINE_FS_ERRNO_TYPE
 typedef int FS_ERRNO_TYPE;
 #if AZ_TRAIT_COMPILER_DEFINE_FS_STAT_TYPE
@@ -349,23 +348,23 @@ void _makepath(char* path, const char* drive, const char* dir, const char* filen
     }
     if (dir && dir[0])
     {
-        azstrcat(tmp, dir);
+        azstrcat(tmp, MAX_PATH, dir);
         ch = tmp[strlen(tmp) - 1];
         if (ch != '/' && ch != '\\')
         {
-            azstrcat(tmp, "\\");
+            azstrcat(tmp, MAX_PATH, "\\");
         }
     }
     if (filename && filename[0])
     {
-        azstrcat(tmp, filename);
+        azstrcat(tmp, MAX_PATH, filename);
         if (ext && ext[0])
         {
             if (ext[0] != '.')
             {
-                azstrcat(tmp, ".");
+                azstrcat(tmp, MAX_PATH, ".");
             }
-            azstrcat(tmp, ext);
+            azstrcat(tmp, MAX_PATH, ext);
         }
     }
     azstrcpy(path, strlen(tmp) + 1, tmp);
@@ -489,9 +488,9 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext
     typedef AZStd::fixed_string path_stack_string;
 
     const path_stack_string inPath(inpath);
-    string::size_type s = inPath.rfind('/', inPath.size());//position of last /
+    AZStd::string::size_type s = inPath.rfind('/', inPath.size());//position of last /
     path_stack_string fName;
-    if (s == string::npos)
+    if (s == AZStd::string::npos)
     {
         if (dir)
         {
@@ -503,9 +502,9 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext
     {
         if (dir)
         {
-            azstrcpy(dir, AZ_MAX_PATH_LEN, (inPath.substr((string::size_type)0, (string::size_type)(s + 1))).c_str());    //assign directory
+            azstrcpy(dir, AZ_MAX_PATH_LEN, (inPath.substr((AZStd::string::size_type)0, (AZStd::string::size_type)(s + 1))).c_str());    //assign directory
         }
-        fName = inPath.substr((string::size_type)(s + 1));                    //assign remaining string as rest
+        fName = inPath.substr((AZStd::string::size_type)(s + 1));                    //assign remaining string as rest
     }
     if (fName.size() == 0)
     {
@@ -521,8 +520,8 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext
     else
     {
         //dir and drive are now set
-        s = fName.find(".", (string::size_type)0);//position of first .
-        if (s == string::npos)
+        s = fName.find(".", (AZStd::string::size_type)0);//position of first .
+        if (s == AZStd::string::npos)
         {
             if (ext)
             {
@@ -547,7 +546,7 @@ void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext
                 }
                 else
                 {
-                    azstrcpy(fname, AZ_MAX_PATH_LEN, (fName.substr((string::size_type)0, s)).c_str());  //assign filename
+                    azstrcpy(fname, AZ_MAX_PATH_LEN, (fName.substr((AZStd::string::size_type)0, s)).c_str());  //assign filename
                 }
             }
         }
@@ -779,17 +778,17 @@ BOOL SystemTimeToFileTime(const SYSTEMTIME* syst, LPFILETIME ft)
     return TRUE;
 }
 
-void adaptFilenameToLinux(string& rAdjustedFilename)
+void adaptFilenameToLinux(AZStd::string& rAdjustedFilename)
 {
     //first replace all \\ by /
-    string::size_type loc = 0;
-    while ((loc = rAdjustedFilename.find("\\", loc)) != string::npos)
+    AZStd::string::size_type loc = 0;
+    while ((loc = rAdjustedFilename.find("\\", loc)) != AZStd::string::npos)
     {
         rAdjustedFilename.replace(loc, 1, "/");
     }
     loc = 0;
     //remove /./
-    while ((loc = rAdjustedFilename.find("/./", loc)) != string::npos)
+    while ((loc = rAdjustedFilename.find("/./", loc)) != AZStd::string::npos)
     {
         rAdjustedFilename.replace(loc, 3, "/");
     }
@@ -798,16 +797,16 @@ void adaptFilenameToLinux(string& rAdjustedFilename)
 void replaceDoublePathFilename(char* szFileName)
 {
     //replace "\.\" by "\"
-    string s(szFileName);
-    string::size_type loc = 0;
+    AZStd::string s(szFileName);
+    AZStd::string::size_type loc = 0;
     //remove /./
-    while ((loc = s.find("/./", loc)) != string::npos)
+    while ((loc = s.find("/./", loc)) != AZStd::string::npos)
     {
         s.replace(loc, 3, "/");
     }
     loc = 0;
     //remove "\.\"
-    while ((loc = s.find("\\.\\", loc)) != string::npos)
+    while ((loc = s.find("\\.\\", loc)) != AZStd::string::npos)
     {
         s.replace(loc, 3, "\\");
     }
@@ -817,8 +816,8 @@ void replaceDoublePathFilename(char* szFileName)
 const int comparePathNames(const char* cpFirst, const char* cpSecond, unsigned int len)
 {
     //create two strings and replace the \\ by / and /./ by /
-    string first(cpFirst);
-    string second(cpSecond);
+    AZStd::string first(cpFirst);
+    AZStd::string second(cpSecond);
     adaptFilenameToLinux(first);
     adaptFilenameToLinux(second);
     if (strlen(cpFirst) < len || strlen(cpSecond) < len)
@@ -1618,14 +1617,16 @@ const bool GetFilenameNoCase
     return true;
 }
 
-DWORD GetFileAttributes(LPCSTR lpFileName)
+DWORD GetFileAttributes(LPCWSTR lpFileNameW)
 {
+    AZStd::string lpFileName;
+    AZStd::to_string(lpFileName, lpFileNameW);
     struct stat fileStats;
-    const int success = stat(lpFileName, &fileStats);
+    const int success = stat(lpFileName.c_str(), &fileStats);
     if (success == -1)
     {
         char adjustedFilename[MAX_PATH];
-        GetFilenameNoCase(lpFileName, adjustedFilename);
+        GetFilenameNoCase(lpFileName.c_str(), adjustedFilename);
         if (stat(adjustedFilename, &fileStats) == -1)
         {
             return (DWORD)INVALID_FILE_ATTRIBUTES;
@@ -1648,7 +1649,7 @@ DWORD GetFileAttributes(LPCSTR lpFileName)
 uint32 CryGetFileAttributes(const char* lpFileName)
 {
     
-    string fn = lpFileName;
+    AZStd::string fn = lpFileName;
     adaptFilenameToLinux(fn);
     const char* buffer = fn.c_str();
     return GetFileAttributes(buffer);
diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp
index 289d4070ff..c0923341ad 100644
--- a/Code/Legacy/CrySystem/DebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/DebugCallStack.cpp
@@ -435,18 +435,18 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
     {
         const char* const szMessage = m_bIsFatalError ? s_szFatalErrorCode : m_szBugMessage;
         excName = szMessage;
-        azstrcpy(excCode, szMessage);
-        azstrcpy(excAddr, "");
-        azstrcpy(desc, "");
-        azstrcpy(m_excModule, "");
-        azstrcpy(excDesc, szMessage);
+        azstrcpy(excCode, AZ_ARRAY_SIZE(excCode), szMessage);
+        azstrcpy(excAddr, AZ_ARRAY_SIZE(excAddr), "");
+        azstrcpy(desc, AZ_ARRAY_SIZE(desc), "");
+        azstrcpy(m_excModule, AZ_ARRAY_SIZE(m_excModule), "");
+        azstrcpy(excDesc, AZ_ARRAY_SIZE(excDesc), szMessage);
     }
     else
     {
         sprintf_s(excAddr, "0x%04X:0x%p", pex->ContextRecord->SegCs, pex->ExceptionRecord->ExceptionAddress);
         sprintf_s(excCode, "0x%08X", pex->ExceptionRecord->ExceptionCode);
         excName = TranslateExceptionCode(pex->ExceptionRecord->ExceptionCode);
-        azstrcpy(desc, "");
+        azstrcpy(desc, AZ_ARRAY_SIZE(desc), "");
         sprintf_s(excDesc, "%s\r\n%s", excName, desc);
 
 
@@ -476,9 +476,9 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
     WriteLineToLog("Exception Description: %s", desc);
 
 
-    azstrcpy(m_excDesc, excDesc);
-    azstrcpy(m_excAddr, excAddr);
-    azstrcpy(m_excCode, excCode);
+    azstrcpy(m_excDesc, AZ_ARRAY_SIZE(m_excDesc), excDesc);
+    azstrcpy(m_excAddr, AZ_ARRAY_SIZE(m_excAddr), excAddr);
+    azstrcpy(m_excCode, AZ_ARRAY_SIZE(m_excCode), excCode);
 
 
     char errs[32768];
@@ -504,7 +504,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         dumpCallStack(funcs);
         // Fill call stack.
         char str[s_iCallStackSize];
-        azstrcpy(str, "");
+        azstrcpy(str, AZ_ARRAY_SIZE(str), "");
         for (unsigned int i = 0; i < funcs.size(); i++)
         {
             char temp[s_iCallStackSize];
@@ -514,7 +514,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
             azstrcat(errs, temp);
             azstrcat(errs, "\n");
         }
-        azstrcpy(m_excCallstack, str);
+        azstrcpy(m_excCallstack, AZ_ARRAY_SIZE(m_excCallstack), str);
     }
 
     azstrcat(errorString, errs);
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp
index bee43b237b..1176c15f0e 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp
@@ -237,7 +237,7 @@ void IDebugCallStack::WriteLineToLog(const char* format, ...)
     char        szBuffer[MAX_WARNING_LENGTH];
     va_start(ArgList, format);
     vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, format, ArgList);
-    azstrcat(szBuffer, "\n");
+    azstrcat(szBuffer, MAX_WARNING_LENGTH, "\n");
     szBuffer[sizeof(szBuffer) - 1] = '\0';
     va_end(ArgList);
 
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.h b/Code/Legacy/CrySystem/IDebugCallStack.h
index a2c1d3f5e2..1a65fbbdb7 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.h
+++ b/Code/Legacy/CrySystem/IDebugCallStack.h
@@ -41,11 +41,7 @@ public:
         filename = "[unknown]";
         line = 0;
         baseAddr = addr;
-#if defined(PLATFORM_64BIT)
-        procName = AZStd::string::format("[%016llX]", addr);
-#else
-        procName = AZStd::string::format("[%08X]", addr);
-#endif
+        procName = AZStd::string::format("[%p]", addr);
     }
 
     // returns current filename
diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
index 3e6432a721..d21fff3dd3 100644
--- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
+++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
@@ -567,7 +567,7 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName)
     INDENT_LOG_DURING_SCOPE();
 
     char levelName[256];
-    azstrcpy(levelName, _levelName);
+    azstrcpy(levelName, AZ_ARRAY_SIZE(levelName), _levelName);
 
     // Not remove a scope!!!
     {
diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
index 42bdb3afef..cffe1c38c6 100644
--- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp
+++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
@@ -2762,7 +2762,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
     const size_t bufSize = sizeof(buf) / sizeof(buf[0]);
     wcsftime(buf, bufSize, bShowSeconds ? L"%#X" : L"%X", &theTime);
     buf[bufSize - 1] = 0;
-    Unicode::Convert(outTimeString, buf);
+    AZStd::to_string(outTimeString, buf);
 }
 
 void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, AZStd::string& outDateString)
@@ -2790,7 +2790,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
     const wchar_t* format = bShort ? (bIncludeWeekday ? L"%a %x" : L"%x") : L"%#x"; // long format always contains Weekday name
     wcsftime(buf, bufSize, format, &theTime);
     buf[bufSize - 1] = 0;
-    Unicode::Convert(outDateString, buf);
+    AZStd::to_string(outDateString, buf);
 }
 
 
diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp
index 6ee6af6c22..0385ff8eb3 100644
--- a/Code/Legacy/CrySystem/Log.cpp
+++ b/Code/Legacy/CrySystem/Log.cpp
@@ -508,7 +508,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
             stack_string s = szBuffer;
             s += "\t ";
             s += sAssetScope;
-            azstrcpy(szBuffer, s.c_str());
+            azstrcpy(szBuffer, AZ_ARRAY_SIZE(szBuffer), s.c_str());
         }
     }
 
@@ -531,7 +531,7 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
             }
         }
         i = m_iLastHistoryItem = m_iLastHistoryItem + 1 & sz - 1;
-        azstrcpy(m_history[i].str, m_history[i].ptr = szSpamCheck);
+        azstrcpy(m_history[i].str, AZ_ARRAY_SIZE(m_history[i].str), m_history[i].ptr = szSpamCheck);
         m_history[i].type = type;
         m_history[i].time = time;
     }
@@ -862,7 +862,7 @@ bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SL
     {
         // When logging from other thread then main, push all log strings to queue.
         SLogMsg msg;
-        azstrcpy(msg.msg, szString);
+        azstrcpy(msg.msg, AZ_ARRAY_SIZE(msg.msg), szString);
         msg.bAdd = bAdd;
         msg.destination = destination;
         msg.logType = logType;
@@ -1277,7 +1277,7 @@ void CLog::CreateBackupFile() const
 
     AZStd::string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt);
     fileSystem->CreatePath(LOG_BACKUP_PATH);
-    azstrcpy(m_sBackupFilename, bakdest.c_str());
+    azstrcpy(m_sBackupFilename, AZ_ARRAY_SIZE(m_sBackupFilename), bakdest.c_str());
     // Remove any existing backup file with the same name first since the copy will fail otherwise.
     fileSystem->Remove(m_sBackupFilename);
     fileSystem->Copy(m_szFilename, bakdest.c_str());
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index 9fd01f1905..66be2a2ca5 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -282,7 +282,7 @@ static const char* GetLastSystemErrorMessage()
                 0,
                 NULL))
         {
-            azstrcpy(szBuffer, (char*)lpMsgBuf);
+            azstrcpy(szBuffer, AZ_ARRAY_SIZE(szBuffer), (char*)lpMsgBuf);
             LocalFree(lpMsgBuf);
         }
         else
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index 252ab8137d..6da42420f8 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -1547,31 +1547,31 @@ const char* CXConsole::GetFlagsString(const uint32 dwFlags)
     // hiding this makes it a bit more difficult for cheaters
     //  if(dwFlags&VF_CHEAT)                  azstrcat( sFlags,"CHEAT, ");
 
-    azstrcpy(sFlags, "");
+    azstrcpy(sFlags, AZ_ARRAY_SIZE(sFlags), "");
 
     if (dwFlags & VF_READONLY)
     {
-        azstrcat(sFlags, "READONLY, ");
+        azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "READONLY, ");
     }
     if (dwFlags & VF_DEPRECATED)
     {
-        azstrcat(sFlags, "DEPRECATED, ");
+        azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "DEPRECATED, ");
     }
     if (dwFlags & VF_DUMPTODISK)
     {
-        azstrcat(sFlags, "DUMPTODISK, ");
+        azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "DUMPTODISK, ");
     }
     if (dwFlags & VF_REQUIRE_LEVEL_RELOAD)
     {
-        azstrcat(sFlags, "REQUIRE_LEVEL_RELOAD, ");
+        azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "REQUIRE_LEVEL_RELOAD, ");
     }
     if (dwFlags & VF_REQUIRE_APP_RESTART)
     {
-        azstrcat(sFlags, "REQUIRE_APP_RESTART, ");
+        azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "REQUIRE_APP_RESTART, ");
     }
     if (dwFlags & VF_RESTRICTEDMODE)
     {
-        azstrcat(sFlags, "RESTRICTEDMODE, ");
+        azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "RESTRICTEDMODE, ");
     }
 
     if (sFlags[0] != 0)
@@ -3325,7 +3325,7 @@ const char* CXConsole::AutoComplete(const char* substr)
         const char* szCmd = cmds[i];
 
         size_t cmdlen = strlen(szCmd);
-        if (cmdlen >= substrLen && azmemicmp(szCmd, substr, substrLen) == 0)
+        if (cmdlen >= substrLen && azstrnicmp(szCmd, substr, substrLen) == 0)
         {
             if (substrLen == cmdlen)
             {
diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp
index e59f6b8969..c86c0691a9 100644
--- a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp
+++ b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp
@@ -32,7 +32,7 @@ const char* XMLBinary::XMLBinaryReader::GetErrorDescription() const
 
 void XMLBinary::XMLBinaryReader::SetErrorDescription(const char* text)
 {
-    azstrcpy(m_errorDescription, text);
+    azstrcpy(m_errorDescription, AZ_ARRAY_SIZE(m_errorDescription), text);
 }
 
 
diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp
index 81994b26e0..7fd9df30c9 100644
--- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp
+++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp
@@ -99,7 +99,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node,
     static const uint nMaxNodeCount = (NodeIndex) ~0;
     if (m_nodes.size() > nMaxNodeCount)
     {
-        error = AZStd::string::format("XMLBinary: Too many nodes: %d (max is %i)", m_nodes.size(), nMaxNodeCount);
+        error = AZStd::string::format("XMLBinary: Too many nodes: %zu (max is %i)", m_nodes.size(), nMaxNodeCount);
         return false;
     }
 
diff --git a/Code/Tools/GridHub/GridHub/gridhub.cpp b/Code/Tools/GridHub/GridHub/gridhub.cpp
index 978589ab74..24dd440411 100644
--- a/Code/Tools/GridHub/GridHub/gridhub.cpp
+++ b/Code/Tools/GridHub/GridHub/gridhub.cpp
@@ -543,7 +543,7 @@ GridHubComponent::OnMemberJoined([[maybe_unused]] GridMate::GridSession* session
     case AZ::PlatformID::PLATFORM_WINDOWS_64:
     case AZ::PlatformID::PLATFORM_APPLE_MAC:
         {
-            GridMate::string localMachineName = GridMate::Utils::GetMachineAddress();
+            AZStd::string localMachineName = GridMate::Utils::GetMachineAddress();
             if( member->GetMachineName() == localMachineName )
             {
                 ExternalProcessMonitor mi;
@@ -629,7 +629,7 @@ bool GridHubComponent::StartSession(bool isRestarting)
     AZ_Assert(GridMate::HasGridMateService(m_gridMate), "Failed to start multiplayer service for LAN!");
 
     // if we get an address 169.X.X.X (AZCP is NOT ready) or 127.0.0.1 when network is not ready
-    GridMate::string machineIP = GridMate::Utils::GetMachineAddress();
+    AZStd::string machineIP = GridMate::Utils::GetMachineAddress();
     if( machineIP == "127.0.0.1" || machineIP.compare(0,4,"169.") == 0 )
     {
         AZ_Warning("GridHub", false, "\nCurrent IP %s might be invalid.\n",machineIP.c_str());
diff --git a/Code/Tools/GridHub/GridHub/gridhub.hxx b/Code/Tools/GridHub/GridHub/gridhub.hxx
index 468cf525a0..849dbb92e1 100644
--- a/Code/Tools/GridHub/GridHub/gridhub.hxx
+++ b/Code/Tools/GridHub/GridHub/gridhub.hxx
@@ -141,7 +141,7 @@ public:
     /// Callback that notifies the title when a session will be left. session pointer is NOT valid after the callback returns.
     void OnSessionDelete(GridMate::GridSession* session) override;
     /// Called when a session error occurs.
-    void OnSessionError(GridMate::GridSession* session, const GridMate::string& errorMsg ) { (void)session; (void)errorMsg; }
+    void OnSessionError(GridMate::GridSession* session, const AZStd::string& errorMsg ) { (void)session; (void)errorMsg; }
     /// Called when the actual game(match) starts
     void OnSessionStart(GridMate::GridSession* session) { (void)session; }
     /// Called when the actual game(match) ends
diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp
index 2630a63bee..dd65722560 100644
--- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp
+++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp
@@ -11,6 +11,7 @@
 #include 
 
 #include 
+#include 
 
 namespace TestImpact
 {
@@ -55,9 +56,11 @@ namespace TestImpact
 
         CreatePipes(sa, si);
 
-        if (!CreateProcess(
+        AZStd::wstring argsW;
+        AZStd::to_wstring(argsW, args.c_str());
+        if (!CreateProcessW(
             NULL,
-            &args[0],
+            argsW.c_str(),
             NULL,
             NULL,
             IsPiping(),
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
index ae0880e98e..a38736ff67 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp
@@ -2362,10 +2362,10 @@ void CUiAnimViewDopeSheetBase::DrawKeys(CUiAnimViewTrack* pTrack, QPainter* pain
                 }
                 else
                 {
-                    azstrcpy(keydesc, "{");
+                    azstrcpy(keydesc, AZ_ARRAY_SIZE(keydesc), "{");
                 }
-                azstrcat(keydesc, pDescription);
-                azstrcat(keydesc, "}");
+                azstrcat(keydesc, AZ_ARRAY_SIZE(keydesc), pDescription);
+                azstrcat(keydesc, AZ_ARRAY_SIZE(keydesc), "}");
                 // Draw key description text.
                 // Find next key.
                 const QRect textRect(QPoint(x + 10, rect.top()), QPoint(x1, rect.bottom()));
diff --git a/Gems/LyShine/Code/Source/Platform/Common/Unimplemented/UiClipboard_Unimplemented.cpp b/Gems/LyShine/Code/Source/Platform/Common/Unimplemented/UiClipboard_Unimplemented.cpp
index 744cb65ac8..9175c7b2be 100644
--- a/Gems/LyShine/Code/Source/Platform/Common/Unimplemented/UiClipboard_Unimplemented.cpp
+++ b/Gems/LyShine/Code/Source/Platform/Common/Unimplemented/UiClipboard_Unimplemented.cpp
@@ -8,16 +8,13 @@
 // UiClipboard is responsible setting and getting clipboard data for the UI elements in a platform-independent way.
 
 #include "UiClipboard.h"
-#include 
 
-bool UiClipboard::SetText(const AZStd::string& text)
+bool UiClipboard::SetText([[maybe_unused]] const AZStd::string& text)
 {
-    AZ_UNUSED(text);
     return false;
 }
 
 AZStd::string UiClipboard::GetText()
 {
-    AZStd::string outText;
-    return outText;
+    return {};
 }
diff --git a/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp
index 60d578d1f8..f4faf4dbeb 100644
--- a/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/CaptureTrack.cpp
@@ -52,7 +52,7 @@ void CCaptureTrack::GetKeyInfo(int key, const char*& description, float& duratio
     char prefix[64] = "Frame";
     if (!m_keys[key].prefix.empty())
     {
-        azstrcpy(prefix, m_keys[key].prefix.c_str());
+        azstrcpy(prefix, AZ_ARRAY_SIZE(prefix), m_keys[key].prefix.c_str());
     }
     description = buffer;
     if (!m_keys[key].folder.empty())
diff --git a/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp
index 1dd72de567..8c1baf4684 100644
--- a/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/CommentTrack.cpp
@@ -25,7 +25,7 @@ void CCommentTrack::GetKeyInfo(int key, const char*& description, float& duratio
     description = 0;
     duration = m_keys[key].m_duration;
 
-    azstrcpy(desc, m_keys[key].m_strComment.c_str());
+    azstrcpy(desc, AZ_ARRAY_SIZE(desc), m_keys[key].m_strComment.c_str());
 
     description = desc;
 }
diff --git a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
index 62de2dfdf5..884a90b200 100644
--- a/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/CompoundSplineTrack.cpp
@@ -457,31 +457,31 @@ void CCompoundSplineTrack::GetKeyInfo(int key, const char*& description, float&
         {
             float dummy;
             m_subTracks[0]->GetKeyInfo(m, subDesc, dummy);
-            azstrcat(str, subDesc);
+            azstrcat(str, AZ_ARRAY_SIZE(str), subDesc);
             break;
         }
     }
     if (m == m_subTracks[0]->GetNumKeys())
     {
-        azstrcat(str, m_subTrackNames[0].c_str());
+        azstrcat(str, AZ_ARRAY_SIZE(str), m_subTrackNames[0].c_str());
     }
     // Tail cases
     for (int i = 1; i < GetSubTrackCount(); ++i)
     {
-        azstrcat(str, ",");
+        azstrcat(str, AZ_ARRAY_SIZE(str), ",");
         for (m = 0; m < m_subTracks[i]->GetNumKeys(); ++m)
         {
             if (m_subTracks[i]->GetKeyTime(m) == time)
             {
                 float dummy;
                 m_subTracks[i]->GetKeyInfo(m, subDesc, dummy);
-                azstrcat(str, subDesc);
+                azstrcat(str, AZ_ARRAY_SIZE(str), subDesc);
                 break;
             }
         }
         if (m == m_subTracks[i]->GetNumKeys())
         {
-            azstrcat(str, m_subTrackNames[i].c_str());
+            azstrcat(str, AZ_ARRAY_SIZE(str), m_subTrackNames[i].c_str());
         }
     }
 }
diff --git a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
index 36d468e36d..4d32a4a4a1 100644
--- a/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/EventTrack.cpp
@@ -69,11 +69,11 @@ void CEventTrack::GetKeyInfo(int key, const char*& description, float& duration)
     CheckValid();
     description = 0;
     duration = 0;
-    azstrcpy(desc, m_keys[key].event.c_str());
+    azstrcpy(desc, AZ_ARRAY_SIZE(desc), m_keys[key].event.c_str());
     if (!m_keys[key].eventValue.empty())
     {
-        azstrcat(desc, ", ");
-        azstrcat(desc, m_keys[key].eventValue.c_str());
+        azstrcat(desc, AZ_ARRAY_SIZE(desc), ", ");
+        azstrcat(desc, AZ_ARRAY_SIZE(desc), m_keys[key].eventValue.c_str());
     }
 
     description = desc;
diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
index 799747eb12..be6d18eeb2 100644
--- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp
@@ -916,8 +916,8 @@ void CAnimSceneNode::ApplyCameraKey(ISelectKey& key, SAnimContext& ec)
 void CAnimSceneNode::ApplyEventKey(IEventKey& key, [[maybe_unused]] SAnimContext& ec)
 {
     char funcName[1024];
-    azstrcpy(funcName, "Event_");
-    azstrcat(funcName, key.event.c_str());
+    azstrcpy(funcName, AZ_ARRAY_SIZE(funcName), "Event_");
+    azstrcat(funcName, AZ_ARRAY_SIZE(funcName), key.event.c_str());
     gEnv->pMovieSystem->SendGlobalEvent(funcName);
 }
 
diff --git a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
index 3541fe718e..9ac19f91ea 100644
--- a/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/ScreenFaderTrack.cpp
@@ -32,7 +32,7 @@ void CScreenFaderTrack::GetKeyInfo(int key, const char*& description, float& dur
     CheckValid();
     description = 0;
     duration = m_keys[key].m_fadeTime;
-    azstrcpy(desc, m_keys[key].m_fadeType == IScreenFaderKey::eFT_FadeIn ? "In" : "Out");
+    azstrcpy(desc, AZ_ARRAY_SIZE(desc), m_keys[key].m_fadeType == IScreenFaderKey::eFT_FadeIn ? "In" : "Out");
 
     description = desc;
 }
diff --git a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
index 25d709bcdc..83b141cfb2 100644
--- a/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/TrackEventTrack.cpp
@@ -143,11 +143,11 @@ void CTrackEventTrack::GetKeyInfo(int key, const char*& description, float& dura
     CheckValid();
     description = 0;
     duration = 0;
-    azstrcpy(desc, m_keys[key].event.c_str());
+    azstrcpy(desc, AZ_ARRAY_SIZE(desc), m_keys[key].event.c_str());
     if (!m_keys[key].eventValue.empty())
     {
-        azstrcat(desc, ", ");
-        azstrcat(desc, m_keys[key].eventValue.c_str());
+        azstrcat(desc, AZ_ARRAY_SIZE(desc), ", ");
+        azstrcat(desc, AZ_ARRAY_SIZE(desc), m_keys[key].eventValue.c_str());
     }
 
     description = desc;

From 82c5f80fbd163317d823f4d700befc971562a1ea Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 3 Aug 2021 18:56:46 -0700
Subject: [PATCH 047/205] More windows/linux fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Framework/AzCore/AzCore/base.h           | 20 +++++++++----------
 Code/Framework/AzCore/Tests/Debug.cpp         |  4 ++--
 Code/Legacy/CryCommon/platform_impl.cpp       |  2 +-
 Code/Legacy/CrySystem/DebugCallStack.cpp      | 16 +++++++--------
 .../Code/Editor/Animation/UiAnimViewNodes.cpp |  2 +-
 5 files changed, 22 insertions(+), 22 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/base.h b/Code/Framework/AzCore/AzCore/base.h
index 00fdbf515e..20f5c17b27 100644
--- a/Code/Framework/AzCore/AzCore/base.h
+++ b/Code/Framework/AzCore/AzCore/base.h
@@ -71,7 +71,7 @@
 
 // note: for cross-platform compatibility, do not use the return value of azfopen. On Windows, it's an errno_t and 0 indicates success. On other platforms, the return value is a FILE*, and a 0 value indicates failure.
 #   define azfopen(_fp, _filename, _attrib)                 fopen_s(_fp, _filename, _attrib)
-#   define azfscanf         fscanf_s
+#   define azfscanf                                         fscanf_s
 
 #   define azsprintf(_buffer, ...)                          sprintf_s(_buffer, AZ_ARRAY_SIZE(_buffer), __VA_ARGS__)
 #   define azstrlwr                                         _strlwr_s
@@ -118,19 +118,19 @@
 #   define azfopen(_fp, _filename, _attrib)                 *(_fp) = fopen(_filename, _attrib)
 #   define azfscanf                                         fscanf
 
-#   define azsprintf       sprintf
-#   define azstrlwr(_buffer, _size)             strlwr(_buffer)
-#   define azvsprintf       vsprintf
-#   define azwcscpy(_dest, _size, _buffer)      wcscpy(_dest, _buffer)
-#   define azstrtime        _strtime
-#   define azstrdate        _strdate
-#   define azlocaltime      localtime_r
+#   define azsprintf                                        sprintf
+#   define azstrlwr(_buffer, _size)                         strlwr(_buffer)
+#   define azvsprintf                                       vsprintf
+#   define azwcscpy(_dest, _size, _buffer)                  wcscpy(_dest, _buffer)
+#   define azstrtime                                        _strtime
+#   define azstrdate                                        _strdate
+#   define azlocaltime                                      localtime_r
 #endif
 
 #if AZ_TRAIT_USE_POSIX_STRERROR_R
-#   define azstrerror_s(_dst, _num, _err)   strerror_r(_err, _dst, _num)
+#   define azstrerror_s(_dst, _num, _err)                   strerror_r(_err, _dst, _num)
 #else
-#   define azstrerror_s strerror_s
+#   define azstrerror_s                                     strerror_s
 #endif
 
 #define AZ_INVALID_POINTER  reinterpret_cast(0x0badf00dul)
diff --git a/Code/Framework/AzCore/Tests/Debug.cpp b/Code/Framework/AzCore/Tests/Debug.cpp
index 3d214ffc68..6181823737 100644
--- a/Code/Framework/AzCore/Tests/Debug.cpp
+++ b/Code/Framework/AzCore/Tests/Debug.cpp
@@ -56,7 +56,7 @@ namespace UnitTest
                 int isFoundModule = 0;
                 char expectedNameBuffer[AZ_ARRAY_SIZE(SymbolStorage::ModuleInfo::m_modName)];
 #if defined(AZCORETEST_DLL_NAME)
-                azstrncpy(expectedNameBuffer, AZCORETEST_DLL_NAME, AZ_ARRAY_SIZE(expectedNameBuffer));
+                azstrncpy(expectedNameBuffer, AZ_ARRAY_SIZE(expectedNameBuffer), AZCORETEST_DLL_NAME, AZ_ARRAY_SIZE(expectedNameBuffer));
 #else
                 azstrncpy(expectedNameBuffer, "azcoretests.dll", AZ_ARRAY_SIZE(expectedNameBuffer));
 #endif
@@ -65,7 +65,7 @@ namespace UnitTest
                 for (u32 i = 0; i < SymbolStorage::GetNumLoadedModules(); ++i)
                 {
                     char nameBuffer[AZ_ARRAY_SIZE(SymbolStorage::ModuleInfo::m_modName)];
-                    azstrncpy(nameBuffer, SymbolStorage::GetModuleInfo(i)->m_fileName, AZ_ARRAY_SIZE(nameBuffer));
+                    azstrncpy(nameBuffer, AZ_ARRAY_SIZE(nameBuffer), SymbolStorage::GetModuleInfo(i)->m_fileName, AZ_ARRAY_SIZE(nameBuffer));
                     AZStd::to_lower(nameBuffer, nameBuffer + AZ_ARRAY_SIZE(nameBuffer));
 
                     if (strstr(nameBuffer, expectedNameBuffer))
diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp
index 1523622538..3d7b2180fc 100644
--- a/Code/Legacy/CryCommon/platform_impl.cpp
+++ b/Code/Legacy/CryCommon/platform_impl.cpp
@@ -288,7 +288,7 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], uint
                 firstIteration = false;
             }
             // Check if the engineroot exists
-            azstrcat(szPath, "\\engine.json");
+            azstrcat(szPath, AZ_ARRAY_SIZE(szPath), "\\engine.json");
             WIN32_FILE_ATTRIBUTE_DATA data;
             AZStd::wstring szPathW;
             AZStd::to_wstring(szPathW, szPath);
diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp
index c0923341ad..ef27ef2c59 100644
--- a/Code/Legacy/CrySystem/DebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/DebugCallStack.cpp
@@ -419,8 +419,8 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
     char versionbuf[1024];
     azstrcpy(versionbuf, AZ_ARRAY_SIZE(versionbuf), "");
     PutVersion(versionbuf, AZ_ARRAY_SIZE(versionbuf));
-    azstrcat(errorString, versionbuf);
-    azstrcat(errorString, "\n");
+    azstrcat(errorString, AZ_ARRAY_SIZE(errorString), versionbuf);
+    azstrcat(errorString, AZ_ARRAY_SIZE(errorString), "\n");
 
     char excCode[MAX_WARNING_LENGTH];
     char excAddr[80];
@@ -486,7 +486,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         excCode, excAddr, m_excModule, excName, desc);
 
 
-    azstrcat(errs, "\nCall Stack Trace:\n");
+    azstrcat(errs, AZ_ARRAY_SIZE(errs), "\nCall Stack Trace:\n");
 
     std::vector funcs;
     {
@@ -509,15 +509,15 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
         {
             char temp[s_iCallStackSize];
             sprintf_s(temp, "%2zd) %s", funcs.size() - i, (const char*)funcs[i].c_str());
-            azstrcat(str, temp);
-            azstrcat(str, "\r\n");
-            azstrcat(errs, temp);
-            azstrcat(errs, "\n");
+            azstrcat(str, AZ_ARRAY_SIZE(str), temp);
+            azstrcat(str, AZ_ARRAY_SIZE(str), "\r\n");
+            azstrcat(errs, AZ_ARRAY_SIZE(errs), temp);
+            azstrcat(errs, AZ_ARRAY_SIZE(errs), "\n");
         }
         azstrcpy(m_excCallstack, AZ_ARRAY_SIZE(m_excCallstack), str);
     }
 
-    azstrcat(errorString, errs);
+    azstrcat(errorString, AZ_ARRAY_SIZE(errorString), errs);
 
     if (f)
     {
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
index 67fd542c3f..679477e3d3 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp
@@ -1512,7 +1512,7 @@ int CUiAnimViewNodesCtrl::GetMatNameAndSubMtlIndexFromName(QString& matName, con
     if (const char* pCh = strstr(nodeName, ".["))
     {
         char matPath[MAX_PATH];
-        azstrncpy(matPath, nodeName, (size_t)(pCh - nodeName));
+        azstrncpy(matPath, AZ_ARRAY_SIZE(matPath), nodeName, (size_t)(pCh - nodeName));
         matName = matPath;
         pCh += 2;
         if ((*pCh) != 0)

From eeed7df429f0d25917e42e5217b460bfcc41c2eb Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 3 Aug 2021 20:24:36 -0700
Subject: [PATCH 048/205] fixing no unity builds

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../ProjectSettingsContainer.cpp              |  1 +
 .../GridMate/Carrier/DefaultHandshake.h       |  1 +
 .../Carrier/DefaultTrafficControl.cpp         |  1 +
 .../GridMate/Carrier/DefaultTrafficControl.h  |  2 ++
 .../GridMate/GridMate/Carrier/Handshake.h     |  1 +
 Code/Legacy/CryCommon/Linux_Win32Wrapper.h    |  2 +-
 Code/Legacy/CryCommon/WinBase.cpp             | 25 +++++++++++++++++--
 .../Code/Source/Animation/AnimSequence.cpp    |  2 ++
 .../Code/Source/SystemComponent.cpp           |  1 +
 9 files changed, 33 insertions(+), 3 deletions(-)

diff --git a/Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsContainer.cpp b/Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsContainer.cpp
index a7a238d241..772469808b 100644
--- a/Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsContainer.cpp
+++ b/Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsContainer.cpp
@@ -8,6 +8,7 @@
 
 #include "ProjectSettingsContainer.h"
 
+#include 
 #include 
 #include 
 #include 
diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
index 8f456e4649..9225cca8d7 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultHandshake.h
@@ -9,6 +9,7 @@
 #define GM_DEFAULT_HANDSHAKE_H
 
 #include 
+#include 
 
 namespace GridMate
 {
diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.cpp b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.cpp
index 5da3c784ff..f9280d9918 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.cpp
@@ -12,6 +12,7 @@
 
 #include 
 #include 
+#include 
 
 using namespace GridMate;
 
diff --git a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h
index 1d8a1f6b46..259c619f53 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/DefaultTrafficControl.h
@@ -12,6 +12,8 @@
 
 #include 
 
+#include 
+
 namespace GridMate
 {
     /**
diff --git a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
index 0f825da49b..5f67b6637c 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
+++ b/Code/Framework/GridMate/GridMate/Carrier/Handshake.h
@@ -10,6 +10,7 @@
 
 #include 
 #include 
+#include 
 
 namespace GridMate
 {
diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
index 6507d7c8ee..912546cb7b 100644
--- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
+++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
@@ -378,7 +378,7 @@ typedef struct _finddata_t
 extern int _findnext64(intptr_t last, __finddata64_t* pFindData);
 extern intptr_t _findfirst64(const char* pFileName, __finddata64_t* pFindData);
 
-extern DWORD GetFileAttributes(LPCSTR lpFileName);
+extern DWORD GetFileAttributesW(LPCWSTR lpFileName);
 
 extern const bool GetFilenameNoCase(const char* file, char*, const bool cCreateNew = false);
 
diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp
index 74d383b88d..64e9d9b066 100644
--- a/Code/Legacy/CryCommon/WinBase.cpp
+++ b/Code/Legacy/CryCommon/WinBase.cpp
@@ -1648,12 +1648,33 @@ DWORD GetFileAttributes(LPCWSTR lpFileNameW)
 
 uint32 CryGetFileAttributes(const char* lpFileName)
 {
-    
     AZStd::string fn = lpFileName;
     adaptFilenameToLinux(fn);
     const char* buffer = fn.c_str();
-    return GetFileAttributes(buffer);
     
+    struct stat fileStats;
+    const int success = stat(buffer, &fileStats);
+    if (success == -1)
+    {
+        char adjustedFilename[MAX_PATH];
+        GetFilenameNoCase(buffer, adjustedFilename);
+        if (stat(adjustedFilename, &fileStats) == -1)
+        {
+            return (DWORD)INVALID_FILE_ATTRIBUTES;
+        }
+    }
+    DWORD ret = 0;
+
+    const int acc = (fileStats.st_mode & S_IWRITE);
+
+    if (acc != 0)
+    {
+        if (S_ISDIR(fileStats.st_mode) != 0)
+        {
+            ret |= FILE_ATTRIBUTE_DIRECTORY;
+        }
+    }
+    return (ret == 0) ? FILE_ATTRIBUTE_NORMAL : ret;//return file attribute normal as the default value, must only be set if no other attributes have been found    
 }
 
 __finddata64_t::~__finddata64_t()
diff --git a/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp b/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
index 43a80d5002..0b19c4a06a 100644
--- a/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
+++ b/Gems/LyShine/Code/Source/Animation/AnimSequence.cpp
@@ -594,6 +594,8 @@ void CUiAnimSequence::Activate()
     }
 }
 
+typedef AZStd::fixed_string<512> stack_string;
+
 //////////////////////////////////////////////////////////////////////////
 void CUiAnimSequence::Deactivate()
 {
diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
index 4944626d77..f46c8e229a 100644
--- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
+++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
@@ -30,6 +30,7 @@
 #include 
 
 #include 
+#include 
 
 #include 
 

From 9bab6761096d1490f487f296ed32efb728707686 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 3 Aug 2021 20:25:21 -0700
Subject: [PATCH 049/205] enabling test impact framework tool build and fixed
 it

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Tools/TestImpactFramework/CMakeLists.txt               | 6 ++----
 .../Platform/Windows/Process/TestImpactWin32_Process.cpp    | 2 +-
 2 files changed, 3 insertions(+), 5 deletions(-)

diff --git a/Code/Tools/TestImpactFramework/CMakeLists.txt b/Code/Tools/TestImpactFramework/CMakeLists.txt
index 04cbee98dc..1cdf02d101 100644
--- a/Code/Tools/TestImpactFramework/CMakeLists.txt
+++ b/Code/Tools/TestImpactFramework/CMakeLists.txt
@@ -11,8 +11,6 @@ ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Platf
 include(${pal_source_dir}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake)
 
 if(PAL_TRAIT_TEST_IMPACT_FRAMEWORK_SUPPORTED)
-    if(LY_TEST_IMPACT_INSTRUMENTATION_BIN)
-        add_subdirectory(Runtime)
-        add_subdirectory(Frontend)
-    endif()
+    add_subdirectory(Runtime)
+    add_subdirectory(Frontend)
 endif()
diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp
index dd65722560..7ba061f932 100644
--- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp
+++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Process.cpp
@@ -60,7 +60,7 @@ namespace TestImpact
         AZStd::to_wstring(argsW, args.c_str());
         if (!CreateProcessW(
             NULL,
-            argsW.c_str(),
+            argsW.data(),
             NULL,
             NULL,
             IsPiping(),

From e9ef0a02ec30689e692da05575fa86dbdf4e79d2 Mon Sep 17 00:00:00 2001
From: evanchia 
Date: Wed, 4 Aug 2021 11:17:38 -0700
Subject: [PATCH 050/205] minor fixes for c++ retry command

Signed-off-by: evanchia 
---
 Code/Tools/AzTestRunner/src/main.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Code/Tools/AzTestRunner/src/main.cpp b/Code/Tools/AzTestRunner/src/main.cpp
index 225975b654..d9ee727447 100644
--- a/Code/Tools/AzTestRunner/src/main.cpp
+++ b/Code/Tools/AzTestRunner/src/main.cpp
@@ -229,7 +229,7 @@ namespace AzTestRunner
         // Construct a retry command if the test fails
         if (result != 0)
         {
-            std::cout << "Retry command:\n " << argv[0] << " " << lib << " " << symbol << std::endl;
+            std::cout << "Retry command: " << std::endl << argv[0] << " " << lib << " " << symbol << std::endl;
         }
 
         // unload and reset the module here, because it needs to release resources that were used / activated in

From 4b817a6483560691a5f95a34355c87c8972b05ab Mon Sep 17 00:00:00 2001
From: Shirang Jia 
Date: Wed, 4 Aug 2021 17:57:47 -0700
Subject: [PATCH 051/205] Include build failure root cause in email
 notification (#2491)

Signed-off-by: shiranj 
---
 scripts/build/Jenkins/Jenkinsfile | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile
index 70618fea78..e693168af0 100644
--- a/scripts/build/Jenkins/Jenkinsfile
+++ b/scripts/build/Jenkins/Jenkinsfile
@@ -577,13 +577,19 @@ finally {
             )
         }
         node('controller') {
-            step([
-                $class: 'Mailer',
-                notifyEveryUnstableBuild: true,
-                recipients: emailextrecipients([
+            if("${currentBuild.currentResult}" == "SUCCESS") {
+                emailBody = "${BUILD_URL}\nSuccess!"
+            } else {
+                buildFailure = tm('${BUILD_FAILURE_ANALYZER}')
+                emailBody = "${BUILD_URL}\n${buildFailure}!"
+            }
+            emailext (
+                body: "${emailBody}",
+                subject: "${currentBuild.currentResult}: ${JOB_NAME} - Build # ${BUILD_NUMBER}",
+                recipientProviders: [
                     [$class: 'RequesterRecipientProvider']
-                ])
-            ])
+                ]
+            )
         }
     } catch(Exception e) {
     }

From c979ab03385f19970e1a422b23a6d2d9e09d888f Mon Sep 17 00:00:00 2001
From: dmcdiar 
Date: Wed, 4 Aug 2021 18:26:43 -0700
Subject: [PATCH 052/205] Keep the mutex locked while processing pending
 notifies.

Signed-off-by: dmcdiar 
---
 .../RHI/Code/Include/Atom/RHI/ObjectCollector.h     | 13 +++----------
 1 file changed, 3 insertions(+), 10 deletions(-)

diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h
index d79a86afea..3f9fed056f 100644
--- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h
+++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h
@@ -179,7 +179,6 @@ namespace AZ
             {
                 m_pendingGarbage.push_back({ AZStd::move(m_pendingObjects), m_currentIteration });
             }
-            m_mutex.unlock();
 
             if (m_pendingNotifies.size())
             {
@@ -200,25 +199,19 @@ namespace AZ
                     }
 
                     latestGarbage.m_notifies.insert(latestGarbage.m_notifies.end(), m_pendingNotifies.begin(), m_pendingNotifies.end());
-
-                    m_mutex.lock();
-                    m_pendingNotifies.clear();
-                    m_mutex.unlock();
-
                 }
                 else
                 {
                     // garbage queue is empty, notify now
-                    m_mutex.lock();
                     for (auto& notifyFunction : m_pendingNotifies)
                     {
                         notifyFunction();
                     }
-
-                    m_pendingNotifies.clear();
-                    m_mutex.unlock();
                 }
+
+                m_pendingNotifies.clear();
             }
+            m_mutex.unlock();
 
             size_t objectCount = 0;
             size_t i = 0;

From 9a82005cb8e3d516b43064651b056df6e57128e2 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 12:42:33 -0700
Subject: [PATCH 053/205] PR comments/fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzCore/AzCore/std/string/conversions.h    | 26 ++++++++++++-------
 .../WinAPI/AzCore/Utils/Utils_WinAPI.cpp      |  2 +-
 .../Linux/AzCore/Debug/Trace_Linux.cpp        |  2 +-
 Code/Framework/AzCore/Tests/AZStd/String.cpp  |  2 +-
 4 files changed, 20 insertions(+), 12 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index 91af1029b4..235eb188d1 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -58,15 +58,15 @@ namespace AZStd
                 }
             }
 
-            static inline void to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last)
+            static inline char* to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last)
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf16to8(first, last, dest, destSize);
+                    return Utf8::Unchecked::utf16to8(first, last, dest, destSize);
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf32to8(first, last, dest, destSize);
+                    return Utf8::Unchecked::utf32to8(first, last, dest, destSize);
                 }
             }
 
@@ -96,15 +96,15 @@ namespace AZStd
                 }
             }
 
-            static inline void to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last)
+            static inline wchar_t* to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last)
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf8to16(first, last, dest, destSize);
+                    return Utf8::Unchecked::utf8to16(first, last, dest, destSize);
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf8to32(first, last, dest, destSize);
+                    return Utf8::Unchecked::utf8to32(first, last, dest, destSize);
                 }
             }
         };
@@ -337,7 +337,11 @@ namespace AZStd
 
         if (srcLen > 0)
         {
-            Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen + 1); // copy null terminator
+            char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen);
+            if (*(endStr - 1) != '\0')
+            {
+                *endStr = '\0'; // copy null terminator
+            }
         }
     }
 
@@ -485,12 +489,16 @@ namespace AZStd
     {
         if (srcLen == 0)
         {
-            srcLen = strlen(str) + 1;
+            srcLen = strlen(str);
         }
 
         if (srcLen > 0)
         {
-            Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen + 1); // copy null terminator
+            wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen);
+            if (*(endWStr - 1) != '\0')
+            {
+                *endWStr = '\0'; // copy null terminator
+            }
         }
     }
 
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
index a4af19a2a4..dc104668be 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
@@ -30,7 +30,7 @@ namespace AZ
             result.m_pathIncludesFilename = true;
             // Platform specific get exe path: http://stackoverflow.com/a/1024937
             // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
-            wchar_t pathBufferW[AZ_MAX_PATH_LEN] = { 0 };
+            wchar_t pathBufferW[AZ::IO::MaxPathLength] = { 0 };
             const DWORD pathLen = GetModuleFileNameW(nullptr, pathBufferW, static_cast(exeStorageSize));
             const DWORD errorCode = GetLastError();
             if (pathLen == exeStorageSize && errorCode == ERROR_INSUFFICIENT_BUFFER)
diff --git a/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp b/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
index 86c7e14ae6..1ca06fcf7f 100644
--- a/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
+++ b/Code/Framework/AzCore/Platform/Linux/AzCore/Debug/Trace_Linux.cpp
@@ -15,7 +15,7 @@ namespace AZ
     {
         namespace Platform
         {
-            void OutputToDebugger(const char* title, const char* message)
+            void OutputToDebugger([[maybe_unused]] const char* title, [[maybe_unused]] const char* message)
             {
                 // std::cout << title << ": " << message;
             }
diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp
index c0d378bd39..309f561a75 100644
--- a/Code/Framework/AzCore/Tests/AZStd/String.cpp
+++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp
@@ -703,7 +703,7 @@ namespace UnitTest
         AZ_TEST_ASSERT(0 == azwcsicmp(wstrBuffer, L"BlaBla 5"));
 
         // char buffer to wchar_t buffer
-        memset(wstrBuffer, 0, AZ_ARRAY_SIZE(wstrBuffer));
+        memset(wstrBuffer, L' ', AZ_ARRAY_SIZE(wstrBuffer)); // to check that the null terminator is properly placed
         to_wstring(wstrBuffer, 9, strBuffer);
         AZ_TEST_ASSERT(0 == azwcsicmp(wstrBuffer, L"BLABLA 5"));
 

From d955189a31a5f8eb6ddc4529c3d28421aba6a558 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 12:43:46 -0700
Subject: [PATCH 054/205] Removal of unused files from Code/Editor
 XmlHistoryManager.cpp was being compiled but unused

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/Animation/SkeletonHierarchy.cpp   | 149 ---
 Code/Editor/Animation/SkeletonHierarchy.h     |  57 --
 Code/Editor/Animation/SkeletonMapper.cpp      | 368 --------
 Code/Editor/Animation/SkeletonMapper.h        |  76 --
 .../Animation/SkeletonMapperOperator.cpp      | 284 ------
 .../Editor/Animation/SkeletonMapperOperator.h | 164 ----
 Code/Editor/ControlMRU.cpp                    | 135 ---
 Code/Editor/ControlMRU.h                      |  24 -
 Code/Editor/Controls/ConsoleSCBMFC.cpp        | 543 -----------
 Code/Editor/Util/IXmlHistoryManager.h         |  73 --
 Code/Editor/Util/StringNoCasePredicate.h      |  62 --
 Code/Editor/Util/XmlHistoryManager.cpp        | 875 ------------------
 Code/Editor/Util/XmlHistoryManager.h          | 218 -----
 Code/Editor/editor_lib_files.cmake            |   4 -
 14 files changed, 3032 deletions(-)
 delete mode 100644 Code/Editor/Animation/SkeletonHierarchy.cpp
 delete mode 100644 Code/Editor/Animation/SkeletonHierarchy.h
 delete mode 100644 Code/Editor/Animation/SkeletonMapper.cpp
 delete mode 100644 Code/Editor/Animation/SkeletonMapper.h
 delete mode 100644 Code/Editor/Animation/SkeletonMapperOperator.cpp
 delete mode 100644 Code/Editor/Animation/SkeletonMapperOperator.h
 delete mode 100644 Code/Editor/ControlMRU.cpp
 delete mode 100644 Code/Editor/ControlMRU.h
 delete mode 100644 Code/Editor/Controls/ConsoleSCBMFC.cpp
 delete mode 100644 Code/Editor/Util/IXmlHistoryManager.h
 delete mode 100644 Code/Editor/Util/StringNoCasePredicate.h
 delete mode 100644 Code/Editor/Util/XmlHistoryManager.cpp
 delete mode 100644 Code/Editor/Util/XmlHistoryManager.h

diff --git a/Code/Editor/Animation/SkeletonHierarchy.cpp b/Code/Editor/Animation/SkeletonHierarchy.cpp
deleted file mode 100644
index 3015ff5e27..0000000000
--- a/Code/Editor/Animation/SkeletonHierarchy.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#include "EditorDefs.h"
-#include "SkeletonHierarchy.h"
-
-using namespace Skeleton;
-
-/*
-
-  CHierarchy
-
-*/
-
-CHierarchy::CHierarchy()
-{
-}
-
-CHierarchy::~CHierarchy()
-{
-}
-
-//
-
-uint32 CHierarchy::AddNode(const char* name, const QuatT& pose, int32 parent)
-{
-    int32 index = FindNodeIndexByName(name);
-
-    if (index < 0)
-    {
-        m_nodes.push_back(SNode());
-        index = int32(m_nodes.size() - 1);
-    }
-
-    m_nodes[index].name = name;
-    m_nodes[index].pose = pose;
-    m_nodes[index].parent = parent;
-    return uint32(index);
-}
-
-int32 CHierarchy::FindNodeIndexByName(const char* name) const
-{
-    uint32 count = uint32(m_nodes.size());
-    for (uint32 i = 0; i < count; ++i)
-    {
-        if (::_stricmp(m_nodes[i].name, name))
-        {
-            continue;
-        }
-
-        return i;
-    }
-
-    return -1;
-}
-
-const CHierarchy::SNode* CHierarchy::FindNode(const char* name) const
-{
-    int32 index = FindNodeIndexByName(name);
-    return index < 0 ? NULL : &m_nodes[index];
-}
-
-void CHierarchy::CreateFrom(IDefaultSkeleton* pIDefaultSkeleton)
-{
-    const uint32 jointCount = pIDefaultSkeleton->GetJointCount();
-
-    m_nodes.clear();
-    m_nodes.reserve(jointCount);
-    for (uint32 i = 0; i < jointCount; ++i)
-    {
-        m_nodes.push_back(SNode());
-
-        m_nodes.back().name = pIDefaultSkeleton->GetJointNameByID(int32(i));
-        m_nodes.back().pose = pIDefaultSkeleton->GetDefaultAbsJointByID(int32(i));
-
-        m_nodes.back().parent = pIDefaultSkeleton->GetJointParentIDByID(int32(i));
-    }
-
-    ValidateReferences();
-}
-
-void CHierarchy::ValidateReferences()
-{
-    uint32 nodeCount = m_nodes.size();
-    if (!nodeCount)
-    {
-        return;
-    }
-
-    for (uint32 i = 0; i < nodeCount; ++i)
-    {
-        if (m_nodes[i].parent < nodeCount)
-        {
-            continue;
-        }
-
-        m_nodes[i].parent = -1;
-    }
-}
-
-void CHierarchy::AbsoluteToRelative(const QuatT* pSource, QuatT* pDestination)
-{
-    uint32 count = uint32(m_nodes.size());
-    std::vector absolutes(count);
-    for (uint32 i = 0; i < count; ++i)
-    {
-        absolutes[i] = pSource[i];
-    }
-
-    for (uint32 i = 0; i < count; ++i)
-    {
-        int32 parent = m_nodes[i].parent;
-        if (parent < 0)
-        {
-            pDestination[i] = absolutes[i];
-            continue;
-        }
-
-        pDestination[i].t = (absolutes[i].t - absolutes[parent].t) * absolutes[parent].q;
-        pDestination[i].q = absolutes[parent].q.GetInverted() * absolutes[i].q;
-    }
-}
-
-bool CHierarchy::SerializeTo(XmlNodeRef& node)
-{
-    XmlNodeRef hierarchy = node->newChild("Hierarchy");
-
-    uint32 nodeCount = uint32(m_nodes.size());
-    std::vector nodes(nodeCount);
-    for (uint32 i = 0; i < nodeCount; ++i)
-    {
-        XmlNodeRef parent = hierarchy;
-        if (m_nodes[i].parent > -1)
-        {
-            parent = nodes[m_nodes[i].parent];
-        }
-
-        nodes[i] = parent->newChild("Node");
-        nodes[i]->setAttr("name", m_nodes[i].name);
-    }
-
-    return true;
-}
diff --git a/Code/Editor/Animation/SkeletonHierarchy.h b/Code/Editor/Animation/SkeletonHierarchy.h
deleted file mode 100644
index ad0d8fc7fc..0000000000
--- a/Code/Editor/Animation/SkeletonHierarchy.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#ifndef CRYINCLUDE_EDITOR_ANIMATION_SKELETONHIERARCHY_H
-#define CRYINCLUDE_EDITOR_ANIMATION_SKELETONHIERARCHY_H
-#pragma once
-
-namespace Skeleton {
-    class CHierarchy
-        : public _reference_target_t
-    {
-    public:
-        struct SNode
-        {
-            string name;
-            QuatT pose;
-
-            int32 parent;
-
-            /* TODO: Implement
-                    uint32 childrenIndex;
-                    uint32 childrenCount;
-            */
-        };
-
-    public:
-        CHierarchy();
-        ~CHierarchy();
-
-    public:
-        uint32 AddNode(const char* name, const QuatT& pose, int32 parent = -1);
-        uint32 GetNodeCount() const { return uint32(m_nodes.size()); }
-        SNode* GetNode(uint32 index) { return &m_nodes[index]; }
-        const SNode* GetNode(uint32 index) const { return &m_nodes[index]; }
-        int32 FindNodeIndexByName(const char* name) const;
-        const SNode* FindNode(const char* name) const;
-        void ClearNodes() { m_nodes.clear(); }
-
-        void CreateFrom(IDefaultSkeleton* rIDefaultSkeleton);
-        void ValidateReferences();
-
-        void AbsoluteToRelative(const QuatT* pSource, QuatT* pDestination);
-
-        bool SerializeTo(XmlNodeRef& node);
-
-    private:
-        std::vector m_nodes;
-    };
-} // namespace Skeleton
-
-#endif // CRYINCLUDE_EDITOR_ANIMATION_SKELETONHIERARCHY_H
diff --git a/Code/Editor/Animation/SkeletonMapper.cpp b/Code/Editor/Animation/SkeletonMapper.cpp
deleted file mode 100644
index 3913801fc8..0000000000
--- a/Code/Editor/Animation/SkeletonMapper.cpp
+++ /dev/null
@@ -1,368 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#include "EditorDefs.h"
-
-#include "SkeletonMapper.h"
-
-using namespace Skeleton;
-
-/*
-
-  CMapper
-
-*/
-
-CMapper::CMapper()
-{
-}
-
-CMapper::~CMapper()
-{
-}
-
-//
-
-void CMapper::CreateFromHierarchy()
-{
-    m_nodes.clear();
-
-    uint32 nodeCount = m_hierarchy.GetNodeCount();
-    m_nodes.resize(nodeCount);
-}
-
-//
-
-uint32 CMapper::CreateLocation(const char* name)
-{
-    int32 index = FindLocation(name);
-    if (index < 1)
-    {
-        CMapperLocation* pLocation = new CMapperLocation();
-        pLocation->SetName(name);
-        m_locations.push_back(pLocation);
-    }
-    return uint32(m_locations.size() - 1);
-}
-
-void CMapper::ClearLocations()
-{
-    uint32 count = uint32(m_nodes.size());
-    for (uint32 i = 0; i < count; ++i)
-    {
-        m_nodes[i].position = NULL;
-        m_nodes[i].orientation = NULL;
-    }
-
-    m_locations.clear();
-}
-
-int32 CMapper::FindLocation(const char* name) const
-{
-    uint32 count = uint32(m_locations.size());
-    for (uint32 i = 0; i < count; ++i)
-    {
-        if (::_stricmp(m_locations[i]->GetName(), name))
-        {
-            continue;
-        }
-
-        return int32(i);
-    }
-
-    return -1;
-}
-
-void CMapper::SetLocation(CMapperLocation& location)
-{
-    int32 index = FindLocation(location.GetName());
-    if (index < 0)
-    {
-        m_locations.push_back(&location);
-        return;
-    }
-
-    m_locations[index] = &location;
-}
-
-//
-
-bool CMapper::CreateLocationsHierarchy(uint32 index, CHierarchy& hierarchy, int32 hierarchyParent)
-{
-    if (NodeHasLocation(index))
-    {
-        const CHierarchy::SNode* pNode = m_hierarchy.GetNode(index);
-        uint32 nodeIndex = hierarchy.AddNode(pNode->name, pNode->pose, hierarchyParent);
-        hierarchyParent = uint32(nodeIndex);
-    }
-
-    std::vector children;
-    GetChildrenIndices(index, children);
-    uint32 childCount = uint32(children.size());
-    for (uint32 i = 0; i < childCount; ++i)
-    {
-        CreateLocationsHierarchy(children[i], hierarchy, hierarchyParent);
-    }
-
-    return hierarchy.GetNodeCount() != 0;
-}
-
-bool CMapper::CreateLocationsHierarchy(CHierarchy& hierarchy)
-{
-    hierarchy.ClearNodes();
-    if (!CreateLocationsHierarchy(0, hierarchy, -1))
-    {
-        return false;
-    }
-
-    hierarchy.ValidateReferences();
-    return true;
-}
-
-void CMapper::Map(QuatT* pResult)
-{
-    uint32 outputCount = m_hierarchy.GetNodeCount();
-    std::vector absolutes(outputCount);
-    for (uint32 i = 0; i < outputCount; ++i)
-    {
-        pResult[i].SetIdentity();
-        absolutes[i].SetIdentity();
-
-        CHierarchy::SNode* pNode = m_hierarchy.GetNode(i);
-        if (!pNode)
-        {
-            continue;
-        }
-
-        CHierarchy::SNode* pParent = pNode->parent < 0 ?
-            NULL : m_hierarchy.GetNode(pNode->parent);
-        if (pParent)
-        {
-            pResult[i].t =
-                (pNode->pose.t - pParent->pose.t) * pParent->pose.q;
-        }
-
-        if (m_nodes[i].position)
-        {
-            pResult[i].t = m_nodes[i].position->Compute().t;
-        }
-
-        if (m_nodes[i].orientation)
-        {
-            absolutes[i] = m_nodes[i].orientation->Compute().q;
-        }
-        else if (pParent)
-        {
-            Quat relative = pParent->pose.q.GetInverted() * pNode->pose.q;
-            absolutes[i] = absolutes[pNode->parent] * relative;
-        }
-    }
-
-    for (uint32 i = 0; i < outputCount; ++i)
-    {
-        CHierarchy::SNode* pNode = m_hierarchy.GetNode(i);
-        if (!pNode)
-        {
-            continue;
-        }
-
-        CHierarchy::SNode* pParent = pNode->parent < 0 ?
-            NULL : m_hierarchy.GetNode(pNode->parent);
-        if (!pParent)
-        {
-            pResult[i].q = absolutes[i];
-            continue;
-        }
-
-        pResult[i].q = absolutes[i];
-        if (!m_nodes[i].position)
-        {
-            pResult[i].t = pResult[pNode->parent].t +
-                pResult[i].t * absolutes[pNode->parent].GetInverted();
-        }
-    }
-}
-
-//
-
-bool CMapper::NodeHasLocation(uint32 index)
-{
-    if (CMapperOperator* pOperator = m_nodes[index].position)
-    {
-        if (pOperator->IsOfClass("Location"))
-        {
-            return true;
-        }
-        if (pOperator->HasLinksOfClass("Location"))
-        {
-            return true;
-        }
-    }
-
-    if (CMapperOperator* pOperator = m_nodes[index].orientation)
-    {
-        if (pOperator->IsOfClass("Location"))
-        {
-            return true;
-        }
-        if (pOperator->HasLinksOfClass("Location"))
-        {
-            return true;
-        }
-    }
-
-    return false;
-}
-
-void CMapper::GetChildrenIndices(uint32 parent, std::vector& children)
-{
-    uint32 nodeCount = m_hierarchy.GetNodeCount();
-    for (uint32 i = 0; i < nodeCount; ++i)
-    {
-        if (m_hierarchy.GetNode(i)->parent != parent)
-        {
-            continue;
-        }
-
-        children.push_back(i);
-    }
-}
-
-bool CMapper::ChildrenHaveLocation(uint32 index)
-{
-    std::vector children;
-    GetChildrenIndices(index, children);
-
-    uint32 childrenCount = uint32(children.size());
-    for (uint32 i = 0; i < childrenCount; ++i)
-    {
-        if (ChildrenHaveLocation(children[i]))
-        {
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool CMapper::NodeOrChildrenHaveLocation(uint32 index)
-{
-    if (NodeHasLocation(index))
-    {
-        return true;
-    }
-
-    std::vector children;
-    GetChildrenIndices(index, children);
-
-    uint32 childrenCount = uint32(children.size());
-    for (uint32 i = 0; i < childrenCount; ++i)
-    {
-        if (NodeOrChildrenHaveLocation(children[i]))
-        {
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool CMapper::SerializeTo(XmlNodeRef& node)
-{
-    XmlNodeRef hierarchy = node->newChild("Hierarchy");
-
-    uint32 nodeCount = GetNodeCount();
-    std::vector nodes(nodeCount);
-    for (uint32 i = 0; i < nodeCount; ++i)
-    {
-        if (!NodeOrChildrenHaveLocation(i))
-        {
-            continue;
-        }
-
-        CHierarchy::SNode* pNode = m_hierarchy.GetNode(i);
-        if (!pNode)
-        {
-            return false;
-        }
-
-        XmlNodeRef xmlParent = hierarchy;
-        int32 parent = pNode->parent;
-        if (parent > -1)
-        {
-            xmlParent = nodes[parent];
-        }
-
-        nodes[i] = xmlParent->newChild("Node");
-        nodes[i]->setAttr("name", pNode->name);
-
-        if (CMapperOperator* pOperator = m_nodes[i].position)
-        {
-            XmlNodeRef position = nodes[i]->newChild("Position");
-            XmlNodeRef child = position->newChild("Operator");
-            if (!pOperator->SerializeWithLinksTo(child))
-            {
-                return false;
-            }
-        }
-
-        if (CMapperOperator* pOperator = m_nodes[i].orientation)
-        {
-            XmlNodeRef orientation = nodes[i]->newChild("Orientation");
-            XmlNodeRef child = orientation->newChild("Operator");
-            if (!pOperator->SerializeWithLinksTo(child))
-            {
-                return false;
-            }
-        }
-    }
-
-    return true;
-}
-
-bool CMapper::SerializeFrom(XmlNodeRef& node, int32 parent)
-{
-    int childCount = uint32(node->getChildCount());
-    for (int i = 0; i < childCount; ++i)
-    {
-        XmlNodeRef child = node->getChild(i);
-        if (::_stricmp(child->getTag(), "Node"))
-        {
-            continue;
-        }
-
-        uint32 index = m_hierarchy.AddNode(child->getAttr("name"), QuatT(IDENTITY), parent);
-        if (!SerializeFrom(child, int32(index)))
-        {
-            return false;
-        }
-    }
-
-    return true;
-}
-
-bool CMapper::SerializeFrom(XmlNodeRef& node)
-{
-    XmlNodeRef hierarchy = node->findChild("Hierarchy");
-    if (!hierarchy)
-    {
-        return false;
-    }
-
-    m_hierarchy.ClearNodes();
-
-    if (!SerializeFrom(hierarchy, -1))
-    {
-        return false;
-    }
-
-    m_nodes.resize(m_hierarchy.GetNodeCount());
-
-    return true;
-}
diff --git a/Code/Editor/Animation/SkeletonMapper.h b/Code/Editor/Animation/SkeletonMapper.h
deleted file mode 100644
index 159b019396..0000000000
--- a/Code/Editor/Animation/SkeletonMapper.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#ifndef CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPER_H
-#define CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPER_H
-#pragma once
-
-
-#include "SkeletonHierarchy.h"
-#include "SkeletonMapperOperator.h"
-
-namespace Skeleton {
-    class CMapper
-    {
-    public:
-        struct SNode
-        {
-            _smart_ptr position;
-            _smart_ptr orientation;
-        };
-
-    public:
-        CMapper();
-        ~CMapper();
-
-    public:
-        CHierarchy& GetHierarchy() { return m_hierarchy; }
-        void CreateFromHierarchy();
-
-        uint32 GetNodeCount() const { return uint32(m_nodes.size()); }
-        SNode* GetNode(uint32 index) { return &m_nodes[index]; }
-        const SNode* GetNode(uint32 index) const { return &m_nodes[index]; }
-
-        uint32 CreateLocation(const char* name);
-        void ClearLocations();
-        int32 FindLocation(const char* name) const;
-
-        uint32 GetLocationCount() const { return uint32(m_locations.size()); }
-        void SetLocation(CMapperLocation& location);
-        CMapperLocation* GetLocation(uint32 index) { return m_locations[index]; }
-        const CMapperLocation* GetLocation(uint32 index)  const { return m_locations[index]; }
-
-        bool CreateLocationsHierarchy(CHierarchy& hierarchy);
-
-        void Map(QuatT* pResult);
-
-        bool SerializeTo(XmlNodeRef& node);
-        bool SerializeFrom(XmlNodeRef& node);
-
-    private:
-        bool NodeHasLocation(uint32 index);
-        bool ChildrenHaveLocation(uint32 index);
-        bool NodeOrChildrenHaveLocation(uint32 index);
-
-        bool SerializeFrom(XmlNodeRef& node, int32 parent);
-
-        bool CreateLocationsHierarchy(uint32 index, CHierarchy& hierarchy, int32 hierarchyParent = -1);
-
-        // TEMP
-        void GetChildrenIndices(uint32 parent, std::vector& children);
-
-    private:
-        CHierarchy m_hierarchy;
-        std::vector<_smart_ptr > m_locations;
-
-        std::vector m_nodes;
-    };
-} // namespace Skeleton
-
-#endif // CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPER_H
diff --git a/Code/Editor/Animation/SkeletonMapperOperator.cpp b/Code/Editor/Animation/SkeletonMapperOperator.cpp
deleted file mode 100644
index 7a69173bed..0000000000
--- a/Code/Editor/Animation/SkeletonMapperOperator.cpp
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#include "EditorDefs.h"
-
-#include "SkeletonMapperOperator.h"
-
-using namespace Skeleton;
-
-/*
-
-  CMapperOperatorDesc
-
-*/
-
-std::vector CMapperOperatorDesc::s_descs;
-
-//
-
-CMapperOperatorDesc::CMapperOperatorDesc(const char* name)
-{
-    s_descs.push_back(this);
-}
-
-/*
-
-  CMapperOperator
-
-*/
-
-CMapperOperator::CMapperOperator(const char* className, uint32 positionCount, uint32 orientationCount)
-{
-    m_className = className;
-    m_position.resize(positionCount, NULL);
-    m_orientation.resize(orientationCount, NULL);
-}
-
-CMapperOperator::~CMapperOperator()
-{
-}
-
-//
-
-bool CMapperOperator::IsOfClass(const char* className)
-{
-    if (::_stricmp(m_className, className))
-    {
-        return false;
-    }
-
-    return true;
-}
-
-uint32 CMapperOperator::HasLinksOfClass(const char* className)
-{
-    uint32 count = 0;
-
-    uint32 positionCount = m_position.size();
-    for (uint32 i = 0; i < positionCount; ++i)
-    {
-        CMapperOperator* pOperator = m_position[i];
-        if (!pOperator)
-        {
-            continue;
-        }
-
-        if (pOperator->IsOfClass(className))
-        {
-            ++count;
-        }
-    }
-
-    uint32 orientationCount = m_orientation.size();
-    for (uint32 i = 0; i < orientationCount; ++i)
-    {
-        CMapperOperator* pOperator = m_orientation[i];
-        if (!pOperator)
-        {
-            continue;
-        }
-
-        if (pOperator->IsOfClass(className))
-        {
-            ++count;
-        }
-    }
-
-    return count;
-}
-
-//
-
-bool CMapperOperator::SerializeTo(XmlNodeRef& node)
-{
-    node->setAttr("class", m_className);
-
-    uint32 parameterCount = uint32(m_parameters.size());
-    for (uint32 i = 0; i < parameterCount; ++i)
-    {
-        m_parameters[i]->Serialize(node, false);
-    }
-
-    return true;
-}
-
-bool CMapperOperator::SerializeFrom(XmlNodeRef& node)
-{
-    uint32 parameterCount = uint32(m_parameters.size());
-    for (uint32 i = 0; i < parameterCount; ++i)
-    {
-        m_parameters[i]->Serialize(node, true);
-    }
-
-    return true;
-}
-
-bool CMapperOperator::SerializeWithLinksTo(XmlNodeRef& node)
-{
-    if (!SerializeTo(node))
-    {
-        return false;
-    }
-
-    uint32 positionCount = uint32(m_position.size());
-    for (uint32 i = 0; i < positionCount; ++i)
-    {
-        CMapperOperator* pOperator = m_position[i];
-        if (!pOperator)
-        {
-            continue;
-        }
-
-        XmlNodeRef position = node->newChild("Position");
-        position->setAttr("index", i);
-
-        XmlNodeRef child = position->newChild("Operator");
-        if (!pOperator->SerializeWithLinksTo(child))
-        {
-            return false;
-        }
-    }
-
-    uint32 orientationCount = uint32(m_orientation.size());
-    for (uint32 i = 0; i < orientationCount; ++i)
-    {
-        CMapperOperator* pOperator = m_orientation[i];
-        if (!pOperator)
-        {
-            continue;
-        }
-
-        XmlNodeRef orientation = node->newChild("Orientation");
-        orientation->setAttr("index", i);
-
-        XmlNodeRef child = orientation->newChild("Operator");
-        if (!pOperator->SerializeWithLinksTo(child))
-        {
-            return false;
-        }
-    }
-
-    return true;
-}
-
-bool CMapperOperator::SerializeWithLinksFrom(XmlNodeRef& node)
-{
-    if (!SerializeFrom(node))
-    {
-        return false;
-    }
-
-    return true;
-}
-/*
-
-  CMapperOperator_Transform
-
-*/
-
-class CMapperOperator_Transform
-    : public CMapperOperator
-{
-public:
-    CMapperOperator_Transform()
-        : CMapperOperator("Transform", 1, 1)
-    {
-        m_pAngles = new CVariable();
-        m_pAngles->SetName("rotation");
-        m_pAngles->Set(Vec3(0.0f, 0.0f, 0.0f));
-        m_pAngles->SetLimits(-180.0f, 180.0f);
-        AddParameter(*m_pAngles);
-
-        m_pVector = new CVariable();
-        m_pVector->SetName("vector");
-        m_pVector->Set(Vec3(0.0f, 0.0f, 0.0f));
-        AddParameter(*m_pVector);
-
-        m_pScale = new CVariable();
-        m_pScale->SetName("scale");
-        m_pScale->Set(Vec3(1.0f, 1.0f, 1.0f));
-        AddParameter(*m_pScale);
-    }
-
-    // CMapperOperator
-public:
-    virtual QuatT CMapperOperator_Transform::Compute()
-    {
-        QuatT result(IDENTITY);
-        m_pVector->Get(result.t);
-
-        Vec3 scale;
-        m_pScale->Get(scale);
-
-        Vec3 angles;
-        m_pAngles->Get(angles);
-
-        result.q = Quat::CreateRotationXYZ(
-                Ang3(DEG2RAD(angles.x), DEG2RAD(angles.y), DEG2RAD(angles.z)));
-
-        if (CMapperOperator* pOperator = GetPosition(0))
-        {
-            result.t = pOperator->Compute().t.CompMul(scale) + result.t;
-        }
-        if (CMapperOperator* pOperator = GetOrientation(0))
-        {
-            result.q = pOperator->Compute().q * result.q;
-        }
-        return result;
-    }
-
-private:
-    CVariable* m_pVector;
-    CVariable* m_pAngles;
-    CVariable* m_pScale;
-};
-
-SkeletonMapperOperatorRegister(Transform, CMapperOperator_Transform)
-
-class CMapperOperator_PositionsToOrientation
-    : public CMapperOperator
-{
-public:
-    CMapperOperator_PositionsToOrientation()
-        : CMapperOperator("PositionsToOrientation", 3, 0)
-    {
-    }
-
-    // CMapperOperator
-public:
-    virtual QuatT Compute()
-    {
-        CMapperOperator* pOperator0 = GetPosition(0);
-        CMapperOperator* pOperator1 = GetPosition(1);
-        CMapperOperator* pOperator2 = GetPosition(2);
-        if (!pOperator0 || !pOperator1 || !pOperator2)
-        {
-            return QuatT(IDENTITY);
-        }
-
-        Vec3 p0 = pOperator0->Compute().t;
-        Vec3 p1 = pOperator1->Compute().t;
-        Vec3 p2 = pOperator2->Compute().t;
-
-        Vec3 m = (p1 + p2) * 0.5f;
-        Vec3 y = (m - p0).GetNormalized();
-        Vec3 z = (p1 - p2).GetNormalized();
-        Vec3 x = y % z;
-        z = x % y;
-
-        Matrix33 m33;
-        m33.SetFromVectors(x, y, z);
-        QuatT result(IDENTITY);
-        result.q = Quat(m33);
-        return result;
-    }
-};
-
-SkeletonMapperOperatorRegister(PositionsToOrientation, CMapperOperator_PositionsToOrientation)
diff --git a/Code/Editor/Animation/SkeletonMapperOperator.h b/Code/Editor/Animation/SkeletonMapperOperator.h
deleted file mode 100644
index 68bbb84ac7..0000000000
--- a/Code/Editor/Animation/SkeletonMapperOperator.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#ifndef CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPEROPERATOR_H
-#define CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPEROPERATOR_H
-#pragma once
-
-
-#include "../Util/Variable.h"
-
-#undef GetClassName
-
-#define SkeletonMapperOperatorRegister(name, className)               \
-    class CMapperOperatorDesc_##name                                  \
-        : public CMapperOperatorDesc                                  \
-    {                                                                 \
-    public:                                                           \
-        CMapperOperatorDesc_##name()                                  \
-            : CMapperOperatorDesc(#name) { }                          \
-    protected:                                                        \
-        virtual const char* GetName() { return #name; }               \
-        virtual CMapperOperator* Create() { return new className(); } \
-    } mapperOperatorDesc__##name;
-
-namespace Skeleton {
-    class CMapperOperator;
-
-    class CMapperOperatorDesc
-    {
-    public:
-        static uint32 GetCount() { return uint32(s_descs.size()); }
-        static const char* GetName(uint32 index) { return s_descs[index]->GetName(); }
-        static CMapperOperator* Create(uint32 index) { return s_descs[index]->Create(); }
-
-    private:
-        static std::vector s_descs;
-
-    public:
-        CMapperOperatorDesc(const char* name);
-
-    protected:
-        virtual const char* GetName() = 0;
-        virtual CMapperOperator* Create() = 0;
-    };
-
-    class CMapperOperator
-        : public _reference_target_t
-    {
-    protected:
-        CMapperOperator(const char* className, uint32 positionCount, uint32 orientationCount);
-        ~CMapperOperator();
-
-    public:
-        const char* GetClassName() { return m_className; }
-
-        uint32 GetPositionCount() const { return uint32(m_position.size()); }
-        void SetPosition(uint32 index, CMapperOperator* pOperator) { m_position[index] = pOperator; }
-        CMapperOperator* GetPosition(uint32 index) { return m_position[index]; }
-
-        uint32 GetOrientationCount() const { return uint32(m_orientation.size()); }
-        void SetOrientation(uint32 index, CMapperOperator* pOperator) { m_orientation[index] = pOperator; }
-        CMapperOperator* GetOrientation(uint32 index) { return m_orientation[index]; }
-
-        uint32 GetParameterCount() { return uint32(m_parameters.size()); }
-        IVariable* GetParameter(uint32 index) { return m_parameters[index]; }
-
-        bool IsOfClass(const char* className);
-        uint32 HasLinksOfClass(const char* className);
-
-        bool SerializeTo(XmlNodeRef& node);
-        bool SerializeFrom(XmlNodeRef& node);
-
-        bool SerializeWithLinksTo(XmlNodeRef& node);
-        bool SerializeWithLinksFrom(XmlNodeRef& node);
-
-    protected:
-        void AddParameter(IVariable& variable) { m_parameters.push_back(&variable); }
-
-    public:
-        virtual QuatT Compute() = 0;
-
-    private:
-        const char* m_className;
-        std::vector<_smart_ptr > m_position;
-        std::vector<_smart_ptr > m_orientation;
-
-        std::vector m_parameters;
-    };
-
-    class CMapperLocation
-        : public CMapperOperator
-    {
-    public:
-        CMapperLocation()
-            : CMapperOperator("Location", 0, 0)
-        {
-            m_pName = new CVariable();
-            m_pName->SetName("name");
-            m_pName->SetFlags(m_pName->GetFlags() | IVariable::UI_INVISIBLE);
-            AddParameter(*m_pName);
-
-            m_pAxis = new CVariable();
-            m_pAxis->SetName("axis");
-            m_pAxis->SetLimits(-3.0f, +3.0f);
-            m_pAxis->Set(Vec3(1.0f, 2.0f, 3.0f));
-            AddParameter(*m_pAxis);
-
-            m_location = QuatT(IDENTITY);
-        }
-
-    public:
-        void SetName(const char* name) { m_pName->Set(name); }
-        CString GetName() const { CString s; m_pName->Get(s); return s; }
-
-        void SetLocation(const QuatT& location) { m_location = location; }
-        const QuatT& GetLocation() const { return m_location; }
-
-        // CMapperOperator
-    public:
-        virtual QuatT Compute()
-        {
-            Vec3 axis;
-            m_pAxis->Get(axis);
-
-            uint32 x = fabs_tpl(axis.x);
-            uint32 y = fabs_tpl(axis.y);
-            uint32 z = fabs_tpl(axis.z);
-            if (x < 1 || y < 1 || z < 1 ||
-                x > 3 || y > 3 || y > 3 ||
-                x == y || x == z || y == z)
-            {
-                return QuatT(IDENTITY);
-            }
-
-            Matrix33 matrix;
-            matrix.SetFromVectors(
-                m_location.q.GetColumn(x - 1) * f32(::sgn(axis.x)),
-                m_location.q.GetColumn(y - 1) * f32(::sgn(axis.y)),
-                m_location.q.GetColumn(z - 1) * f32(::sgn(axis.z)));
-            if (!matrix.IsOrthonormalRH(0.01f))
-            {
-                return QuatT(IDENTITY);
-            }
-
-            QuatT result = m_location;
-            result.q = Quat(matrix);
-            return result;
-        }
-
-    private:
-        CVariable* m_pName;
-        CVariable* m_pAxis;
-
-        QuatT m_location;
-    };
-} // namespace Skeleton
-
-#endif // CRYINCLUDE_EDITOR_ANIMATION_SKELETONMAPPEROPERATOR_H
diff --git a/Code/Editor/ControlMRU.cpp b/Code/Editor/ControlMRU.cpp
deleted file mode 100644
index 47de13950f..0000000000
--- a/Code/Editor/ControlMRU.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#include "EditorDefs.h"
-#include "ControlMRU.h"
-
-IMPLEMENT_XTP_CONTROL(CControlMRU, CXTPControlRecentFileList)
-
-bool CControlMRU::DoesFileExist(CString& sFileName)
-{
-    return (_access(sFileName.GetBuffer(), 0) == 0);
-}
-
-void CControlMRU::OnCalcDynamicSize(DWORD dwMode)
-{
-    CRecentFileList* pRecentFileList = GetRecentFileList();
-
-    if (!pRecentFileList)
-    {
-        return;
-    }
-
-    CString* pArrNames = pRecentFileList->m_arrNames;
-
-    assert(pArrNames != NULL);
-    if (!pArrNames)
-    {
-        return;
-    }
-
-    while (m_nIndex + 1 < m_pControls->GetCount())
-    {
-        CXTPControl* pControl = m_pControls->GetAt(m_nIndex + 1);
-        assert(pControl);
-        if (pControl->GetID() >= GetFirstMruID()
-            && pControl->GetID() <= GetFirstMruID() + pRecentFileList->m_nSize)
-        {
-            m_pControls->Remove(pControl);
-        }
-        else
-        {
-            break;
-        }
-    }
-
-    if (m_pParent->IsCustomizeMode())
-    {
-        m_dwHideFlags = 0;
-        SetEnabled(TRUE);
-        return;
-    }
-
-    if (pArrNames[0].IsEmpty())
-    {
-        SetCaption(CString(MAKEINTRESOURCE(IDS_NORECENTFILE_CAPTION)));
-        SetDescription("No recently opened files");
-        m_dwHideFlags = 0;
-        SetEnabled(FALSE);
-
-        return;
-    }
-    else
-    {
-        SetCaption(CString(MAKEINTRESOURCE(IDS_RECENTFILE_CAPTION)));
-        SetDescription("Open this document");
-    }
-
-    m_dwHideFlags |= xtpHideGeneric;
-
-    CString sCurDir = (Path::GetEditingGameDataFolder() + "\\").c_str();
-    int nCurDir = sCurDir.GetLength();
-
-    CString strName;
-    CString strTemp;
-    int iLastValidMRU = 0;
-
-    for (int iMRU = 0; iMRU < pRecentFileList->m_nSize; iMRU++)
-    {
-        if (!pRecentFileList->GetDisplayName(strName, iMRU, sCurDir.GetBuffer(), nCurDir))
-        {
-            break;
-        }
-
-        if (DoesFileExist(pArrNames[iMRU]))
-        {
-            CString sCurEntryDir = pArrNames[iMRU].Left(nCurDir);
-
-            if (sCurEntryDir.CompareNoCase(sCurDir) != 0)
-            {
-                //unavailable entry (wrong directory)
-                continue;
-            }
-        }
-        else
-        {
-            //invalid entry (not existing)
-            continue;
-        }
-
-        int nId = iMRU + GetFirstMruID();
-
-        CXTPControl* pControl = m_pControls->Add(xtpControlButton, nId, _T(""), m_nIndex + iLastValidMRU + 1, TRUE);
-        assert(pControl);
-
-        pControl->SetCaption(CXTPControlWindowList::ConstructCaption(strName, iLastValidMRU + 1));
-        pControl->SetFlags(xtpFlagManualUpdate);
-        pControl->SetBeginGroup(iLastValidMRU == 0 && m_nIndex != 0);
-        pControl->SetParameter(pArrNames[iMRU]);
-
-        CString sDescription = "Open file:  " + pArrNames[iMRU];
-        pControl->SetDescription(sDescription);
-
-        if ((GetFlags() & xtpFlagWrapRow) && iMRU == 0)
-        {
-            pControl->SetFlags(pControl->GetFlags() | xtpFlagWrapRow);
-        }
-
-        ++iLastValidMRU;
-    }
-
-    //if no entry was valid, treat as none would exist
-    if (iLastValidMRU == 0)
-    {
-        SetCaption(CString(MAKEINTRESOURCE(IDS_NORECENTFILE_CAPTION)));
-        SetDescription("No recently opened files");
-        m_dwHideFlags = 0;
-        SetEnabled(FALSE);
-    }
-}
diff --git a/Code/Editor/ControlMRU.h b/Code/Editor/ControlMRU.h
deleted file mode 100644
index 4ca6562589..0000000000
--- a/Code/Editor/ControlMRU.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#pragma once
-#ifndef CRYINCLUDE_EDITOR_CONTROLMRU_H
-#define CRYINCLUDE_EDITOR_CONTROLMRU_H
-
-class CControlMRU
-    : public CXTPControlRecentFileList
-{
-protected:
-    virtual void OnCalcDynamicSize(DWORD dwMode);
-
-private:
-    DECLARE_XTP_CONTROL(CControlMRU)
-    bool DoesFileExist(CString& sFileName);
-};
-#endif // CRYINCLUDE_EDITOR_CONTROLMRU_H
diff --git a/Code/Editor/Controls/ConsoleSCBMFC.cpp b/Code/Editor/Controls/ConsoleSCBMFC.cpp
deleted file mode 100644
index 3337997811..0000000000
--- a/Code/Editor/Controls/ConsoleSCBMFC.cpp
+++ /dev/null
@@ -1,543 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#include "EditorDefs.h"
-#include "ConsoleSCBMFC.h"
-#include "PropertiesDialog.h"
-#include "QtViewPaneManager.h"
-#include "Core/QtEditorApplication.h"
-
-#include 
-
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-
-namespace MFC
-{
-
-static CPropertiesDialog* gPropertiesDlg = nullptr;
-static CString mfc_popup_helper(HWND hwnd, int x, int y);
-static CConsoleSCB* s_consoleSCB = nullptr;
-
-static QString RemoveColorCode(const QString& text, int& iColorCode)
-{
-    QString cleanString;
-    cleanString.reserve(text.size());
-
-    const int textSize = text.size();
-    for (int i = 0; i < textSize; ++i)
-    {
-        QChar c = text.at(i);
-        bool isLast = i == textSize - 1;
-        if (c == '$' && !isLast && text.at(i + 1).isDigit())
-        {
-            if (iColorCode == 0)
-            {
-                iColorCode = text.at(i + 1).digitValue();
-            }
-            ++i;
-            continue;
-        }
-
-        if (c == '\r' || c == '\n')
-        {
-            ++i;
-            continue;
-        }
-
-        cleanString.append(c);
-    }
-
-    return cleanString;
-}
-
-ConsoleLineEdit::ConsoleLineEdit(QWidget* parent)
-    : QLineEdit(parent)
-    , m_historyIndex(0)
-    , m_bReusedHistory(false)
-{
-}
-
-void ConsoleLineEdit::mousePressEvent(QMouseEvent* ev)
-{
-    if (ev->type() == QEvent::MouseButtonPress && ev->button() & Qt::RightButton)
-    {
-        Q_EMIT variableEditorRequested();
-    }
-
-    QLineEdit::mousePressEvent(ev);
-}
-
-void ConsoleLineEdit::mouseDoubleClickEvent(QMouseEvent* ev)
-{
-    Q_EMIT variableEditorRequested();
-}
-
-bool ConsoleLineEdit::event(QEvent* ev)
-{
-    // Tab key doesn't go to keyPressEvent(), must be processed here
-
-    if (ev->type() != QEvent::KeyPress)
-    {
-        return QLineEdit::event(ev);
-    }
-
-    QKeyEvent* ke = static_cast(ev);
-    if (ke->key() != Qt::Key_Tab)
-    {
-        return QLineEdit::event(ev);
-    }
-
-    QString inputStr = text();
-    QString newStr;
-
-    QStringList tokens = inputStr.split(" ");
-    inputStr = tokens.isEmpty() ? QString() : tokens.first();
-    IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
-
-    const bool ctrlPressed = ke->modifiers() & Qt::ControlModifier;
-    CString cstring = QtUtil::ToCString(inputStr); // TODO: Use QString once the backend stops using QString
-    if (ctrlPressed)
-    {
-        newStr = QtUtil::ToString(console->AutoCompletePrev(cstring));
-    }
-    else
-    {
-        newStr = QtUtil::ToString(console->ProcessCompletion(cstring));
-        newStr = QtUtil::ToString(console->AutoComplete(cstring));
-
-        if (newStr.isEmpty())
-        {
-            newStr = QtUtil::ToQString(GetIEditor()->GetCommandManager()->AutoComplete(QtUtil::ToString(newStr)));
-        }
-    }
-
-    if (!newStr.isEmpty())
-    {
-        newStr += " ";
-        setText(newStr);
-    }
-
-    deselect();
-    return true;
-}
-
-void ConsoleLineEdit::keyPressEvent(QKeyEvent* ev)
-{
-    IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
-    auto commandManager = GetIEditor()->GetCommandManager();
-
-    console->ResetAutoCompletion();
-
-    switch (ev->key())
-    {
-    case Qt::Key_Enter:
-    case Qt::Key_Return:
-    {
-        QString str = text().trimmed();
-        if (!str.isEmpty())
-        {
-            if (commandManager->IsRegistered(QtUtil::ToCString(str)))
-            {
-                commandManager->Execute(QtUtil::ToString(str));
-            }
-            else
-            {
-                CLogFile::WriteLine(QtUtil::ToCString(str));
-                GetIEditor()->GetSystem()->GetIConsole()->ExecuteString(QtUtil::ToCString(str));
-            }
-
-            // If a history command was reused directly via up arrow enter, do not reset history index
-            if (m_history.size() > 0 && m_historyIndex < m_history.size() && m_history[m_historyIndex] == str)
-            {
-                m_bReusedHistory = true;
-            }
-            else
-            {
-                m_historyIndex = m_history.size();
-            }
-
-            // Do not add the same string if it is the top of the stack, but allow duplicate entries otherwise
-            if (m_history.isEmpty() || m_history.back() != str)
-            {
-                m_history.push_back(str);
-                if (!m_bReusedHistory)
-                {
-                    m_historyIndex = m_history.size();
-                }
-            }
-        }
-        else
-        {
-            m_historyIndex = m_history.size();
-        }
-
-        setText(QString());
-        break;
-    }
-    case Qt::Key_AsciiTilde: // ~
-    case Qt::Key_Agrave: // `
-        // disable log.
-        GetIEditor()->ShowConsole(false);
-        setText(QString());
-        m_historyIndex = m_history.size();
-        break;
-    case Qt::Key_Escape:
-        setText(QString());
-        m_historyIndex = m_history.size();
-        break;
-    case Qt::Key_Up:
-        DisplayHistory(false /*bForward*/);
-        break;
-    case Qt::Key_Down:
-        DisplayHistory(true /*bForward*/);
-        break;
-    default:
-        QLineEdit::keyPressEvent(ev);
-    }
-}
-
-void ConsoleLineEdit::DisplayHistory(bool bForward)
-{
-    if (m_history.isEmpty())
-    {
-        return;
-    }
-
-    // Immediately after reusing a history entry, ensure up arrow re-displays command just used
-    if (!m_bReusedHistory || bForward)
-    {
-        m_historyIndex = static_cast(clamp_tpl(static_cast(m_historyIndex) + (bForward ? 1 : -1), 0, m_history.size() - 1));
-    }
-    m_bReusedHistory = false;
-
-    setText(m_history[m_historyIndex]);
-}
-
-ConsoleTextEdit::ConsoleTextEdit(QWidget* parent)
-    : QTextEdit(parent)
-{
-}
-
-
-Lines CConsoleSCB::s_pendingLines;
-
-CConsoleSCB::CConsoleSCB(QWidget* parent)
-    : QWidget(parent)
-    , ui(new Ui::ConsoleMFC())
-    , m_richEditTextLength(0)
-    , m_backgroundTheme(gSettings.consoleBackgroundColorTheme)
-{
-    m_lines = s_pendingLines;
-    s_pendingLines.clear();
-    s_consoleSCB = this;
-    ui->setupUi(this);
-    setMinimumHeight(120);
-
-    // Setup the color table for the default (light) theme
-    m_colorTable << QColor(0, 0, 0)
-        << QColor(0, 0, 0)
-        << QColor(0, 0, 200) // blue
-        << QColor(0, 200, 0) // green
-        << QColor(200, 0, 0) // red
-        << QColor(0, 200, 200) // cyan
-        << QColor(128, 112, 0) // yellow
-        << QColor(200, 0, 200) // red+blue
-        << QColor(0x000080ff)
-        << QColor(0x008f8f8f);
-    OnStyleSettingsChanged();
-
-    connect(ui->button, &QPushButton::clicked, this, &CConsoleSCB::showVariableEditor);
-    connect(ui->lineEdit, &MFC::ConsoleLineEdit::variableEditorRequested, this, &MFC::CConsoleSCB::showVariableEditor);
-    connect(Editor::EditorQtApplication::instance(), &Editor::EditorQtApplication::skinChanged, this, &MFC::CConsoleSCB::OnStyleSettingsChanged);
-
-    if (GetIEditor()->IsInConsolewMode())
-    {
-        // Attach / register edit box
-        //CLogFile::AttachEditBox(m_edit.GetSafeHwnd()); // FIXME
-    }
-}
-
-CConsoleSCB::~CConsoleSCB()
-{
-    s_consoleSCB = nullptr;
-    delete gPropertiesDlg;
-    gPropertiesDlg = nullptr;
-    CLogFile::AttachEditBox(nullptr);
-}
-
-void CConsoleSCB::RegisterViewClass()
-{
-    QtViewOptions opts;
-    opts.preferedDockingArea = Qt::BottomDockWidgetArea;
-    opts.isDeletable = false;
-    opts.isStandard = true;
-    opts.showInMenu = true;
-    opts.builtInActionId = ID_VIEW_CONSOLEWINDOW;
-    opts.sendViewPaneNameBackToAmazonAnalyticsServers = true;
-    RegisterQtViewPane(GetIEditor(), LyViewPane::Console, LyViewPane::CategoryTools, opts);
-}
-
-void CConsoleSCB::OnStyleSettingsChanged()
-{
-    ui->button->setIcon(QIcon(QString(":/controls/img/cvar_dark.bmp")));
-
-    // Set the debug/warning text colors appropriately for the background theme
-    // (e.g. not have black text on black background)
-    QColor textColor = Qt::black;
-    m_backgroundTheme = gSettings.consoleBackgroundColorTheme;
-    if (m_backgroundTheme == SEditorSettings::ConsoleColorTheme::Dark)
-    {
-        textColor = Qt::white;
-    }
-    m_colorTable[0] = textColor;
-    m_colorTable[1] = textColor;
-
-    QColor bgColor;
-    if (!GetIEditor()->IsInConsolewMode() && CConsoleSCB::GetCreatedInstance() && m_backgroundTheme == SEditorSettings::ConsoleColorTheme::Dark)
-    {
-        bgColor = Qt::black;
-    }
-    else
-    {
-        bgColor = Qt::white;
-    }
-
-    ui->textEdit->setStyleSheet(QString("QTextEdit{ background: %1 }").arg(bgColor.name(QColor::HexRgb)));
-
-    // Clear out the console text when we change our background color since
-    // some of the previous text colors may not be appropriate for the
-    // new background color
-    ui->textEdit->clear();
-}
-
-void CConsoleSCB::showVariableEditor()
-{
-    const QPoint cursorPos = QCursor::pos();
-    CString str = mfc_popup_helper(0, cursorPos.x(), cursorPos.y());
-    if (!str.IsEmpty())
-    {
-        ui->lineEdit->setText(QtUtil::ToQString(str));
-    }
-}
-
-void CConsoleSCB::SetInputFocus()
-{
-    ui->lineEdit->setFocus();
-    ui->lineEdit->setText(QString());
-}
-
-void CConsoleSCB::AddToConsole(const QString& text, bool bNewLine)
-{
-    m_lines.push_back({ text, bNewLine });
-    FlushText();
-}
-
-void CConsoleSCB::FlushText()
-{
-    if (m_lines.empty())
-    {
-        return;
-    }
-
-    // Store our current cursor in case we need to restore it, and check if
-    // the user has scrolled the text edit away from the bottom
-    const QTextCursor oldCursor = ui->textEdit->textCursor();
-    QScrollBar* scrollBar = ui->textEdit->verticalScrollBar();
-    const int oldScrollValue = scrollBar->value();
-    bool scrolledOffBottom = oldScrollValue != scrollBar->maximum();
-
-    ui->textEdit->moveCursor(QTextCursor::End);
-    QTextCursor textCursor = ui->textEdit->textCursor();
-
-    while (!m_lines.empty())
-    {
-        ConsoleLine line = m_lines.front();
-        m_lines.pop_front();
-
-        int iColor = 0;
-        QString text = MFC::RemoveColorCode(line.text, iColor);
-        if (iColor < 0 || iColor >= m_colorTable.size())
-        {
-            iColor = 0;
-        }
-
-        if (line.newLine)
-        {
-            text = QtUtil::trimRight(text);
-            text = "\r\n" + text;
-        }
-
-        QTextCharFormat format;
-        const QColor color(m_colorTable[iColor]);
-        format.setForeground(color);
-
-        if (iColor != 0)
-        {
-            format.setFontWeight(QFont::Bold);
-        }
-
-        textCursor.setCharFormat(format);
-        textCursor.insertText(text);
-    }
-
-    // If the user has selected some text in the text edit area or has scrolled
-    // away from the bottom, then restore the previous cursor and keep the scroll
-    // bar in the same location
-    if (oldCursor.hasSelection() || scrolledOffBottom)
-    {
-        ui->textEdit->setTextCursor(oldCursor);
-        scrollBar->setValue(oldScrollValue);
-    }
-    // Otherwise scroll to the bottom so the latest text can be seen
-    else
-    {
-        scrollBar->setValue(scrollBar->maximum());
-    }
-}
-
-QSize CConsoleSCB::minimumSizeHint() const
-{
-    return QSize(-1, -1);
-}
-
-QSize CConsoleSCB::sizeHint() const
-{
-    return QSize(100, 100);
-}
-
-/** static */
-void CConsoleSCB::AddToPendingLines(const QString& text, bool bNewLine)
-{
-    s_pendingLines.push_back({ text, bNewLine });
-}
-
-static CVarBlock* VarBlockFromConsoleVars()
-{
-    IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
-    std::vector cmds;
-    cmds.resize(console->GetNumVars());
-    size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size());
-
-    CVarBlock* vb = new CVarBlock;
-    IVariable* pVariable = 0;
-    for (int i = 0; i < cmdCount; i++)
-    {
-        ICVar* pCVar = console->GetCVar(cmds[i]);
-        if (!pCVar)
-        {
-            continue;
-        }
-        int varType = pCVar->GetType();
-
-        switch (varType)
-        {
-        case CVAR_INT:
-            pVariable = new CVariable();
-            pVariable->Set(pCVar->GetIVal());
-            break;
-        case CVAR_FLOAT:
-            pVariable = new CVariable();
-            pVariable->Set(pCVar->GetFVal());
-            break;
-        case CVAR_STRING:
-            pVariable = new CVariable();
-            pVariable->Set(pCVar->GetString());
-            break;
-        default:
-            assert(0);
-        }
-
-        pVariable->SetDescription(pCVar->GetHelp());
-        pVariable->SetName(cmds[i]);
-
-        if (pVariable)
-        {
-            vb->AddVariable(pVariable);
-        }
-    }
-    return vb;
-}
-
-static void OnConsoleVariableUpdated(IVariable* pVar)
-{
-    if (!pVar)
-    {
-        return;
-    }
-    CString varName = pVar->GetName();
-    ICVar* pCVar = GetIEditor()->GetSystem()->GetIConsole()->GetCVar(varName);
-    if (!pCVar)
-    {
-        return;
-    }
-    if (pVar->GetType() == IVariable::INT)
-    {
-        int val;
-        pVar->Get(val);
-        pCVar->Set(val);
-    }
-    else if (pVar->GetType() == IVariable::FLOAT)
-    {
-        float val;
-        pVar->Get(val);
-        pCVar->Set(val);
-    }
-    else if (pVar->GetType() == IVariable::STRING)
-    {
-        CString val;
-        pVar->Get(val);
-        pCVar->Set(val);
-    }
-}
-
-static CString mfc_popup_helper(HWND hwnd, int x, int y)
-{
-    IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
-
-    TSmartPtr vb = VarBlockFromConsoleVars();
-    XmlNodeRef node;
-    if (!gPropertiesDlg)
-    {
-        gPropertiesDlg = new CPropertiesDialog("Console Variables", node, AfxGetMainWnd(), true);
-    }
-    if (!gPropertiesDlg->m_hWnd)
-    {
-        gPropertiesDlg->Create(CPropertiesDialog::IDD, AfxGetMainWnd());
-        gPropertiesDlg->SetUpdateCallback(AZStd::bind(OnConsoleVariableUpdated, AZStd::placeholders::_1));
-    }
-    gPropertiesDlg->ShowWindow(SW_SHOW);
-    gPropertiesDlg->BringWindowToTop();
-    gPropertiesDlg->GetPropertyCtrl()->AddVarBlock(vb);
-
-    return "";
-}
-
-CConsoleSCB* CConsoleSCB::GetCreatedInstance()
-{
-    return s_consoleSCB;
-}
-
-} // namespace MFC
-
-#include 
diff --git a/Code/Editor/Util/IXmlHistoryManager.h b/Code/Editor/Util/IXmlHistoryManager.h
deleted file mode 100644
index e133d073bc..0000000000
--- a/Code/Editor/Util/IXmlHistoryManager.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#ifndef CRYINCLUDE_EDITOR_UTIL_IXMLHISTORYMANAGER_H
-#define CRYINCLUDE_EDITOR_UTIL_IXMLHISTORYMANAGER_H
-#pragma once
-
-
-// Helper class to handle Redo/Undo on set of Xml nodes
-struct IXmlUndoEventHandler
-{
-    virtual bool SaveToXml(XmlNodeRef& xmlNode) = 0;
-    virtual bool LoadFromXml(const XmlNodeRef& xmlNode) = 0;
-    virtual bool ReloadFromXml(const XmlNodeRef& xmlNode) = 0;
-};
-
-struct IXmlHistoryEventListener
-{
-    enum EHistoryEventType
-    {
-        eHET_HistoryDeleted,
-        eHET_HistoryCleared,
-        eHET_HistorySaved,
-
-        eHET_VersionChanged,
-        eHET_VersionAdded,
-
-        eHET_HistoryInvalidate,
-
-        eHET_HistoryGroupChanged,
-        eHET_HistoryGroupAdded,
-        eHET_HistoryGroupRemoved,
-    };
-    virtual void OnEvent(EHistoryEventType event, void* pData = NULL) = 0;
-};
-
-struct IXmlHistoryView
-{
-    virtual bool LoadXml(int typeId, const XmlNodeRef& xmlNode, IXmlUndoEventHandler*& pUndoEventHandler, uint32 userindex) = 0;
-    virtual void UnloadXml(int typeId) = 0;
-};
-
-struct IXmlHistoryManager
-{
-    // Undo/Redo
-    virtual bool Undo() = 0;
-    virtual bool Redo() = 0;
-    virtual bool Goto(int historyNum) = 0;
-    virtual void RecordUndo(IXmlUndoEventHandler* pEventHandler, const char* desc) = 0;
-    virtual void UndoEventHandlerDestroyed(IXmlUndoEventHandler* pEventHandler, uint32 typeId = 0, bool destoryForever = false) = 0;
-    virtual void RestoreUndoEventHandler(IXmlUndoEventHandler* pEventHandler, uint32 typeId) = 0;
-
-    virtual void RegisterEventListener(IXmlHistoryEventListener* pEventListener) = 0;
-    virtual void UnregisterEventListener(IXmlHistoryEventListener* pEventListener) = 0;
-
-    // History
-    virtual void ClearHistory(bool flagAsSaved = false) = 0;
-    virtual int GetVersionCount() const = 0;
-    virtual const AZStd::string& GetVersionDesc(int number) const = 0;
-    virtual int GetCurrentVersionNumber() const = 0;
-
-    // Views
-    virtual void RegisterView(IXmlHistoryView* pView) = 0;
-    virtual void UnregisterView(IXmlHistoryView* pView) = 0;
-};
-
-#endif // CRYINCLUDE_EDITOR_UTIL_IXMLHISTORYMANAGER_H
diff --git a/Code/Editor/Util/StringNoCasePredicate.h b/Code/Editor/Util/StringNoCasePredicate.h
deleted file mode 100644
index 4fb81cf7d6..0000000000
--- a/Code/Editor/Util/StringNoCasePredicate.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-// Description : Utility class to help in STL algorithms on containers with
-//               CStrings when intending to use case insensitive searches or sorting for
-//               example.
-
-
-#ifndef CRYINCLUDE_EDITOR_UTIL_STRINGNOCASEPREDICATE_H
-#define CRYINCLUDE_EDITOR_UTIL_STRINGNOCASEPREDICATE_H
-#pragma once
-
-/*
-Utility class to help in STL algorithms on containers with CStrings
-when intending to use case insensitive searches or sorting for example.
-
-e.g.
-std::vector< CString > v;
-...
-std::sort( v.begin(), v.end(), CStringNoCasePredicate::LessThan() );
-std::find_if( v.begin(), v.end(), CStringNoCasePredicate::Equal( stringImLookingFor ) );
-*/
-class CStringNoCasePredicate
-{
-public:
-    //////////////////////////////////////////////////////////////////////////
-    struct Equal
-    {
-        Equal(const QString& referenceString)
-            : m_referenceString(referenceString)
-        {
-        }
-
-        bool operator() (const QString& arg) const
-        {
-            return (m_referenceString.compare(arg, Qt::CaseInsensitive) == 0);
-        }
-
-    private:
-        const QString& m_referenceString;
-    };
-    //////////////////////////////////////////////////////////////////////////
-
-    //////////////////////////////////////////////////////////////////////////
-    struct LessThan
-    {
-        bool operator() (const QString& arg1, const QString& arg2) const
-        {
-            return (arg1.CompareNoCase(arg2) < 0);
-        }
-    };
-    //////////////////////////////////////////////////////////////////////////
-};
-
-
-#endif // CRYINCLUDE_EDITOR_UTIL_STRINGNOCASEPREDICATE_H
diff --git a/Code/Editor/Util/XmlHistoryManager.cpp b/Code/Editor/Util/XmlHistoryManager.cpp
deleted file mode 100644
index b642929af1..0000000000
--- a/Code/Editor/Util/XmlHistoryManager.cpp
+++ /dev/null
@@ -1,875 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#include "EditorDefs.h"
-
-#include "XmlHistoryManager.h"
-
-////////////////////////////////////////////////////////////////////////////
-SXmlHistory::SXmlHistory(CXmlHistoryManager* pManager, const XmlNodeRef& xmlBaseVersion, uint32 typeId)
-    : m_pManager(pManager)
-    , m_typeId(typeId)
-    , m_DeletedVersion(-1)
-    , m_SavedVersion(-1)
-{
-    int newVersionNumber = m_pManager->GetCurrentVersionNumber() + (m_pManager->IsPreparedForNextVersion() ? 1 : 0);
-    m_xmlVersionList[ newVersionNumber ] = xmlBaseVersion;
-}
-
-////////////////////////////////////////////////////////////////////////////
-void SXmlHistory::AddToHistory(const XmlNodeRef& newXmlVersion)
-{
-    int newVersionNumber = m_pManager->IncrementVersion(this);
-    m_xmlVersionList[ newVersionNumber ] = newXmlVersion;
-}
-
-////////////////////////////////////////////////////////////////////////////
-const XmlNodeRef& SXmlHistory::Undo(bool* bVersionExist)
-{
-    m_pManager->Undo();
-    return GetCurrentVersion(bVersionExist);
-}
-
-////////////////////////////////////////////////////////////////////////////
-const XmlNodeRef& SXmlHistory::Redo()
-{
-    m_pManager->Redo();
-    return GetCurrentVersion();
-}
-
-////////////////////////////////////////////////////////////////////////////
-const XmlNodeRef& SXmlHistory::GetCurrentVersion(bool* bVersionExist, int* iVersionNumber) const
-{
-    int currentVersion = m_pManager->GetCurrentVersionNumber();
-
-    TXmlVersionMap::const_iterator it = m_xmlVersionList.begin();
-    TXmlVersionMap::const_iterator previt = m_xmlVersionList.begin();
-    while (it != m_xmlVersionList.end())
-    {
-        if (it->first > currentVersion)
-        {
-            break;
-        }
-        previt = it;
-        ++it;
-    }
-
-    if (bVersionExist)
-    {
-        *bVersionExist = currentVersion >= m_xmlVersionList.begin()->first;
-    }
-    if (iVersionNumber)
-    {
-        *iVersionNumber = previt->first;
-    }
-
-    return previt->second;
-}
-
-////////////////////////////////////////////////////////////////////////////
-bool SXmlHistory::IsModified() const
-{
-    int currVersion;
-    GetCurrentVersion(NULL, &currVersion);
-    return m_SavedVersion != currVersion;
-}
-
-////////////////////////////////////////////////////////////////////////////
-void SXmlHistory::FlagAsDeleted()
-{
-    assert(m_pManager->IsPreparedForNextVersion());
-    m_DeletedVersion = m_pManager->GetCurrentVersionNumber() + 1;
-    m_SavedVersion = -1;
-}
-
-////////////////////////////////////////////////////////////////////////////
-void SXmlHistory::FlagAsSaved()
-{
-    if (Exist())
-    {
-        int currVersion;
-        GetCurrentVersion(NULL, &currVersion);
-        m_SavedVersion = currVersion;
-    }
-}
-
-////////////////////////////////////////////////////////////////////////////
-bool SXmlHistory::Exist() const
-{
-    //  int currentVersion = m_pManager->GetCurrentVersionNumber();
-    //  bool deleted = m_DeletedVersion != -1 && currentVersion >= m_DeletedVersion;
-    //  bool exist = currentVersion >= m_xmlVersionList.begin()->first;
-    //  return !deleted && exist;
-    int currentVersion = m_pManager->GetCurrentVersionNumber();
-    return currentVersion >= m_xmlVersionList.begin()->first && (m_DeletedVersion == -1 || currentVersion < m_DeletedVersion);
-}
-
-////////////////////////////////////////////////////////////////////////////
-void SXmlHistory::ClearRedo()
-{
-    int currentVersion = m_pManager->GetCurrentVersionNumber();
-    if (m_DeletedVersion > currentVersion + (m_pManager->IsPreparedForNextVersion() ? 1 : 0))
-    {
-        m_DeletedVersion = -1;
-    }
-    TXmlVersionMap::iterator it = m_xmlVersionList.begin();
-    for (; it != m_xmlVersionList.end(); ++it)
-    {
-        if (it->first > currentVersion)
-        {
-            break;
-        }
-    }
-    if (it != m_xmlVersionList.end())
-    {
-        ++it;
-        while (it != m_xmlVersionList.end())
-        {
-            m_xmlVersionList.erase(it++);
-        }
-    }
-}
-
-////////////////////////////////////////////////////////////////////////////
-void SXmlHistory::ClearHistory(bool flagAsSaved)
-{
-    bool wasModified = !flagAsSaved && IsModified();
-    m_DeletedVersion = Exist() ? -1 : 0;
-    ClearRedo();
-    XmlNodeRef latest = m_xmlVersionList.rbegin()->second;
-    m_xmlVersionList.clear();
-    m_xmlVersionList[ 0 ] = latest;
-    m_SavedVersion = wasModified ? -1 : 0;
-}
-
-////////////////////////////////////////////////////////////////////////////
-SXmlHistoryGroup::SXmlHistoryGroup(CXmlHistoryManager* pManager, uint32 typeId)
-    : m_pManager(pManager)
-    , m_typeId(typeId)
-{
-}
-
-////////////////////////////////////////////////////////////////////////////
-SXmlHistory* SXmlHistoryGroup::GetHistory(int index) const
-{
-    THistoryList::const_iterator it = m_List.begin();
-    while (index > 0 && it != m_List.end())
-    {
-        ++it;
-        if ((*it)->Exist())
-        {
-            --index;
-        }
-    }
-    return it != m_List.end() ? *it : NULL;
-}
-
-////////////////////////////////////////////////////////////////////////////
-int SXmlHistoryGroup::GetHistoryCount() const
-{
-    int count = 0;
-    for (THistoryList::const_iterator it = m_List.begin(); it != m_List.end(); ++it)
-    {
-        if ((*it)->Exist())
-        {
-            count++;
-        }
-    }
-    return count;
-}
-
-////////////////////////////////////////////////////////////////////////////
-SXmlHistory* SXmlHistoryGroup::GetHistoryByTypeId(uint32 typeId, int index /*= 0*/) const
-{
-    for (int i = 0; i < GetHistoryCount(); ++i)
-    {
-        SXmlHistory* pHistory = GetHistory(i);
-        if (pHistory->GetTypeId() == typeId)
-        {
-            index--;
-        }
-        if (index == -1)
-        {
-            return pHistory;
-        }
-    }
-    return NULL;
-}
-
-////////////////////////////////////////////////////////////////////////////
-int SXmlHistoryGroup::GetHistoryCountByTypeId(uint32 typeId) const
-{
-    int res = 0;
-    for (int i = 0; i < GetHistoryCount(); ++i)
-    {
-        if (GetHistory(i)->GetTypeId() == typeId)
-        {
-            res++;
-        }
-    }
-    return res;
-}
-
-////////////////////////////////////////////////////////////////////////////
-int SXmlHistoryGroup::CreateXmlHistory(uint32 typeId, const XmlNodeRef& xmlBaseVersion)
-{
-    if (m_pManager)
-    {
-        m_List.push_back(m_pManager->CreateXmlHistory(typeId, xmlBaseVersion));
-        return m_List.size() - 1;
-    }
-    return -1;
-}
-
-////////////////////////////////////////////////////////////////////////////
-int SXmlHistoryGroup::GetHistoryIndex(const SXmlHistory* pHistory) const
-{
-    int index = 0;
-    for (THistoryList::const_iterator it = m_List.begin(); it != m_List.end(); ++it)
-    {
-        if (*it == pHistory)
-        {
-            return index;
-        }
-        index++;
-    }
-    return -1;
-}
-
-////////////////////////////////////////////////////////////////////////////
-CXmlHistoryManager::CXmlHistoryManager()
-    : m_CurrentVersion(0)
-    , m_LatestVersion(0)
-    , m_pExclusiveListener(NULL)
-    , m_RecordNextVersion(false)
-    , m_pExActiveGroup(NULL)
-    , m_bIsActiveGroupEx(false)
-{
-    m_pNullGroup = new SXmlHistoryGroup(this, (uint32) - 1);
-}
-
-CXmlHistoryManager::~CXmlHistoryManager()
-{
-    delete m_pNullGroup;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-bool CXmlHistoryManager::Undo()
-{
-    if (m_CurrentVersion > 0)
-    {
-        int prevVersion = m_CurrentVersion;
-        const SXmlHistoryGroup* pPrevCurrGroup = GetActiveGroup();
-        m_CurrentVersion--;
-        ReloadCurrentVersion(pPrevCurrGroup, prevVersion);
-        return true;
-    }
-    return false;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-bool CXmlHistoryManager::Redo()
-{
-    if (m_CurrentVersion < m_LatestVersion)
-    {
-        int prevVersion = m_CurrentVersion;
-        const SXmlHistoryGroup* pPrevCurrGroup = GetActiveGroup();
-        m_CurrentVersion++;
-        ReloadCurrentVersion(pPrevCurrGroup, prevVersion);
-        return true;
-    }
-    return false;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-bool CXmlHistoryManager::Goto(int historyNum)
-{
-    if (historyNum >= 0 && historyNum <= m_LatestVersion)
-    {
-        int prevVersion = m_CurrentVersion;
-        const SXmlHistoryGroup* pPrevCurrGroup = GetActiveGroup();
-        m_CurrentVersion = historyNum;
-        ReloadCurrentVersion(pPrevCurrGroup, prevVersion);
-        return true;
-    }
-    return false;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RecordUndo(IXmlUndoEventHandler* pEventHandler, const char* desc)
-{
-    ClearRedo();
-    SXmlHistory* pChangedXml = m_UndoEventHandlerMap[ pEventHandler ].CurrentData;
-    assert(pChangedXml);
-
-    XmlNodeRef newData = gEnv->pSystem->CreateXmlNode();
-#if !defined(NDEBUG)
-    bool bRes =
-#endif
-        pEventHandler->SaveToXml(newData);
-    assert(bRes);
-
-    TXmlHistotyGroupPtrList activeGroups = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups;
-
-    pChangedXml->AddToHistory(newData);
-    m_UndoEventHandlerMap[ pEventHandler ].HistoryData[ m_CurrentVersion ] = pChangedXml;
-    m_HistoryInfoMap[ m_CurrentVersion ].HistoryDescription = desc;
-    m_HistoryInfoMap[ m_CurrentVersion ].IsNullUndo = false;
-    m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups = activeGroups;
-    m_HistoryInfoMap[ m_CurrentVersion ].HistoryInvalidated = false;
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_VersionAdded);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::UndoEventHandlerDestroyed(IXmlUndoEventHandler* pEventHandler, uint32 typeId /*= 0*/, bool destoryForever /*= false*/)
-{
-    if (destoryForever)
-    {
-        UnregisterUndoEventHandler(pEventHandler);
-    }
-    else
-    {
-        m_InvalidHandlerMap[typeId] = pEventHandler;
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RestoreUndoEventHandler(IXmlUndoEventHandler* pEventHandler, uint32 typeId)
-{
-    TInvalidUndoEventListener::iterator it = m_InvalidHandlerMap.find(typeId);
-    if (it != m_InvalidHandlerMap.end())
-    {
-        IXmlUndoEventHandler* pLastHandler = it->second;
-        TUndoEventHandlerMap::iterator lastit = m_UndoEventHandlerMap.find(pLastHandler);
-        if (lastit != m_UndoEventHandlerMap.end())
-        {
-            m_UndoEventHandlerMap[pEventHandler] = lastit->second;
-            m_UndoEventHandlerMap.erase(lastit);
-        }
-        m_InvalidHandlerMap.erase(it);
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RegisterEventListener(IXmlHistoryEventListener* pEventListener)
-{
-    stl::push_back_unique(m_EventListener, pEventListener);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::UnregisterEventListener(IXmlHistoryEventListener* pEventListener)
-{
-    m_EventListener.remove(pEventListener);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::PrepareForNextVersion()
-{
-    assert(!m_RecordNextVersion);
-    m_RecordNextVersion = true;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RecordNextVersion(SXmlHistory* pHistory, XmlNodeRef newData, const char* undoDesc /*= NULL*/)
-{
-    assert(m_RecordNextVersion);
-    RegisterUndoEventHandler(this, pHistory);
-    m_newHistoryData = newData;
-    RecordUndo(this, undoDesc ? undoDesc : "");
-    m_RecordNextVersion = false;
-    m_HistoryInfoMap[ m_CurrentVersion ].HistoryInvalidated = true;
-    UnregisterUndoEventHandler(this);
-    SetActiveGroupInt(GetActiveGroup());
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryInvalidate);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-bool CXmlHistoryManager::SaveToXml(XmlNodeRef& xmlNode)
-{
-    assert(m_newHistoryData);
-    xmlNode = m_newHistoryData;
-    return true;
-}
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::ClearHistory(bool flagAsSaved)
-{
-    TXmlHistotyGroupPtrList activeGropus = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups;
-    for (TXmlHistoryList::iterator it = m_XmlHistoryList.begin(); it != m_XmlHistoryList.end(); ++it)
-    {
-        it->ClearHistory(flagAsSaved);
-    }
-
-    SetActiveGroup(NULL);
-
-    m_CurrentVersion = 0;
-    m_LatestVersion = 0;
-
-    m_UndoEventHandlerMap.clear();
-    m_HistoryInfoMap.clear();
-
-    m_HistoryInfoMap[ 0 ].HistoryDescription = "New History";
-    m_HistoryInfoMap[ 0 ].ActiveGroups = activeGropus;
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryCleared);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-const AZStd::string& CXmlHistoryManager::GetVersionDesc(int number) const
-{
-    THistoryInfoMap::const_iterator it = m_HistoryInfoMap.find(number);
-    if (it != m_HistoryInfoMap.end())
-    {
-        return it->second.HistoryDescription;
-    }
-
-    static AZStd::string undef("UNDEFINED");
-    return undef;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RegisterView(IXmlHistoryView* pView)
-{
-    stl::push_back_unique(m_Views, pView);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::UnregisterView(IXmlHistoryView* pView)
-{
-    m_Views.remove(pView);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-SXmlHistoryGroup* CXmlHistoryManager::CreateXmlGroup(uint32 typeId)
-{
-    m_Groups.push_back(SXmlHistoryGroup(this, typeId));
-    return &(*m_Groups.rbegin());
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::AddXmlGroup(const SXmlHistoryGroup* pGroup, const char* undoDesc /*= NULL*/)
-{
-    RecordUndoInternal(undoDesc ? undoDesc : "New XML Group added");
-    m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups.push_back(pGroup);
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupAdded, (void*)pGroup);
-}
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RemoveXmlGroup(const SXmlHistoryGroup* pGroup, const char* undoDesc /*= NULL*/)
-{
-    bool unload = m_HistoryInfoMap[ m_CurrentVersion ].CurrGroup == pGroup;
-    RecordUndoInternal(undoDesc ? undoDesc : "XML Group deleted");
-    TXmlHistotyGroupPtrList& list = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups;
-    stl::find_and_erase(list, pGroup);
-    if (unload)
-    {
-        SetActiveGroupInt(NULL);
-    }
-    m_HistoryInfoMap[ m_CurrentVersion ].CurrGroup = m_pNullGroup;
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupRemoved, (void*)pGroup);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::SetActiveGroup(const SXmlHistoryGroup* pGroup, const char* displayName /*= NULL*/, const TGroupIndexMap& groupIndex /*= TGroupIndexMap()*/, bool setExternal /*= false*/)
-{
-    TGroupIndexMap userIndex;
-    const SXmlHistoryGroup* pActiveGroup = GetActiveGroup(userIndex);
-    if (pGroup != pActiveGroup || userIndex != groupIndex || setExternal)
-    {
-        const bool isEx = m_CurrentVersion != m_LatestVersion || setExternal;
-        m_pExActiveGroup = const_cast(pGroup);
-        m_ExCurrentIndex = groupIndex;
-        m_bIsActiveGroupEx = true;
-        SetActiveGroupInt(pGroup, displayName, !isEx, groupIndex);
-        m_bIsActiveGroupEx = isEx;
-    }
-}
-
-void CXmlHistoryManager::SetActiveGroupInt(const SXmlHistoryGroup* pGroup, const char* displayName /*= NULL*/, bool bRecordNullUndo /*= false*/, const TGroupIndexMap& groupIndex /*= TGroupIndexMap()*/)
-{
-    UnloadInt();
-
-    TEventHandlerList eventHandler;
-    AZStd::string undoDesc;
-
-    if (pGroup)
-    {
-        for (TViews::iterator it = m_Views.begin(); it != m_Views.end(); ++it)
-        {
-            IXmlHistoryView* pView = *it;
-
-            std::map userIndexCount;
-
-            for (SXmlHistoryGroup::THistoryList::const_iterator history = pGroup->m_List.begin(); history != pGroup->m_List.end(); ++history)
-            {
-                std::map::iterator it2 = userIndexCount.find((*history)->GetTypeId());
-                if (it2 == userIndexCount.end())
-                {
-                    userIndexCount[ (*history)->GetTypeId() ] = 0;
-                }
-                uint32 userindex = userIndexCount[ (*history)->GetTypeId() ];
-                IXmlUndoEventHandler* pEventHandler = NULL;
-                TGroupIndexMap::const_iterator indexIter = groupIndex.find((*history)->GetTypeId());
-                if (indexIter == groupIndex.end() || indexIter->second == userindex)
-                {
-                    if ((*history)->Exist())
-                    {
-                        if (pView->LoadXml((*history)->GetTypeId(), (*history)->GetCurrentVersion(), pEventHandler, userindex))
-                        {
-                            if (pEventHandler)
-                            {
-                                m_UndoHandlerViewMap[ pEventHandler ] = pView;
-                                RegisterUndoEventHandler(pEventHandler, *history);
-                                eventHandler.push_back(pEventHandler);
-                            }
-                        }
-                    }
-                }
-                if ((*history)->Exist())
-                {
-                    userIndexCount[ (*history)->GetTypeId() ]++;
-                }
-            }
-        }
-        undoDesc = AZStd::string::format("Changed View to \"%s\"", displayName ? displayName : "UNDEFINED");
-    }
-    else
-    {
-        undoDesc = "Unloaded Views";
-        for (TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.begin(); it != m_UndoEventHandlerMap.end(); ++it)
-        {
-            eventHandler.push_back(it->first);
-        }
-        pGroup = m_pNullGroup;
-    }
-
-    if (bRecordNullUndo)
-    {
-        RecordNullUndo(eventHandler, undoDesc.c_str());
-        m_HistoryInfoMap[ m_CurrentVersion ].CurrGroup = pGroup;
-        m_HistoryInfoMap[ m_CurrentVersion ].CurrUserIndex = groupIndex;
-    }
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupChanged);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-const SXmlHistoryGroup* CXmlHistoryManager::GetActiveGroup() const
-{
-    TGroupIndexMap userIndex;
-    return GetActiveGroup(userIndex);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-const SXmlHistoryGroup* CXmlHistoryManager::GetActiveGroup(TGroupIndexMap& currUserIndex /*out*/) const
-{
-    if (m_bIsActiveGroupEx)
-    {
-        currUserIndex = m_ExCurrentIndex;
-        return m_pExActiveGroup;
-    }
-
-    int currVersion = m_CurrentVersion;
-    do
-    {
-        THistoryInfoMap::const_iterator it = m_HistoryInfoMap.find(currVersion);
-        if (it != m_HistoryInfoMap.end())
-        {
-            const SXmlHistoryGroup* pGroup = it->second.CurrGroup;
-            if (it != m_HistoryInfoMap.end() && pGroup)
-            {
-                currUserIndex = it->second.CurrUserIndex;
-                return pGroup == m_pNullGroup ? NULL : pGroup;
-            }
-        }
-        currVersion--;
-    } while (currVersion >= 0);
-    return NULL;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-SXmlHistory* CXmlHistoryManager::CreateXmlHistory(uint32 typeId, const XmlNodeRef& xmlBaseVersion)
-{
-    m_XmlHistoryList.push_back(SXmlHistory(this, xmlBaseVersion, typeId));
-    return &(*m_XmlHistoryList.rbegin());
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::DeleteXmlHistory(const SXmlHistory* pXmlHistry)
-{
-    for (TXmlHistoryList::iterator it = m_XmlHistoryList.begin(); it != m_XmlHistoryList.end(); ++it)
-    {
-        if (&(*it) == pXmlHistry)
-        {
-            m_XmlHistoryList.erase(it);
-            return;
-        }
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::UnloadInt()
-{
-    for (TViews::iterator it = m_Views.begin(); it != m_Views.end(); ++it)
-    {
-        IXmlHistoryView* pView = *it;
-        pView->UnloadXml(-1);
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-namespace
-{
-    template< class T >
-    void ClearAfterVersion(T& container, int version)
-    {
-        auto foundit = container.end();
-        do
-        {
-            auto it = container.find(version);
-            if (it != container.end())
-            {
-                foundit = it;
-                break;
-            }
-            version--;
-        } while (version >= 0);
-        if (foundit != container.end())
-        {
-            for (auto it = ++foundit; it != container.end(); )
-            {
-                container.erase(it++);
-            }
-        }
-    }
-}
-
-void CXmlHistoryManager::ClearRedo()
-{
-    ClearAfterVersion(m_HistoryInfoMap, m_CurrentVersion);
-    for (TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.begin(); it != m_UndoEventHandlerMap.end(); ++it)
-    {
-        ClearAfterVersion(it->second.HistoryData, m_CurrentVersion);
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::DeleteAll()
-{
-    ClearHistory();
-    m_Groups.clear();
-    m_UndoEventHandlerMap.clear();
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryDeleted);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::FlagHistoryAsSaved()
-{
-    for (TXmlHistoryList::iterator it = m_XmlHistoryList.begin(); it != m_XmlHistoryList.end(); ++it)
-    {
-        it->FlagAsSaved();
-    }
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistorySaved);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RecordNullUndo(const TEventHandlerList& eventHandler, const char* desc, bool isNull /*= true*/)
-{
-    TXmlHistotyGroupPtrList activeGroups = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups;
-
-    // if current version is already null undo, overwrite it instead of create a new version
-    if (m_HistoryInfoMap[ m_CurrentVersion ].IsNullUndo && isNull)
-    {
-        assert(m_CurrentVersion);
-        m_CurrentVersion--;
-    }
-
-    ClearRedo();
-    IncrementVersion();
-
-    for (TEventHandlerList::const_iterator it = eventHandler.begin(); it != eventHandler.end(); ++it)
-    {
-        SXmlHistory* pChangedXml = m_UndoEventHandlerMap[ *it ].CurrentData;
-        m_UndoEventHandlerMap[ *it ].HistoryData[ m_CurrentVersion ] = pChangedXml;
-    }
-    m_HistoryInfoMap[ m_CurrentVersion ].HistoryDescription = desc;
-    m_HistoryInfoMap[ m_CurrentVersion ].IsNullUndo = isNull;
-    m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups = activeGroups;
-    m_HistoryInfoMap[ m_CurrentVersion ].HistoryInvalidated = false;
-    NotifyUndoEventListener(IXmlHistoryEventListener::eHET_VersionAdded);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::ReloadCurrentVersion(const SXmlHistoryGroup* pPrevGroup, int prevVersion)
-{
-    m_bIsActiveGroupEx = false;
-    const SXmlHistoryGroup* pActiveGroup = GetActiveGroup();
-
-    bool bInvalidated = false;
-    int start = min(prevVersion, m_CurrentVersion);
-    int end = max(prevVersion, m_CurrentVersion);
-    for (int i = start; i <= end; ++i)
-    {
-        if (m_HistoryInfoMap[i].HistoryInvalidated)
-        {
-            bInvalidated = true;
-            break;
-        }
-    }
-
-    if (!bInvalidated && pPrevGroup == pActiveGroup)
-    {
-        for (TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.begin(); it != m_UndoEventHandlerMap.end(); ++it)
-        {
-            IXmlUndoEventHandler* pEventHandler = it->first;
-            if (!IsEventHandlerValid(pEventHandler))
-            {
-                assert(false);
-                continue;
-            }
-            SXmlHistory* pXmlHistory = GetLatestHistory(m_UndoEventHandlerMap[ pEventHandler ]);  /*m_UndoEventHandlerMap[ pEventHandler ].HistoryData[ m_CurrentVersion ];*/
-            if (pXmlHistory)
-            {
-                if (pXmlHistory->Exist())
-                {
-                    pEventHandler->ReloadFromXml(pXmlHistory->GetCurrentVersion());
-                }
-            }
-        }
-        NotifyUndoEventListener(IXmlHistoryEventListener::eHET_VersionChanged);
-    }
-    else
-    {
-        SetActiveGroupInt(pActiveGroup);
-    }
-
-    if (bInvalidated)
-    {
-        NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryInvalidate);
-    }
-
-    TXmlHistotyGroupPtrList oldActiveGroups = m_HistoryInfoMap[ prevVersion ].ActiveGroups;
-    TXmlHistotyGroupPtrList newActiveGroups = m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups;
-
-    RemoveListFromList(newActiveGroups, oldActiveGroups);
-    RemoveListFromList(oldActiveGroups, m_HistoryInfoMap[ m_CurrentVersion ].ActiveGroups);
-
-    for (TXmlHistotyGroupPtrList::iterator it = newActiveGroups.begin(); it != newActiveGroups.end(); ++it)
-    {
-        NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupAdded, (void*) *it);
-    }
-
-    for (TXmlHistotyGroupPtrList::iterator it = oldActiveGroups.begin(); it != oldActiveGroups.end(); ++it)
-    {
-        NotifyUndoEventListener(IXmlHistoryEventListener::eHET_HistoryGroupRemoved, (void*) *it);
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RemoveListFromList(TXmlHistotyGroupPtrList& list, const TXmlHistotyGroupPtrList& removeList)
-{
-    for (TXmlHistotyGroupPtrList::const_iterator rit = removeList.begin(); rit != removeList.end(); ++rit)
-    {
-        for (TXmlHistotyGroupPtrList::iterator it = list.begin(); it != list.end(); ++it)
-        {
-            if (*it == *rit)
-            {
-                list.erase(it);
-                break;
-            }
-        }
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-SXmlHistory* CXmlHistoryManager::GetLatestHistory(SUndoEventHandlerData& eventHandlerData)
-{
-    int currVersion = m_CurrentVersion;
-    do
-    {
-        THistoryVersionMap::iterator it = eventHandlerData.HistoryData.find(currVersion);
-        if (it != eventHandlerData.HistoryData.end())
-        {
-            return it->second;
-        }
-        currVersion--;
-    } while (currVersion >= 0);
-    return NULL;
-}
-
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::NotifyUndoEventListener(IXmlHistoryEventListener::EHistoryEventType event, void* pData)
-{
-    if (m_pExclusiveListener)
-    {
-        m_pExclusiveListener->OnEvent(event, pData);
-    }
-    else
-    {
-        for (TEventListener::iterator it = m_EventListener.begin(); it != m_EventListener.end(); ++it)
-        {
-            (*it)->OnEvent(event, pData);
-        }
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-int CXmlHistoryManager::IncrementVersion([[maybe_unused]] SXmlHistory* pXmlHistry)
-{
-    for (TXmlHistoryList::iterator it = m_XmlHistoryList.begin(); it != m_XmlHistoryList.end(); ++it)
-    {
-        it->ClearRedo();
-    }
-    return IncrementVersion();
-}
-
-/////////////////////////////////////////////////////////////////////////////
-int CXmlHistoryManager::IncrementVersion()
-{
-    m_CurrentVersion++;
-    m_LatestVersion = m_CurrentVersion;
-    return m_CurrentVersion;
-}
-
-////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RegisterUndoEventHandler(IXmlUndoEventHandler* pEventHandler, SXmlHistory* pXmlData)
-{
-    m_UndoEventHandlerMap[ pEventHandler ].CurrentData = pXmlData;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::UnregisterUndoEventHandler(IXmlUndoEventHandler* pEventHandler)
-{
-    TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.find(pEventHandler);
-    if (it != m_UndoEventHandlerMap.end())
-    {
-        m_UndoEventHandlerMap.erase(it);
-    }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-void CXmlHistoryManager::RecordUndoInternal(const char* desc)
-{
-    TEventHandlerList eventHandler;
-    for (TUndoEventHandlerMap::iterator it = m_UndoEventHandlerMap.begin(); it != m_UndoEventHandlerMap.end(); ++it)
-    {
-        eventHandler.push_back(it->first);
-    }
-    RecordNullUndo(eventHandler, desc, false);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-bool CXmlHistoryManager::IsEventHandlerValid(IXmlUndoEventHandler* pEventHandler)
-{
-    for (TInvalidUndoEventListener::iterator it = m_InvalidHandlerMap.begin(); it != m_InvalidHandlerMap.end(); ++it)
-    {
-        if (it->second == pEventHandler)
-        {
-            return false;
-        }
-    }
-    return true;
-}
diff --git a/Code/Editor/Util/XmlHistoryManager.h b/Code/Editor/Util/XmlHistoryManager.h
deleted file mode 100644
index 176f0a8d83..0000000000
--- a/Code/Editor/Util/XmlHistoryManager.h
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#ifndef CRYINCLUDE_EDITOR_UTIL_XMLHISTORYMANAGER_H
-#define CRYINCLUDE_EDITOR_UTIL_XMLHISTORYMANAGER_H
-#pragma once
-
-
-#include "IXmlHistoryManager.h"
-
-class CXmlHistoryManager;
-
-struct SXmlHistory
-{
-public:
-    SXmlHistory(CXmlHistoryManager* pManager, const XmlNodeRef& xmlBaseVersion, uint32 typeId);
-
-    void AddToHistory(const XmlNodeRef& newXmlVersion);
-
-    const XmlNodeRef& Undo(bool* bVersionExist = NULL);
-    const XmlNodeRef& Redo();
-    const XmlNodeRef& GetCurrentVersion(bool* bVersionExist = NULL, int* iVersionNumber = NULL) const;
-    bool IsModified() const;
-    uint32 GetTypeId() const {return m_typeId; }
-    void FlagAsDeleted();
-    void FlagAsSaved();
-    bool Exist() const;
-
-private:
-    friend class CXmlHistoryManager;
-
-    void ClearRedo();
-    void ClearHistory(bool flagAsSaved);
-
-private:
-    CXmlHistoryManager* m_pManager;
-    uint32 m_typeId;
-    int m_DeletedVersion;
-    int m_SavedVersion;
-
-    typedef std::map< int, XmlNodeRef > TXmlVersionMap;
-    TXmlVersionMap m_xmlVersionList;
-};
-
-
-struct SXmlHistoryGroup
-{
-    SXmlHistoryGroup(CXmlHistoryManager* pManager, uint32 typeId);
-
-    SXmlHistory* GetHistory(int index) const;
-    int GetHistoryCount() const;
-
-    SXmlHistory* GetHistoryByTypeId(uint32 typeId, int index = 0) const;
-    int GetHistoryCountByTypeId(uint32 typeId) const;
-
-    int CreateXmlHistory(uint32 typeId, const XmlNodeRef& xmlBaseVersion);
-    uint32 GetTypeId() const {return m_typeId; }
-
-    int GetHistoryIndex(const SXmlHistory* pHistory) const;
-
-private:
-    friend class CXmlHistoryManager;
-    CXmlHistoryManager* m_pManager;
-    uint32 m_typeId;
-
-    typedef std::list< SXmlHistory* > THistoryList;
-    THistoryList m_List;
-};
-
-typedef std::map TGroupIndexMap;
-
-
-class CXmlHistoryManager
-    : public IXmlHistoryManager
-    , public IXmlUndoEventHandler
-{
-public:
-    CXmlHistoryManager();
-    ~CXmlHistoryManager();
-
-    // Undo/Redo
-    bool Undo();
-    bool Redo();
-    bool Goto(int historyNum);
-    void RecordUndo(IXmlUndoEventHandler* pEventHandler, const char* desc);
-    void UndoEventHandlerDestroyed(IXmlUndoEventHandler* pEventHandler, uint32 typeId = 0, bool destoryForever = false);
-    void RestoreUndoEventHandler(IXmlUndoEventHandler* pEventHandler, uint32 typeId);
-
-    void PrepareForNextVersion();
-    void RecordNextVersion(SXmlHistory* pHistory, XmlNodeRef newData, const char* undoDesc = NULL);
-    bool IsPreparedForNextVersion() const {return m_RecordNextVersion; }
-
-    void RegisterEventListener(IXmlHistoryEventListener* pEventListener);
-    void UnregisterEventListener(IXmlHistoryEventListener* pEventListener);
-    void SetExclusiveListener(IXmlHistoryEventListener* pEventListener) { m_pExclusiveListener = pEventListener; }
-
-    // History
-    void ClearHistory(bool flagAsSaved = false);
-    int GetVersionCount() const { return m_LatestVersion; }
-    const AZStd::string& GetVersionDesc(int number) const;
-    int GetCurrentVersionNumber() const { return m_CurrentVersion; }
-
-    // Views
-    void RegisterView(IXmlHistoryView* pView);
-    void UnregisterView(IXmlHistoryView* pView);
-
-    // Xml History Groups
-    SXmlHistoryGroup* CreateXmlGroup(uint32 typeId);
-    void SetActiveGroup(const SXmlHistoryGroup* pGroup, const char* displayName = NULL, const TGroupIndexMap& groupIndex = TGroupIndexMap(), bool setExternal = false);
-    const SXmlHistoryGroup* GetActiveGroup() const;
-    const SXmlHistoryGroup* GetActiveGroup(TGroupIndexMap& currUserIndex /*out*/) const;
-    void AddXmlGroup(const SXmlHistoryGroup* pGroup, const char* undoDesc = NULL);
-    void RemoveXmlGroup(const SXmlHistoryGroup* pGroup, const char* undoDesc = NULL);
-
-    void DeleteAll();
-
-    void FlagHistoryAsSaved();
-
-    virtual bool SaveToXml(XmlNodeRef& xmlNode);
-    virtual bool LoadFromXml([[maybe_unused]] const XmlNodeRef& xmlNode) { return false; };
-    virtual bool ReloadFromXml([[maybe_unused]] const XmlNodeRef& xmlNode) { return false; };
-
-private:
-    typedef std::list< SXmlHistory > TXmlHistoryList;
-    TXmlHistoryList m_XmlHistoryList;
-    int m_CurrentVersion;
-    int m_LatestVersion;
-    SXmlHistoryGroup* m_pNullGroup; // hack for unload view ...
-    XmlNodeRef m_newHistoryData;
-    bool m_RecordNextVersion;
-    bool m_bIsActiveGroupEx;
-    SXmlHistoryGroup* m_pExActiveGroup;
-    TGroupIndexMap m_ExCurrentIndex;
-
-    typedef std::list< SXmlHistoryGroup > TXmlHistotyGroupList;
-    TXmlHistotyGroupList m_Groups;
-
-    // event listener
-    typedef std::list< IXmlHistoryEventListener* > TEventListener;
-    TEventListener m_EventListener;
-    IXmlHistoryEventListener* m_pExclusiveListener;
-
-    // views
-    typedef std::list< IXmlHistoryView* > TViews;
-    TViews m_Views;
-
-    typedef std::list< const SXmlHistoryGroup* > TXmlHistotyGroupPtrList;
-    // history
-    struct SHistoryInfo
-    {
-        SHistoryInfo()
-            : IsNullUndo(false)
-            , CurrGroup(NULL)
-            , HistoryInvalidated(false) {}
-
-        const SXmlHistoryGroup* CurrGroup;
-        TGroupIndexMap CurrUserIndex;
-        AZStd::string HistoryDescription;
-        bool IsNullUndo;
-        bool HistoryInvalidated;
-        TXmlHistotyGroupPtrList ActiveGroups;
-    };
-    typedef std::map< int, SHistoryInfo > THistoryInfoMap;
-    THistoryInfoMap m_HistoryInfoMap;
-
-    // undo event handler
-    typedef std::map< int, SXmlHistory* > THistoryVersionMap;
-    struct SUndoEventHandlerData
-    {
-        SUndoEventHandlerData()
-            : CurrentData(NULL) {}
-
-        SXmlHistory* CurrentData;
-        THistoryVersionMap HistoryData;
-    };
-    typedef std::map< IXmlUndoEventHandler*, SUndoEventHandlerData > TUndoEventHandlerMap;
-    TUndoEventHandlerMap m_UndoEventHandlerMap;
-
-    typedef std::map< IXmlUndoEventHandler*, IXmlHistoryView* > TUndoHandlerViewMap;
-    TUndoHandlerViewMap m_UndoHandlerViewMap;
-
-    typedef std::map< uint32, IXmlUndoEventHandler* > TInvalidUndoEventListener;
-    TInvalidUndoEventListener m_InvalidHandlerMap;
-
-private:
-    friend struct SXmlHistory;
-    friend struct SXmlHistoryGroup;
-
-    int IncrementVersion(SXmlHistory* pXmlHistry);
-    int IncrementVersion();
-    SXmlHistory* CreateXmlHistory(uint32 typeId, const XmlNodeRef& xmlBaseVersion);
-    void DeleteXmlHistory(const SXmlHistory* pXmlHistry);
-
-    void RegisterUndoEventHandler(IXmlUndoEventHandler* pEventHandler, SXmlHistory* pXmlData);
-    void UnregisterUndoEventHandler(IXmlUndoEventHandler* pEventHandler);
-    typedef std::list< IXmlUndoEventHandler* > TEventHandlerList;
-    void RecordNullUndo(const TEventHandlerList& eventHandler, const char* desc, bool isNull = true);
-    void ReloadCurrentVersion(const SXmlHistoryGroup* pPrevGroup, int prevVersion);
-    SXmlHistory* GetLatestHistory(SUndoEventHandlerData& eventHandlerData);
-    void NotifyUndoEventListener(IXmlHistoryEventListener::EHistoryEventType event, void* pData = NULL);
-
-    void SetActiveGroupInt(const SXmlHistoryGroup* pGroup, const char* displayName = NULL, bool bRecordNullUndo = false, const TGroupIndexMap& groupIndex = TGroupIndexMap());
-    void UnloadInt();
-    void ClearRedo();
-
-    void RecordUndoInternal(const char* desc);
-    void RemoveListFromList(TXmlHistotyGroupPtrList& list, const TXmlHistotyGroupPtrList& removeList);
-
-    bool IsEventHandlerValid(IXmlUndoEventHandler* pEventHandler);
-};
-
-#endif // CRYINCLUDE_EDITOR_UTIL_XMLHISTORYMANAGER_H
diff --git a/Code/Editor/editor_lib_files.cmake b/Code/Editor/editor_lib_files.cmake
index 386b495faa..7f59eed7ae 100644
--- a/Code/Editor/editor_lib_files.cmake
+++ b/Code/Editor/editor_lib_files.cmake
@@ -498,9 +498,7 @@ set(FILES
     UndoViewPosition.h
     UndoViewRotation.h
     Util/GeometryUtil.h
-    Util/IXmlHistoryManager.h
     Util/KDTree.h
-    Util/XmlHistoryManager.h
     WipFeaturesDlg.h
     WipFeaturesDlg.ui
     WipFeaturesDlg.qrc
@@ -737,14 +735,12 @@ set(FILES
     Util/PredefinedAspectRatios.h
     Util/StringHelpers.cpp
     Util/StringHelpers.h
-    Util/StringNoCasePredicate.h
     Util/TRefCountBase.h
     Util/Triangulate.cpp
     Util/Triangulate.h
     Util/Util.h
     Util/XmlArchive.cpp
     Util/XmlArchive.h
-    Util/XmlHistoryManager.cpp
     Util/XmlTemplate.cpp
     Util/XmlTemplate.h
     Util/bitarray.h

From 0545ce4f59c67fdfb094d5610b66165eacdfe78f Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 12:46:50 -0700
Subject: [PATCH 055/205] More PR comments/fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/ConfigGroup.cpp  | 4 ++--
 Code/Editor/GameExporter.cpp | 8 ++++----
 2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/Code/Editor/ConfigGroup.cpp b/Code/Editor/ConfigGroup.cpp
index 04c92ff155..d65cbf2c3b 100644
--- a/Code/Editor/ConfigGroup.cpp
+++ b/Code/Editor/ConfigGroup.cpp
@@ -127,7 +127,7 @@ namespace Config
 
                     case IConfigVar::eType_STRING:
                     {
-                        AZStd::string currentValue = 0;
+                        AZStd::string currentValue;
                         var->Get(¤tValue);
                         node->setAttr(szName, currentValue.c_str());
                         break;
@@ -186,7 +186,7 @@ namespace Config
 
                 case IConfigVar::eType_STRING:
                 {
-                    AZStd::string currentValue = 0;
+                    AZStd::string currentValue;
                     var->GetDefault(¤tValue);
                     QString readValue(currentValue.c_str());
                     if (node->getAttr(szName, readValue))
diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp
index 4c9031f08d..784951cc4d 100644
--- a/Code/Editor/GameExporter.cpp
+++ b/Code/Editor/GameExporter.cpp
@@ -380,12 +380,12 @@ void CGameExporter::ExportFileList(const QString& path, const QString& levelName
     //  that can later be used for map downloads
     AZStd::string newpath;
 
-    QString filename = levelName;
-    AZStd::string mapname = (filename + ".dds").toUtf8().data();
-    AZStd::string metaname = (filename + ".xml").toUtf8().data();
+    AZStd::string filename = levelName.toUtf8().data();
+    AZStd::string mapname = (filename + ".dds");
+    AZStd::string metaname = (filename + ".xml");
 
     XmlNodeRef rootNode = gEnv->pSystem->CreateXmlNode("download");
-    rootNode->setAttr("name", filename.toUtf8().data());
+    rootNode->setAttr("name", filename.c_str());
     rootNode->setAttr("type", "Map");
     XmlNodeRef indexNode = rootNode->newChild("index");
     if (indexNode)

From aa124347284cfc3b36902719a74d9808cc8948bc Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 12:47:36 -0700
Subject: [PATCH 056/205] removing some dead code, commented code referring old
 types, static AZStd::strings

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/CryEdit.cpp                       |  5 ----
 Code/Editor/CryEditPy.cpp                     |  4 ++--
 Code/Editor/GenericSelectItemDialog.cpp       | 14 -----------
 Code/Editor/LogFile.cpp                       |  3 ---
 Code/Editor/QtUtil.h                          |  1 -
 Code/Editor/Settings.cpp                      | 16 -------------
 Code/Editor/Util/EditorUtils.cpp              | 24 -------------------
 Code/Editor/Util/PathUtil.cpp                 |  4 ++--
 Code/Legacy/CryCommon/CryTypeInfo.cpp         |  3 ++-
 Code/Legacy/CrySystem/SystemWin32.cpp         | 21 +---------------
 .../CrySystem/XML/SerializeXMLReader.cpp      |  9 ++++---
 .../Legacy/CrySystem/XML/SerializeXMLReader.h |  2 +-
 .../CrySystem/XML/SerializeXMLWriter.cpp      | 18 +++++++-------
 .../Legacy/CrySystem/XML/SerializeXMLWriter.h |  8 +++----
 Code/Legacy/CrySystem/XML/XMLBinaryNode.h     |  2 --
 .../DataTypes/Rules/IMeshAdvancedRule.h       |  3 ++-
 .../SceneData/GraphData/MaterialData.cpp      |  8 +++----
 .../SceneData/GraphData/MaterialData.h        |  8 +++----
 .../Code/Source/Editor/EditorCommon.cpp       |  8 +++----
 .../Source/OpenGLRender/GLWidget.cpp          |  3 +--
 20 files changed, 39 insertions(+), 125 deletions(-)

diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp
index b69bfa78f3..3673367c12 100644
--- a/Code/Editor/CryEdit.cpp
+++ b/Code/Editor/CryEdit.cpp
@@ -1883,11 +1883,6 @@ void CCryEditApp::UnregisterEventLoopHook(IEventLoopHook* pHookToRemove)
 //////////////////////////////////////////////////////////////////////////
 void CCryEditApp::LoadFile(QString fileName)
 {
-    //CEditCommandLineInfo cmdLine;
-    //ProcessCommandLine(cmdinfo);
-
-    //bool bBuilding = false;
-    //CString file = cmdLine.SpanExcluding()
     if (GetIEditor()->GetViewManager()->GetViewCount() == 0)
     {
         return;
diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp
index 6abaf933fe..7e07d5553d 100644
--- a/Code/Editor/CryEditPy.cpp
+++ b/Code/Editor/CryEditPy.cpp
@@ -210,7 +210,7 @@ namespace
     const char* PyGetCurrentLevelName()
     {
         // Using static member to capture temporary data
-        static AZStd::string tempLevelName;
+        static AZStd::fixed_string tempLevelName;
         tempLevelName = GetIEditor()->GetGameEngine()->GetLevelName().toUtf8().data();
         return tempLevelName.c_str();
     }
@@ -218,7 +218,7 @@ namespace
     const char* PyGetCurrentLevelPath()
     {
         // Using static member to capture temporary data
-        static AZStd::string tempLevelPath;
+        static AZStd::fixed_string tempLevelPath;
         tempLevelPath = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data();
         return tempLevelPath.c_str();
     }
diff --git a/Code/Editor/GenericSelectItemDialog.cpp b/Code/Editor/GenericSelectItemDialog.cpp
index ef109336ef..59c7986a68 100644
--- a/Code/Editor/GenericSelectItemDialog.cpp
+++ b/Code/Editor/GenericSelectItemDialog.cpp
@@ -91,20 +91,6 @@ void CGenericSelectItemDialog::ReloadTree()
 
     QTreeWidgetItem* hSelected = nullptr;
 
-    /*
-    std::vector::const_iterator iter = m_items.begin();
-    while (iter != m_items.end())
-    {
-        const CString& itemName = *iter;
-        HTREEITEM hItem = m_tree.InsertItem(itemName, 0, 0, TVI_ROOT, TVI_SORT);
-        if (!m_preselect.IsEmpty() && m_preselect.CompareNoCase(itemName) == 0)
-        {
-            hSelected = hItem;
-        }
-        ++iter;
-    }
-    */
-
     std::map items;
 
     QRegularExpression sep(QStringLiteral("[\\/.") + m_treeSeparator + QStringLiteral("]+"));
diff --git a/Code/Editor/LogFile.cpp b/Code/Editor/LogFile.cpp
index 76c6f34181..56e91a6806 100644
--- a/Code/Editor/LogFile.cpp
+++ b/Code/Editor/LogFile.cpp
@@ -572,9 +572,6 @@ void CLogFile::OnWriteToConsole(const char* sText, bool bNewLine)
             }
             if (bNewLine)
             {
-                //str = CString("\r\n") + str.TrimLeft();
-                //str = CString("\r\n") + str;
-                //str = CString("\r") + str;
                 str = QString("\r\n") + str;
                 str = str.trimmed();
             }
diff --git a/Code/Editor/QtUtil.h b/Code/Editor/QtUtil.h
index a9aaadc491..380f4dfa4a 100644
--- a/Code/Editor/QtUtil.h
+++ b/Code/Editor/QtUtil.h
@@ -34,7 +34,6 @@ public:
 
 namespace QtUtil
 {
-    // Replacement for CString::trimRight()
     inline QString trimRight(const QString& str)
     {
         // We prepend a char, so that the left doesn't get trimmed, then we remove it after trimming
diff --git a/Code/Editor/Settings.cpp b/Code/Editor/Settings.cpp
index 8f86c74b25..ae4fa75d41 100644
--- a/Code/Editor/Settings.cpp
+++ b/Code/Editor/Settings.cpp
@@ -656,22 +656,6 @@ void SEditorSettings::Save()
     //////////////////////////////////////////////////////////////////////////
     SaveValue("Settings\\Slices", "DynamicByDefault", sliceSettings.dynamicByDefault);
 
-    /*
-    //////////////////////////////////////////////////////////////////////////
-    // Save paths.
-    //////////////////////////////////////////////////////////////////////////
-    for (int id = 0; id < EDITOR_PATH_LAST; id++)
-    {
-        for (int i = 0; i < searchPaths[id].size(); i++)
-        {
-            CString path = searchPaths[id][i];
-            CString key;
-            key.Format( "Paths","Path_%.2d_%.2d",id,i );
-            SaveValue( "Paths",key,path );
-        }
-    }
-    */
-
     s_editorSettings()->sync();
 
     // --- Settings Registry values
diff --git a/Code/Editor/Util/EditorUtils.cpp b/Code/Editor/Util/EditorUtils.cpp
index 8f56e4d956..9f42a5da83 100644
--- a/Code/Editor/Util/EditorUtils.cpp
+++ b/Code/Editor/Util/EditorUtils.cpp
@@ -30,30 +30,6 @@ void HeapCheck::Check([[maybe_unused]] const char* file, [[maybe_unused]] int li
     _ASSERTE(_CrtCheckMemory());
 #endif
 
-    /*
-   int heapstatus = _heapchk();
-   switch( heapstatus )
-   {
-   case _HEAPOK:
-      break;
-   case _HEAPEMPTY:
-      break;
-   case _HEAPBADBEGIN:
-            {
-                CString str;
-                str.Format( "Bad Start of Heap, at file %s line:%d",file,line );
-                MessageBox( NULL,str,"Heap Check",MB_OK );
-            }
-      break;
-   case _HEAPBADNODE:
-            {
-                CString str;
-                str.Format( "Bad Node in Heap, at file %s line:%d",file,line );
-                MessageBox( NULL,str,"Heap Check",MB_OK );
-            }
-      break;
-   }
-     */
     #endif
 }
 
diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp
index 2f99f42188..22c638e289 100644
--- a/Code/Editor/Util/PathUtil.cpp
+++ b/Code/Editor/Util/PathUtil.cpp
@@ -245,8 +245,8 @@ namespace Path
     /// Get the data folder
     AZStd::string GetEditingGameDataFolder()
     {
-        static AZStd::string s_currentModName;
-        // query the editor root.  The bus exists in case we want tools to be able to override this.
+        // Define here the mod name
+        static AZStd::fixed_string s_currentModName;
 
         if (s_currentModName.empty())
         {
diff --git a/Code/Legacy/CryCommon/CryTypeInfo.cpp b/Code/Legacy/CryCommon/CryTypeInfo.cpp
index ffadc732b0..5f0cb47b63 100644
--- a/Code/Legacy/CryCommon/CryTypeInfo.cpp
+++ b/Code/Legacy/CryCommon/CryTypeInfo.cpp
@@ -131,7 +131,8 @@ const CTypeInfo&PtrTypeInfo()
 // bool
 AZStd::string ToString(bool const& val)
 {
-    static AZStd::string sTrue = "true", sFalse = "false";
+    static AZStd::fixed_string sTrue = "true";
+    static AZStd::fixed_string sFalse = "false";
     return val ? sTrue : sFalse;
 }
 
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index 66be2a2ca5..b114c9bf12 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -173,7 +173,7 @@ int CSystem::GetApplicationInstance()
         AZStd::wstring suffix;
         for (int instance = 0;; ++instance)
         {
-            suffix = AZStd::wstring::format(L"LumberyardApplication(%d)", instance);
+            suffix = AZStd::wstring::format(L"O3DEApplication(%d)", instance);
 
             CreateMutexW(NULL, TRUE, suffix.c_str());
             // search for duplicates
@@ -222,25 +222,6 @@ struct CryDbgModule
 };
 
 #ifdef WIN32
-//////////////////////////////////////////////////////////////////////////
-class CStringOrder
-{
-public:
-    bool operator () (const char* szLeft, const char* szRight) const {return azstricmp(szLeft, szRight) < 0; }
-};
-typedef std::map StringToSizeMap;
-void AddSize (StringToSizeMap& mapSS, const char* szString, unsigned nSize)
-{
-    StringToSizeMap::iterator it = mapSS.find (szString);
-    if (it == mapSS.end())
-    {
-        mapSS.insert (StringToSizeMap::value_type(szString, nSize));
-    }
-    else
-    {
-        it->second += nSize;
-    }
-}
 
 //////////////////////////////////////////////////////////////////////////
 const char* GetModuleGroup (const char* szString)
diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp
index 55fab84286..e74b457191 100644
--- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp
+++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp
@@ -15,7 +15,7 @@
 #define TAG_SCRIPT_TYPE "t"
 #define TAG_SCRIPT_NAME "n"
 
-//#define LOG_SERIALIZE_STACK(tag,szName) CryLogAlways( "<%s> %s/%s",tag,GetStackInfo(),szName );
+//#define LOG_SERIALIZE_STACK(tag,szName) CryLogAlways( "<%s> %s/%s",tag,GetStackInfo().c_str(), szName);
 #define LOG_SERIALIZE_STACK(tag, szName)
 
 CSerializeXMLReaderImpl::CSerializeXMLReaderImpl(const XmlNodeRef& nodeRef)
@@ -175,10 +175,9 @@ void CSerializeXMLReaderImpl::EndGroup()
 }
 
 //////////////////////////////////////////////////////////////////////////
-const char* CSerializeXMLReaderImpl::GetStackInfo() const
+AZStd::string CSerializeXMLReaderImpl::GetStackInfo() const
 {
-    static AZStd::string str;
-    str.assign("");
+    AZStd::string str;
     for (int i = 0; i < (int)m_nodeStack.size(); i++)
     {
         const char* name = m_nodeStack[i].m_node->getAttr(TAG_SCRIPT_NAME);
@@ -195,7 +194,7 @@ const char* CSerializeXMLReaderImpl::GetStackInfo() const
             str += "/";
         }
     }
-    return str.c_str();
+    return str;
 }
 
 void CSerializeXMLReaderImpl::GetMemoryUsage(ICrySizer* pSizer) const
diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h
index 177db0ffaa..f87350d3fe 100644
--- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h
+++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h
@@ -88,7 +88,7 @@ public:
     void BeginGroup(const char* szName);
     bool BeginOptionalGroup(const char* szName, bool condition);
     void EndGroup();
-    const char* GetStackInfo() const;
+    AZStd::string GetStackInfo() const;
 
     void GetMemoryUsage(ICrySizer* pSizer) const;
 
diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
index 26007eb229..ce3fbcc2b1 100644
--- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
+++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp
@@ -64,14 +64,14 @@ void CSerializeXMLWriterImpl::BeginGroup(const char* szName)
     if (strchr(szName, ' ') != 0)
     {
         assert(0 && "Spaces in group name not supported");
-        CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Spaces in group name not supported: %s/%s", GetStackInfo(), szName);
+        CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Spaces in group name not supported: %s/%s", GetStackInfo().c_str(), szName);
     }
     XmlNodeRef node = CreateNodeNamed(szName);
     CurNode()->addChild(node);
     m_nodeStack.push_back(node);
     if (m_nodeStack.size() > MAX_NODE_STACK_DEPTH)
     {
-        CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Too Deep Node Stack:\r\n%s", GetStackInfo());
+        CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Too Deep Node Stack:\r\n%s", GetStackInfo().c_str());
     }
 }
 
@@ -112,10 +112,9 @@ void CSerializeXMLWriterImpl::GetMemoryUsage(ICrySizer* pSizer) const
 }
 
 //////////////////////////////////////////////////////////////////////////
-const char* CSerializeXMLWriterImpl::GetStackInfo() const
+AZStd::string CSerializeXMLWriterImpl::GetStackInfo() const
 {
-    static AZStd::string str;
-    str.assign("");
+    AZStd::string str;
     for (int i = 0; i < (int)m_nodeStack.size(); i++)
     {
         const char* name = m_nodeStack[i]->getAttr(TAG_SCRIPT_NAME);
@@ -132,14 +131,13 @@ const char* CSerializeXMLWriterImpl::GetStackInfo() const
             str += "/";
         }
     }
-    return str.c_str();
+    return str;
 }
 
 //////////////////////////////////////////////////////////////////////////
-const char* CSerializeXMLWriterImpl::GetLuaStackInfo() const
+AZStd::string CSerializeXMLWriterImpl::GetLuaStackInfo() const
 {
-    static AZStd::string str;
-    str.assign("");
+    AZStd::string str;
     for (int i = 0; i < (int)m_luaSaveStack.size(); i++)
     {
         const char* name = m_luaSaveStack[i];
@@ -149,5 +147,5 @@ const char* CSerializeXMLWriterImpl::GetLuaStackInfo() const
             str += ".";
         }
     }
-    return str.c_str();
+    return str;
 }
diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
index 41dbe3dd7b..5f3e9f2c53 100644
--- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
+++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h
@@ -77,7 +77,7 @@ private:
         if (strchr(name, ' ') != 0)
         {
             assert(0 && "Spaces in Value name not supported");
-            CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Spaces in Value name not supported: %s in Group %s", name, GetStackInfo());
+            CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Spaces in Value name not supported: %s in Group %s", name, GetStackInfo().c_str());
             return;
         }
         if (GetISystem()->IsDevMode() && CurNode())
@@ -86,7 +86,7 @@ private:
             if (CurNode()->haveAttr(name))
             {
                 assert(0);
-                CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Duplicate tag Value( \"%s\" ) in Group %s", name, GetStackInfo());
+                CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "!Duplicate tag Value( \"%s\" ) in Group %s", name, GetStackInfo().c_str());
             }
         }
 
@@ -115,8 +115,8 @@ private:
     }
 
     // Used for printing currebnt stack info for warnings.
-    const char* GetStackInfo() const;
-    const char* GetLuaStackInfo() const;
+    AZStd::string GetStackInfo() const;
+    AZStd::string GetLuaStackInfo() const;
 
     //////////////////////////////////////////////////////////////////////////
     // Check For Defaults.
diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryNode.h b/Code/Legacy/CrySystem/XML/XMLBinaryNode.h
index cd9ce04e6c..34e0ca22ce 100644
--- a/Code/Legacy/CrySystem/XML/XMLBinaryNode.h
+++ b/Code/Legacy/CrySystem/XML/XMLBinaryNode.h
@@ -189,8 +189,6 @@ public:
     bool getAttr(const char* key, Vec3d& value) const;
     bool getAttr(const char* key, Quat& value) const;
     bool getAttr(const char* key, ColorB& value) const;
-    //  bool getAttr( const char *key,CString &value ) const { XmlString v; if (getAttr(key,v)) { value = (const char*)v; return true; } else return false; }
-
 
 private:
     //////////////////////////////////////////////////////////////////////////
diff --git a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
index d3b31913dd..b759fea158 100644
--- a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
+++ b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
@@ -18,7 +18,8 @@ namespace AZ
     {
         namespace DataTypes
         {
-            const static AZStd::string s_advancedDisabledString = "Disabled";
+            const static AZStd::fixed_string s_advancedDisabledString = "Disabled";
+
             class IMeshAdvancedRule
                 : public IRule
             {
diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp
index cf0f0a6f56..e41e39dd0a 100644
--- a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp
+++ b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp
@@ -18,10 +18,10 @@ namespace AZ
         {
             namespace DataTypes = AZ::SceneAPI::DataTypes;
 
-            const AZStd::string MaterialData::s_DiffuseMapName = "Diffuse";
-            const AZStd::string MaterialData::s_SpecularMapName = "Specular";
-            const AZStd::string MaterialData::s_BumpMapName = "Bump";
-            const AZStd::string MaterialData::s_emptyString = "";
+            const AZStd::fixed_string<8> MaterialData::s_DiffuseMapName = "Diffuse";
+            const AZStd::fixed_string<9> MaterialData::s_SpecularMapName = "Specular";
+            const AZStd::fixed_string<5> MaterialData::s_BumpMapName = "Bump";
+            const AZStd::fixed_string<1> MaterialData::s_emptyString = "";
 
             MaterialData::MaterialData()
                 : m_isNoDraw(false)
diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h
index 8cc9de8352..8c8f8bd66e 100644
--- a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h
+++ b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h
@@ -96,10 +96,10 @@ namespace AZ
 
                 bool m_isNoDraw;
 
-                const static AZStd::string s_DiffuseMapName;
-                const static AZStd::string s_SpecularMapName;
-                const static AZStd::string s_BumpMapName;
-                const static AZStd::string s_emptyString;
+                const static AZStd::fixed_string<8> s_DiffuseMapName;
+                const static AZStd::fixed_string<9> s_SpecularMapName;
+                const static AZStd::fixed_string<5> s_BumpMapName;
+                const static AZStd::fixed_string<1> s_emptyString;
 
                 // A unique id which is used to identify a material in a fbx. 
                 // This is the same as the ID in the fbx file's FbxNode
diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp
index 9938d55502..8ce8b2d487 100644
--- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp
+++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Editor/EditorCommon.cpp
@@ -57,10 +57,10 @@ namespace ImageProcessingAtomEditor
         static double mb = kb * 1024.0;
         static double gb = mb * 1024.0;
 
-        static AZStd::string byteStr = "B";
-        static AZStd::string kbStr = "KB";
-        static AZStd::string mbStr = "MB";
-        static AZStd::string gbStr = "GB";
+        static AZStd::fixed_string<2> byteStr = "B";
+        static AZStd::fixed_string<3> kbStr = "KB";
+        static AZStd::fixed_string<3> mbStr = "MB";
+        static AZStd::fixed_string<3> gbStr = "GB";
 
 #if AZ_TRAIT_IMAGEPROCESSING_USE_BASE10_BYTE_PREFIX
         kb = 1000.0;
diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.cpp
index 2d3a8b9eda..cfdcd704c5 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.cpp
@@ -284,8 +284,7 @@ namespace EMStudio
                 fpsNumFrames    = 0;
             }
 
-            static AZStd::string perfTempString;
-            perfTempString = AZStd::string::format("%d FPS (%.1f ms)", lastFPS, renderTime);
+            const AZStd::string perfTempString = AZStd::string::format("%d FPS (%.1f ms)", lastFPS, renderTime);
 
             // initialize the painter and get the font metrics
             //painter.setBrush( Qt::NoBrush );

From 0dc829891a29addd0a74f0ee0d46085ebc57f769 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 14:30:04 -0700
Subject: [PATCH 057/205] fixing build

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/Util/PathUtil.cpp                              | 2 +-
 Code/Legacy/CryCommon/CryTypeInfo.cpp                      | 7 ++++---
 .../SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h | 3 ++-
 Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp   | 7 +------
 Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h     | 6 ++----
 5 files changed, 10 insertions(+), 15 deletions(-)

diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp
index 22c638e289..3ca4b6222c 100644
--- a/Code/Editor/Util/PathUtil.cpp
+++ b/Code/Editor/Util/PathUtil.cpp
@@ -254,7 +254,7 @@ namespace Path
         }
         AZStd::string str(GetGameAssetsFolder());
         str += "Mods\\";
-        str += s_currentModName;
+        str += s_currentModName.c_str();
         return str;
     }
 
diff --git a/Code/Legacy/CryCommon/CryTypeInfo.cpp b/Code/Legacy/CryCommon/CryTypeInfo.cpp
index 5f0cb47b63..b1f7f20601 100644
--- a/Code/Legacy/CryCommon/CryTypeInfo.cpp
+++ b/Code/Legacy/CryCommon/CryTypeInfo.cpp
@@ -16,6 +16,7 @@
 #include "CrySizer.h"
 #include "CryEndian.h"
 #include "TypeInfo_impl.h"
+#include 
 
 // Traits
 #if defined(AZ_RESTRICTED_PLATFORM)
@@ -131,9 +132,9 @@ const CTypeInfo&PtrTypeInfo()
 // bool
 AZStd::string ToString(bool const& val)
 {
-    static AZStd::fixed_string sTrue = "true";
-    static AZStd::fixed_string sFalse = "false";
-    return val ? sTrue : sFalse;
+    static AZStd::fixed_string<5> sTrue = "true";
+    static AZStd::fixed_string<6> sFalse = "false";
+    return val ? sTrue.c_str() : sFalse.c_str();
 }
 
 bool FromString(bool& val, cstr s)
diff --git a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
index b759fea158..48310091b3 100644
--- a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
+++ b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
@@ -11,6 +11,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace AZ
 {
@@ -18,7 +19,7 @@ namespace AZ
     {
         namespace DataTypes
         {
-            const static AZStd::fixed_string s_advancedDisabledString = "Disabled";
+            static AZStd::string s_advancedDisabledString = "Disabled";
 
             class IMeshAdvancedRule
                 : public IRule
diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp
index e41e39dd0a..d58a89a110 100644
--- a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp
+++ b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.cpp
@@ -18,11 +18,6 @@ namespace AZ
         {
             namespace DataTypes = AZ::SceneAPI::DataTypes;
 
-            const AZStd::fixed_string<8> MaterialData::s_DiffuseMapName = "Diffuse";
-            const AZStd::fixed_string<9> MaterialData::s_SpecularMapName = "Specular";
-            const AZStd::fixed_string<5> MaterialData::s_BumpMapName = "Bump";
-            const AZStd::fixed_string<1> MaterialData::s_emptyString = "";
-
             MaterialData::MaterialData()
                 : m_isNoDraw(false)
                 , m_diffuseColor(AZ::Vector3::CreateOne())
@@ -72,7 +67,7 @@ namespace AZ
                     return result->second;
                 }
 
-                return s_emptyString;
+                return m_emptyString;
             }
 
             void MaterialData::SetNoDraw(bool isNoDraw)
diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h
index 8c8f8bd66e..2a83a53c53 100644
--- a/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h
+++ b/Code/Tools/SceneAPI/SceneData/GraphData/MaterialData.h
@@ -11,6 +11,7 @@
 #include 
 #include 
 #include 
+#include 
 
 namespace AZ
 {
@@ -96,10 +97,7 @@ namespace AZ
 
                 bool m_isNoDraw;
 
-                const static AZStd::fixed_string<8> s_DiffuseMapName;
-                const static AZStd::fixed_string<9> s_SpecularMapName;
-                const static AZStd::fixed_string<5> s_BumpMapName;
-                const static AZStd::fixed_string<1> s_emptyString;
+                const AZStd::string m_emptyString;
 
                 // A unique id which is used to identify a material in a fbx. 
                 // This is the same as the ID in the fbx file's FbxNode

From 84623dfb6693ed38596c25a7c2902aaa0c4b997f Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 19:25:26 -0700
Subject: [PATCH 058/205] FixedMaxPathString replacement

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/CryEditPy.cpp                        |  4 ++--
 Code/Editor/Util/PathUtil.cpp                    |  2 +-
 .../Framework/AzCore/Tests/IO/Path/PathTests.cpp |  4 ++--
 .../AzFramework/AzFramework/Archive/Archive.cpp  |  8 ++++----
 .../AzFramework/AzFramework/Archive/IArchive.h   |  2 +-
 .../AzFramework/Archive/NestedArchive.cpp        | 16 ++++++++--------
 .../AzFramework/Archive/ZipDirStructures.cpp     |  2 +-
 .../native/ui/ProductAssetTreeModel.cpp          |  4 ++--
 .../native/ui/SourceAssetTreeModel.cpp           |  4 ++--
 9 files changed, 23 insertions(+), 23 deletions(-)

diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp
index 7e07d5553d..e4c300d744 100644
--- a/Code/Editor/CryEditPy.cpp
+++ b/Code/Editor/CryEditPy.cpp
@@ -210,7 +210,7 @@ namespace
     const char* PyGetCurrentLevelName()
     {
         // Using static member to capture temporary data
-        static AZStd::fixed_string tempLevelName;
+        static AZ::IO::FixedMaxPathString tempLevelName;
         tempLevelName = GetIEditor()->GetGameEngine()->GetLevelName().toUtf8().data();
         return tempLevelName.c_str();
     }
@@ -218,7 +218,7 @@ namespace
     const char* PyGetCurrentLevelPath()
     {
         // Using static member to capture temporary data
-        static AZStd::fixed_string tempLevelPath;
+        static AZ::IO::FixedMaxPathString tempLevelPath;
         tempLevelPath = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data();
         return tempLevelPath.c_str();
     }
diff --git a/Code/Editor/Util/PathUtil.cpp b/Code/Editor/Util/PathUtil.cpp
index 3ca4b6222c..e8a5f0f74a 100644
--- a/Code/Editor/Util/PathUtil.cpp
+++ b/Code/Editor/Util/PathUtil.cpp
@@ -246,7 +246,7 @@ namespace Path
     AZStd::string GetEditingGameDataFolder()
     {
         // Define here the mod name
-        static AZStd::fixed_string s_currentModName;
+        static AZ::IO::FixedMaxPathString s_currentModName;
 
         if (s_currentModName.empty())
         {
diff --git a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp
index 79d9f8c302..41e0ac3f09 100644
--- a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp
+++ b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp
@@ -418,7 +418,7 @@ namespace UnitTest
 
         // Check each operator/= and append overload for success
         {
-            AZStd::fixed_string pathString{ "foo" };
+            AZ::IO::FixedMaxPathString pathString{ "foo" };
             AZ::IO::FixedMaxPath testPath('/');
             testPath /= AZ::IO::PathView(pathString);
             testPath /= pathString;
@@ -428,7 +428,7 @@ namespace UnitTest
             EXPECT_STREQ("foo/foo/foo/foo/f", testPath.c_str());
         }
         {
-            AZStd::fixed_string pathString{ "foo" };
+            AZ::IO::FixedMaxPathString pathString{ "foo" };
             AZ::IO::FixedMaxPath testPath('/');
             testPath.Append(AZ::IO::PathView(pathString));
             testPath.Append(pathString);
diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp
index 8c24250396..a3d2103650 100644
--- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp
+++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp
@@ -94,7 +94,7 @@ namespace AZ::IO::ArchiveInternal
             }
             return convertedPath;
         }
-        return AZStd::make_optional>(sourcePath);
+        return AZStd::make_optional(sourcePath);
     }
 
     struct CCachedFileRawData
@@ -614,7 +614,7 @@ namespace AZ::IO
 
     const char* Archive::AdjustFileName(AZStd::string_view src, char* dst, size_t dstSize, uint32_t, bool)
     {
-        AZStd::fixed_string srcPath{ src };
+        AZ::IO::FixedMaxPathString srcPath{ src };
         return AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(srcPath.c_str(), dst, dstSize) ? dst : nullptr;
     }
 
@@ -2407,14 +2407,14 @@ namespace AZ::IO
     //////////////////////////////////////////////////////////////////////////
     bool Archive::RemoveFile(AZStd::string_view pName)
     {
-        AZStd::fixed_string szFullPath{ pName };
+        AZ::IO::FixedMaxPathString szFullPath{ pName };
         return AZ::IO::FileIOBase::GetDirectInstance()->Remove(szFullPath.c_str()) == AZ::IO::ResultCode::Success;
     }
 
     //////////////////////////////////////////////////////////////////////////
     bool Archive::RemoveDir(AZStd::string_view pName)
     {
-        AZStd::fixed_string szFullPath{ pName };
+        AZ::IO::FixedMaxPathString szFullPath{ pName };
 
         if (AZ::IO::FileIOBase::GetDirectInstance()->IsDirectory(szFullPath.c_str()))
         {
diff --git a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h
index 3de63169b2..a23a213f05 100644
--- a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h
+++ b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h
@@ -30,7 +30,7 @@ namespace AZ::IO
     struct INestedArchive;
     struct IArchive;
 
-    using PathString = AZStd::fixed_string;
+    using PathString = AZ::IO::FixedMaxPathString;
     using StackString = AZStd::fixed_string<512>;
 
     struct MemoryBlock;
diff --git a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp
index 16548c6a39..dc1d4aa864 100644
--- a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp
+++ b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp
@@ -41,7 +41,7 @@ namespace AZ::IO
             return ZipDir::ZD_ERROR_INVALID_CALL;
         }
 
-        AZStd::fixed_string fullPath = AdjustPath(szRelativePath);
+        AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath);
         if (fullPath.empty())
         {
             return ZipDir::ZD_ERROR_INVALID_PATH;
@@ -63,7 +63,7 @@ namespace AZ::IO
             return ZipDir::ZD_ERROR_INVALID_CALL;
         }
 
-        AZStd::fixed_string fullPath = AdjustPath(szRelativePath);
+        AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath);
         if (fullPath.empty())
         {
             return ZipDir::ZD_ERROR_INVALID_PATH;
@@ -81,7 +81,7 @@ namespace AZ::IO
             return ZipDir::ZD_ERROR_INVALID_CALL;
         }
 
-        AZStd::fixed_string fullPath = AdjustPath(szRelativePath);
+        AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath);
         if (fullPath.empty())
         {
             return ZipDir::ZD_ERROR_INVALID_PATH;
@@ -105,7 +105,7 @@ namespace AZ::IO
             return ZipDir::ZD_ERROR_INVALID_CALL;
         }
 
-        AZStd::fixed_string fullPath = AdjustPath(szRelativePath);
+        AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath);
         if (fullPath.empty())
         {
             return ZipDir::ZD_ERROR_INVALID_PATH;
@@ -122,7 +122,7 @@ namespace AZ::IO
             return ZipDir::ZD_ERROR_INVALID_CALL;
         }
 
-        AZStd::fixed_string fullPath = AdjustPath(szRelativePath);
+        AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath);
         if (fullPath.empty())
         {
             return ZipDir::ZD_ERROR_INVALID_PATH;
@@ -141,7 +141,7 @@ namespace AZ::IO
             return ZipDir::ZD_ERROR_INVALID_CALL;
         }
 
-        AZStd::fixed_string fullPath = AdjustPath(szRelativePath);
+        AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath);
         if (fullPath.empty())
         {
             return ZipDir::ZD_ERROR_INVALID_PATH;
@@ -152,7 +152,7 @@ namespace AZ::IO
     // finds the file; you don't have to close the returned handle
     auto NestedArchive::FindFile(AZStd::string_view szRelativePath) -> Handle
     {
-        AZStd::fixed_string fullPath = AdjustPath(szRelativePath);
+        AZ::IO::FixedMaxPathString fullPath = AdjustPath(szRelativePath);
         if (fullPath.empty())
         {
             return nullptr;
@@ -249,7 +249,7 @@ namespace AZ::IO
 
         if (m_nFlags & FLAGS_RELATIVE_PATHS_ONLY)
         {
-            return AZStd::fixed_string{ szRelativePath };
+            return AZ::IO::FixedMaxPathString{ szRelativePath };
         }
 
         if ((szRelativePath.size() > 1 && szRelativePath[1] == ':') || (m_nFlags & FLAGS_ABSOLUTE_PATHS))
diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp
index 034d2f4029..445bba63f4 100644
--- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp
+++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp
@@ -440,7 +440,7 @@ namespace AZ::IO::ZipDir
             azstrcpy(volume, AZ_ARRAY_SIZE(volume), filename);
         }
 
-        AZStd::fixed_string drive{ AZ::IO::PathView(volume).RootName().Native() };
+        AZ::IO::FixedMaxPathString drive{ AZ::IO::PathView(volume).RootName().Native() };
         if (drive.empty())
         {
             return false;
diff --git a/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp b/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp
index 6b5fa191e8..0574f00961 100644
--- a/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp
+++ b/Code/Tools/AssetProcessor/native/ui/ProductAssetTreeModel.cpp
@@ -195,7 +195,7 @@ namespace AssetProcessor
         AZ::IO::Path currentFullFolderPath;
         const AZ::IO::PathView filename = productNamePath.Filename();
         const AZ::IO::PathView fullPathWithoutFilename = productNamePath.RemoveFilename();
-        AZStd::fixed_string currentPath;
+        AZ::IO::FixedMaxPathString currentPath;
         for (auto pathIt = fullPathWithoutFilename.begin(); pathIt != fullPathWithoutFilename.end(); ++pathIt)
         {
             currentPath = pathIt->FixedMaxPathString();
@@ -236,7 +236,7 @@ namespace AssetProcessor
         }
 
         AZStd::shared_ptr productItemData =
-            ProductAssetTreeItemData::MakeShared(&product, product.m_productName, AZStd::fixed_string(filename.Native()).c_str(), false, sourceId);
+            ProductAssetTreeItemData::MakeShared(&product, product.m_productName, AZ::IO::FixedMaxPathString(filename.Native()).c_str(), false, sourceId);
         m_productToTreeItem[product.m_productName] =
             parentItem->CreateChild(productItemData);
         m_productIdToTreeItem[product.m_productID] = m_productToTreeItem[product.m_productName];
diff --git a/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp b/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp
index 6a5e53eb75..1fcdd62cf7 100644
--- a/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp
+++ b/Code/Tools/AssetProcessor/native/ui/SourceAssetTreeModel.cpp
@@ -94,7 +94,7 @@ namespace AssetProcessor
         AZ::IO::Path currentFullFolderPath(AZ::IO::PosixPathSeparator);
         const AZ::IO::FixedMaxPath filename = fullPath.Filename();
         fullPath.RemoveFilename();
-        AZStd::fixed_string currentPath;
+        AZ::IO::FixedMaxPathString currentPath;
         for (auto pathIt = fullPath.begin(); pathIt != fullPath.end(); ++pathIt)
         {
             currentPath = pathIt->FixedMaxPathString();
@@ -125,7 +125,7 @@ namespace AssetProcessor
         }
 
         m_sourceToTreeItem[source.m_sourceName] =
-            parentItem->CreateChild(SourceAssetTreeItemData::MakeShared(&source, &scanFolder, source.m_sourceName, AZStd::fixed_string(filename.Native()).c_str(), false));
+            parentItem->CreateChild(SourceAssetTreeItemData::MakeShared(&source, &scanFolder, source.m_sourceName, AZ::IO::FixedMaxPathString(filename.Native()).c_str(), false));
         m_sourceIdToTreeItem[source.m_sourceID] = m_sourceToTreeItem[source.m_sourceName];
         if (!modelIsResetting)
         {

From 895dc09176351b44de34a7f810b40dc6c854f6dc Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 19:30:09 -0700
Subject: [PATCH 059/205] addressing PR comments/suggestions

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzCore/AzCore/std/string/conversions.h    |  4 +-
 .../AzCore/AzCore/std/string/utf8/unchecked.h | 48 +++++++++++++++++++
 .../WinAPI/AzCore/Utils/Utils_WinAPI.cpp      | 12 ++++-
 .../AzCore/Debug/StackTracer_Windows.cpp      |  2 +-
 Code/Legacy/CryCommon/CryTypeInfo.cpp         |  4 +-
 .../DataTypes/Rules/IMeshAdvancedRule.h       |  2 +-
 6 files changed, 63 insertions(+), 9 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index 235eb188d1..473c327143 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -338,7 +338,7 @@ namespace AZStd
         if (srcLen > 0)
         {
             char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen);
-            if (*(endStr - 1) != '\0')
+            if (endStr < (dest + destSize) && *(endStr - 1) != '\0')
             {
                 *endStr = '\0'; // copy null terminator
             }
@@ -495,7 +495,7 @@ namespace AZStd
         if (srcLen > 0)
         {
             wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen);
-            if (*(endWStr - 1) != '\0')
+            if (endWStr < (dest + destSize) && *(endWStr - 1) != '\0')
             {
                 *endWStr = '\0'; // copy null terminator
             }
diff --git a/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h b/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
index cfc917ddc4..7199c58d3e 100644
--- a/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
+++ b/Code/Framework/AzCore/AzCore/std/string/utf8/unchecked.h
@@ -251,6 +251,54 @@ namespace Utf8::Unchecked
 
         return result;
     }
+
+    static constexpr size_t utf8_codepoint_length(AZ::u32 cp)
+    {
+        if (cp < 0x80)
+        {
+            return 1;
+        }
+        else if (cp < 0x800)
+        {
+            return 2;
+        }
+        else if (cp < 0x10000)
+        {
+            return 3;
+        }
+        return 4;
+    }
+
+    template 
+    size_t utf16ToUtf8BytesRequired(u16bit_iterator start, u16bit_iterator end)
+    {
+        size_t bytesRequired = 0;
+        while (start != end)
+        {
+            AZ::u32 cp = Utf8::Internal::mask16(*start++);
+            // Take care of surrogate pairs first
+            if (Utf8::Internal::is_lead_surrogate(cp))
+            {
+                AZ::u32 trail_surrogate = Utf8::Internal::mask16(*start++);
+                cp = (cp << 10) + trail_surrogate + Internal::SURROGATE_OFFSET;
+            }
+            bytesRequired += utf8_codepoint_length(cp);
+        }
+        return bytesRequired;
+    }
+
+    template 
+    size_t utf32ToUtf8BytesRequired(u32bit_iterator start, u32bit_iterator end)
+    {
+        size_t bytesRequired = 0;
+        while (start != end)
+        {
+            bytesRequired += utf8_codepoint_length(*start++);
+        }
+        return bytesRequired;
+    }
+
+
 } // namespace Utf8::Unchecked
 
 
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
index dc104668be..4d8c9c8cfc 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
@@ -31,7 +31,7 @@ namespace AZ
             // Platform specific get exe path: http://stackoverflow.com/a/1024937
             // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
             wchar_t pathBufferW[AZ::IO::MaxPathLength] = { 0 };
-            const DWORD pathLen = GetModuleFileNameW(nullptr, pathBufferW, static_cast(exeStorageSize));
+            const DWORD pathLen = GetModuleFileNameW(nullptr, pathBufferW, static_cast(AZStd::size(pathBufferW)));
             const DWORD errorCode = GetLastError();
             if (pathLen == exeStorageSize && errorCode == ERROR_INSUFFICIENT_BUFFER)
             {
@@ -43,7 +43,15 @@ namespace AZ
             }
             else
             {
-                AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBufferW);
+                size_t utf8PathSize = Utf8::Unchecked::utf16ToUtf8BytesRequired(pathBufferW, pathBufferW + pathLen);
+                if (utf8PathSize >= exeStorageSize)
+                {
+                    result.m_pathStored = ExecutablePathResult::BufferSizeNotLargeEnough;
+                }
+                else
+                {
+                    AZStd::to_string(exeStorageBuffer, exeStorageSize, pathBufferW);
+                }
             }
 
             return result;
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp
index 8a99616de3..6cfaf1703b 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp
@@ -90,7 +90,7 @@ namespace AZ {
             {
             case CBA_EVENT:
                 evt = (PIMAGEHLP_CBA_EVENT)CallbackData;
-                _tprintf(_T("%s"), evt->desc);
+                printf("%s", evt->desc);
                 break;
 
             default:
diff --git a/Code/Legacy/CryCommon/CryTypeInfo.cpp b/Code/Legacy/CryCommon/CryTypeInfo.cpp
index b1f7f20601..82743f7eef 100644
--- a/Code/Legacy/CryCommon/CryTypeInfo.cpp
+++ b/Code/Legacy/CryCommon/CryTypeInfo.cpp
@@ -132,9 +132,7 @@ const CTypeInfo&PtrTypeInfo()
 // bool
 AZStd::string ToString(bool const& val)
 {
-    static AZStd::fixed_string<5> sTrue = "true";
-    static AZStd::fixed_string<6> sFalse = "false";
-    return val ? sTrue.c_str() : sFalse.c_str();
+    return val ? "true" : "false";
 }
 
 bool FromString(bool& val, cstr s)
diff --git a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
index 48310091b3..04ed3f0949 100644
--- a/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
+++ b/Code/Tools/SceneAPI/SceneCore/DataTypes/Rules/IMeshAdvancedRule.h
@@ -19,7 +19,7 @@ namespace AZ
     {
         namespace DataTypes
         {
-            static AZStd::string s_advancedDisabledString = "Disabled";
+            static const char* s_advancedDisabledString = "Disabled";
 
             class IMeshAdvancedRule
                 : public IRule

From 6d79f1beee1987bcaac4d5e0c0c84bfdf430c625 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 19:30:52 -0700
Subject: [PATCH 060/205] more replacements of A functions

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp |  2 +-
 Code/Editor/ProcessInfo.cpp                          |  2 +-
 .../Platform/Windows/AzCore/Platform_Windows.cpp     | 12 ++++++------
 3 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
index 0b33caed88..a3be4cfd45 100644
--- a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
+++ b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp
@@ -28,7 +28,7 @@ bool CMailer::SendMail(const char* subject,
     GetCurrentDirectoryW(sizeof(dir), dir);
 
     // Load MAPI dll
-    HMODULE hMAPILib = LoadLibraryA("MAPI32.DLL");
+    HMODULE hMAPILib = LoadLibraryW(L"MAPI32.DLL");
     LPMAPISENDMAIL lpfnMAPISendMail = (LPMAPISENDMAIL) GetProcAddress(hMAPILib, "MAPISendMail");
 
     int numRecipients  = (int)_recipients.size();
diff --git a/Code/Editor/ProcessInfo.cpp b/Code/Editor/ProcessInfo.cpp
index 87f4f23846..692e5d65ef 100644
--- a/Code/Editor/ProcessInfo.cpp
+++ b/Code/Editor/ProcessInfo.cpp
@@ -41,7 +41,7 @@ void LoadPSApi()
 {
     if (!g_hPSAPI)
     {
-        g_hPSAPI = LoadLibraryA("psapi.dll");
+        g_hPSAPI = LoadLibraryW(L"psapi.dll");
 
         if (g_hPSAPI)
         {
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp
index dc675cd931..cc45b36c41 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Platform_Windows.cpp
@@ -31,8 +31,8 @@ namespace AZ
                 // Query the machine guid generated at install time by windows, which is generated from
                 // hardware signatures. This guid is not enough, because images (AWS) may duplicate this,
                 // so include the hostname/username as well
-                TCHAR machineInfo[MAX_COMPUTERNAME_LENGTH + 1024] = { 0 };
-                ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", 0, KEY_QUERY_VALUE, &key);
+                wchar_t machineInfo[MAX_COMPUTERNAME_LENGTH + 1024] = { 0 };
+                ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography", 0, KEY_QUERY_VALUE, &key);
                 if (ret == ERROR_SUCCESS)
                 {
                     DWORD dataType = REG_SZ;
@@ -45,17 +45,17 @@ namespace AZ
                     AZ_Error("System", false, "Failed to open HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid!")
                 }
 
-                TCHAR* hostname = machineInfo + wcslen(machineInfo);
+                wchar_t* hostname = machineInfo + wcslen(machineInfo);
                 // salt the guid time with ComputerName/UserName
                 DWORD  bufCharCount = DWORD(sizeof(machineInfo) - (hostname - machineInfo));
-                if (!::GetComputerName(hostname, &bufCharCount))
+                if (!::GetComputerNameW(hostname, &bufCharCount))
                 {
                     AZ_Error("System", false, "GetComputerName filed with code %d", GetLastError());
                 }
 
-                TCHAR* username = hostname + wcslen(hostname);
+                wchar_t* username = hostname + wcslen(hostname);
                 bufCharCount = DWORD(sizeof(machineInfo) - (username - machineInfo));
-                if( !GetUserName( username, &bufCharCount ) ) 
+                if(!GetUserNameW(username, &bufCharCount)) 
                 {
                     AZ_Error("System",false,"GetUserName filed with code %d",GetLastError());
                 }

From 4358b6eb27fbb65baebb0afc2444015f8983af83 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 19:31:12 -0700
Subject: [PATCH 061/205] runtime fixes (Editor running)

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/Controls/ConsoleSCB.cpp           |   8 +-
 Code/Editor/QuickAccessBar.cpp                |   6 +-
 Code/Editor/SettingsManager.cpp               |  10 +-
 Code/Editor/ToolsConfigPage.cpp               |   6 +-
 Code/Legacy/CryCommon/IConsole.h              |   2 +-
 Code/Legacy/CryCommon/Mocks/IConsoleMock.h    |   2 +-
 Code/Legacy/CrySystem/XConsole.cpp            | 115 +++++-------------
 Code/Legacy/CrySystem/XConsole.h              |   2 +-
 Code/Legacy/CrySystem/XConsoleVariable.h      |   7 +-
 .../RemoteConsole/Core/RemoteConsoleCore.cpp  |   6 +-
 10 files changed, 55 insertions(+), 109 deletions(-)

diff --git a/Code/Editor/Controls/ConsoleSCB.cpp b/Code/Editor/Controls/ConsoleSCB.cpp
index 0c664bbc59..9c13aa7328 100644
--- a/Code/Editor/Controls/ConsoleSCB.cpp
+++ b/Code/Editor/Controls/ConsoleSCB.cpp
@@ -562,15 +562,15 @@ static void OnVariableUpdated([[maybe_unused]] int row, ICVar* pCVar)
 static CVarBlock* VarBlockFromConsoleVars()
 {
     IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
-    std::vector cmds;
+    AZStd::vector cmds;
     cmds.resize(console->GetNumVars());
-    size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size());
+    size_t cmdCount = console->GetSortedVars(cmds);
 
     CVarBlock* vb = new CVarBlock;
     IVariable* pVariable = 0;
     for (int i = 0; i < cmdCount; i++)
     {
-        ICVar* pCVar = console->GetCVar(cmds[i]);
+        ICVar* pCVar = console->GetCVar(cmds[i].data());
         if (!pCVar)
         {
             continue;
@@ -602,7 +602,7 @@ static CVarBlock* VarBlockFromConsoleVars()
         pCVar->AddOnChangeFunctor(onChange);
 
         pVariable->SetDescription(pCVar->GetHelp());
-        pVariable->SetName(cmds[i]);
+        pVariable->SetName(cmds[i].data());
 
         // Transfer the custom limits have they have been set for this variable
         if (pCVar->HasCustomLimits())
diff --git a/Code/Editor/QuickAccessBar.cpp b/Code/Editor/QuickAccessBar.cpp
index 0379be027d..59b4418c4c 100644
--- a/Code/Editor/QuickAccessBar.cpp
+++ b/Code/Editor/QuickAccessBar.cpp
@@ -68,12 +68,12 @@ void CQuickAccessBar::OnInitDialog()
 
     // Add console variables & commands.
     IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
-    std::vector cmds;
+    AZStd::vector cmds;
     cmds.resize(console->GetNumVars());
-    size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size());
+    size_t cmdCount = console->GetSortedVars(cmds);
     for (int i = 0; i < cmdCount; ++i)
     {
-        m_model->setStringList(m_model->stringList() += cmds[i]);
+        m_model->setStringList(m_model->stringList() += cmds[i].data());
     }
 }
 
diff --git a/Code/Editor/SettingsManager.cpp b/Code/Editor/SettingsManager.cpp
index 82e3eaf1e6..3f170e83c8 100644
--- a/Code/Editor/SettingsManager.cpp
+++ b/Code/Editor/SettingsManager.cpp
@@ -607,7 +607,7 @@ void CSettingsManager::SerializeCVars(XmlNodeRef& node, bool bLoad)
     int nCurrentVariable(0);
     IConsole* piConsole(NULL);
     ICVar* piVariable(NULL);
-    std::vector  cszVariableNames;
+    AZStd::vector  cszVariableNames;
 
     char* szKey(NULL);
     char* szValue(NULL);
@@ -662,7 +662,7 @@ void CSettingsManager::SerializeCVars(XmlNodeRef& node, bool bLoad)
         nNumberOfVariables = piConsole->GetNumVisibleVars();
         cszVariableNames.resize(nNumberOfVariables, NULL);
 
-        if (piConsole->GetSortedVars((const char**)&cszVariableNames.front(), nNumberOfVariables, NULL) != nNumberOfVariables)
+        if (piConsole->GetSortedVars(cszVariableNames, NULL) != nNumberOfVariables)
         {
             assert(false);
             return;
@@ -670,12 +670,12 @@ void CSettingsManager::SerializeCVars(XmlNodeRef& node, bool bLoad)
 
         for (nCurrentVariable = 0; nCurrentVariable < cszVariableNames.size(); ++nCurrentVariable)
         {
-            if (_stricmp(cszVariableNames[nCurrentVariable], "_TestFormatMessage") == 0)
+            if (_stricmp(cszVariableNames[nCurrentVariable].data(), "_TestFormatMessage") == 0)
             {
                 continue;
             }
 
-            piVariable = piConsole->GetCVar(cszVariableNames[nCurrentVariable]);
+            piVariable = piConsole->GetCVar(cszVariableNames[nCurrentVariable].data());
             if (!piVariable)
             {
                 assert(false);
@@ -683,7 +683,7 @@ void CSettingsManager::SerializeCVars(XmlNodeRef& node, bool bLoad)
             }
 
             newCVarNode = XmlHelpers::CreateXmlNode(CVAR_NODE);
-            newCVarNode->setAttr(cszVariableNames[nCurrentVariable], piVariable->GetString());
+            newCVarNode->setAttr(cszVariableNames[nCurrentVariable].data(), piVariable->GetString());
             cvarsNode->addChild(newCVarNode);
         }
 
diff --git a/Code/Editor/ToolsConfigPage.cpp b/Code/Editor/ToolsConfigPage.cpp
index a2328550e0..7e481506b3 100644
--- a/Code/Editor/ToolsConfigPage.cpp
+++ b/Code/Editor/ToolsConfigPage.cpp
@@ -818,12 +818,12 @@ void CToolsConfigPage::FillConsoleCmds()
 {
     QStringList commands;
     IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
-    std::vector cmds;
+    AZStd::vector cmds;
     cmds.resize(console->GetNumVars());
-    size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size());
+    size_t cmdCount = console->GetSortedVars(cmds);
     for (int i = 0; i < cmdCount; ++i)
     {
-        commands.push_back(cmds[i]);
+        commands.push_back(cmds[i].data());
     }
     m_completionModel->setStringList(commands);
 }
diff --git a/Code/Legacy/CryCommon/IConsole.h b/Code/Legacy/CryCommon/IConsole.h
index 79bfc5b532..e03de35aa1 100644
--- a/Code/Legacy/CryCommon/IConsole.h
+++ b/Code/Legacy/CryCommon/IConsole.h
@@ -426,7 +426,7 @@ struct IConsole
     //   szPrefix - 0 or prefix e.g. "sys_spec_"
     // Return
     //   used size
-    virtual size_t GetSortedVars(const char** pszArray, size_t numItems, const char* szPrefix = 0) = 0;
+    virtual size_t GetSortedVars(AZStd::vector& pszArray, const char* szPrefix = 0) = 0;
     virtual const char* AutoComplete(const char* substr) = 0;
     virtual const char* AutoCompletePrev(const char* substr) = 0;
     virtual const char* ProcessCompletion(const char* szInputBuffer) = 0;
diff --git a/Code/Legacy/CryCommon/Mocks/IConsoleMock.h b/Code/Legacy/CryCommon/Mocks/IConsoleMock.h
index 1475e8e01e..b416aa5f11 100644
--- a/Code/Legacy/CryCommon/Mocks/IConsoleMock.h
+++ b/Code/Legacy/CryCommon/Mocks/IConsoleMock.h
@@ -56,7 +56,7 @@ public:
     MOCK_METHOD0(IsOpened, bool ());
     MOCK_METHOD0(GetNumVars, int());
     MOCK_METHOD0(GetNumVisibleVars, int());
-    MOCK_METHOD3(GetSortedVars, size_t (const char** pszArray, size_t numItems, const char* szPrefix));
+    MOCK_METHOD2(GetSortedVars, size_t (AZStd::vector& pszArray, const char* szPrefix));
     MOCK_METHOD1(AutoComplete, const char*(const char* substr));
     MOCK_METHOD1(AutoCompletePrev, const char*(const char* substr));
     MOCK_METHOD1(ProcessCompletion, const char*(const char* szInputBuffer));
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index 6da42420f8..0f98dd12d6 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -84,35 +84,6 @@ inline int GetCharPrio(char x)
         return x;
     }
 }
-// case sensitive
-inline bool less_CVar(const AZStd::string& left, const AZStd::string& right)
-{
-    AZStd::string_view leftView(left);
-    AZStd::string_view rightView(right);
-    for (;; )
-    {
-        uint32 l = GetCharPrio(leftView.front()), r = GetCharPrio(rightView.front());
-
-        if (l < r)
-        {
-            return true;
-        }
-        if (l > r)
-        {
-            return false;
-        }
-
-        if (leftView.front() == 0 || rightView.front() == 0)
-        {
-            break;
-        }
-
-        leftView.remove_prefix(1);
-        rightView.remove_prefix(1);
-    }
-
-    return false;
-}
 
 void Command_SetWaitSeconds(IConsoleCmdArgs* pCmd)
 {
@@ -347,28 +318,6 @@ void CXConsole::Init(ISystem* pSystem)
         con_restricted = 0;
     }
 
-    // test cases -----------------------------------------------
-    assert(GetCVar("con_debug") != 0);        // should be registered a few lines above
-    assert(GetCVar("Con_Debug") == GetCVar("con_debug"));     // different case
-
-    // editor
-    assert(strcmp(AutoComplete("con_"), "con_debug") == 0);
-    assert(strcmp(AutoComplete("CON_"), "con_debug") == 0);
-    assert(strcmp(AutoComplete("con_debug"), "con_display_last_messages") == 0);       // actually we should reconsider this behavior
-    assert(strcmp(AutoComplete("Con_Debug"), "con_display_last_messages") == 0);       // actually we should reconsider this behavior
-
-    // game
-    assert(strcmp(ProcessCompletion("con_"), "con_debug ") == 0);
-    ResetAutoCompletion();
-    assert(strcmp(ProcessCompletion("CON_"), "con_debug ") == 0);
-    ResetAutoCompletion();
-    assert(strcmp(ProcessCompletion("con_debug"), "con_debug ") == 0);
-    ResetAutoCompletion();
-    assert(strcmp(ProcessCompletion("Con_Debug"), "con_debug ") == 0);
-    ResetAutoCompletion();
-
-    // ----------------------------------------------------------
-
     m_nLoadingBackTexID = -1;
 
     if (gEnv->IsDedicated())
@@ -2424,7 +2373,7 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
 
     if (!matches.empty())
     {
-        std::sort(matches.begin(), matches.end(), less_CVar);       // to sort commands with variables
+        std::sort(matches.begin(), matches.end());       // to sort commands with variables
     }
     if (showlist && !matches.empty())
     {
@@ -3181,7 +3130,7 @@ char* CXConsole::GetCheatVarAt(uint32 nOffset)
 
 
 //////////////////////////////////////////////////////////////////////////
-size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const char* szPrefix)
+size_t CXConsole::GetSortedVars(AZStd::vector& pszArray, const char* szPrefix)
 {
     size_t i = 0;
     size_t iPrefixLen = szPrefix ? strlen(szPrefix) : 0;
@@ -3191,7 +3140,7 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch
         ConsoleVariablesMap::const_iterator it, end = m_mapVariables.end();
         for (it = m_mapVariables.begin(); it != end; ++it)
         {
-            if (pszArray && i >= numItems)
+            if (i >= pszArray.size())
             {
                 break;
             }
@@ -3209,10 +3158,7 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch
                 continue;
             }
 
-            if (pszArray)
-            {
-                pszArray[i] = it->first;
-            }
+            pszArray[i] = it->first;
 
             i++;
         }
@@ -3223,7 +3169,7 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch
         ConsoleCommandsMap::iterator it, end = m_mapCommands.end();
         for (it = m_mapCommands.begin(); it != end; ++it)
         {
-            if (pszArray && i >= numItems)
+            if (i >= pszArray.size())
             {
                 break;
             }
@@ -3241,18 +3187,15 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch
                 continue;
             }
 
-            if (pszArray)
-            {
-                pszArray[i] = it->first.c_str();
-            }
+            pszArray[i] = it->first.c_str();
 
             i++;
         }
     }
 
-    if (i != 0 && pszArray)
+    if (i != 0)
     {
-        std::sort(pszArray, pszArray + i, less_CVar);
+        std::sort(pszArray.begin(), pszArray.end());
     }
 
     return i;
@@ -3261,22 +3204,22 @@ size_t CXConsole::GetSortedVars(const char** pszArray, size_t numItems, const ch
 //////////////////////////////////////////////////////////////////////////
 void CXConsole::FindVar(const char* substr)
 {
-    std::vector cmds;
+    AZStd::vector cmds;
     cmds.resize(GetNumVars() + m_mapCommands.size());
-    size_t cmdCount = GetSortedVars(&cmds[0], cmds.size());
+    size_t cmdCount = GetSortedVars(cmds);
 
     for (size_t i = 0; i < cmdCount; i++)
     {
         if (AZ::StringFunc::Find(cmds[i], substr) != AZStd::string::npos)
         {
-            ICVar* pCvar = gEnv->pConsole->GetCVar(cmds[i]);
+            ICVar* pCvar = gEnv->pConsole->GetCVar(cmds[i].data());
             if (pCvar)
             {
                 DisplayVarValue(pCvar);
             }
             else
             {
-                ConsoleLogInputResponse("    $3%s $6(Command)", cmds[i]);
+                ConsoleLogInputResponse("    $3%.*s $6(Command)", aznumeric_cast(cmds[i].size()), cmds[i].data());
             }
         }
     }
@@ -3287,22 +3230,22 @@ const char* CXConsole::AutoComplete(const char* substr)
 {
     // following code can be optimized
 
-    std::vector cmds;
+    AZStd::vector cmds;
     cmds.resize(GetNumVars() + m_mapCommands.size());
-    size_t cmdCount = GetSortedVars(&cmds[0], cmds.size());
+    size_t cmdCount = GetSortedVars(cmds);
 
     size_t substrLen = strlen(substr);
 
     // If substring is empty return first command.
     if (substrLen == 0 && cmdCount > 0)
     {
-        return cmds[0];
+        return cmds[0].data();
     }
 
     // find next
     for (size_t i = 0; i < cmdCount; i++)
     {
-        const char* szCmd = cmds[i];
+        const char* szCmd = cmds[i].data();
         size_t cmdlen = strlen(szCmd);
         if (cmdlen >= substrLen && memcmp(szCmd, substr, substrLen) == 0)
         {
@@ -3311,18 +3254,18 @@ const char* CXConsole::AutoComplete(const char* substr)
                 i++;
                 if (i < cmdCount)
                 {
-                    return cmds[i];
+                    return cmds[i].data();
                 }
-                return cmds[i - 1];
+                return cmds[i - 1].data();
             }
-            return cmds[i];
+            return cmds[i].data();
         }
     }
 
     // then first matching case insensitive
     for (size_t i = 0; i < cmdCount; i++)
     {
-        const char* szCmd = cmds[i];
+        const char* szCmd = cmds[i].data();
 
         size_t cmdlen = strlen(szCmd);
         if (cmdlen >= substrLen && azstrnicmp(szCmd, substr, substrLen) == 0)
@@ -3332,11 +3275,11 @@ const char* CXConsole::AutoComplete(const char* substr)
                 i++;
                 if (i < cmdCount)
                 {
-                    return cmds[i];
+                    return cmds[i].data();
                 }
-                return cmds[i - 1];
+                return cmds[i - 1].data();
             }
-            return cmds[i];
+            return cmds[i].data();
         }
     }
 
@@ -3357,27 +3300,27 @@ void CXConsole::SetInputLine(const char* szLine)
 //////////////////////////////////////////////////////////////////////////
 const char* CXConsole::AutoCompletePrev(const char* substr)
 {
-    std::vector cmds;
+    AZStd::vector cmds;
     cmds.resize(GetNumVars() + m_mapCommands.size());
-    size_t cmdCount = GetSortedVars(&cmds[0], cmds.size());
+    size_t cmdCount = GetSortedVars(cmds);
 
     // If substring is empty return last command.
     if (strlen(substr) == 0 && cmds.size() > 0)
     {
-        return cmds[cmdCount - 1];
+        return cmds[cmdCount - 1].data();
     }
 
     for (unsigned int i = 0; i < cmdCount; i++)
     {
-        if (azstricmp(substr, cmds[i]) == 0)
+        if (azstricmp(substr, cmds[i].data()) == 0)
         {
             if (i > 0)
             {
-                return cmds[i - 1];
+                return cmds[i - 1].data();
             }
             else
             {
-                return cmds[0];
+                return cmds[0].data();
             }
         }
     }
diff --git a/Code/Legacy/CrySystem/XConsole.h b/Code/Legacy/CrySystem/XConsole.h
index b141a88e52..16d1870be6 100644
--- a/Code/Legacy/CrySystem/XConsole.h
+++ b/Code/Legacy/CrySystem/XConsole.h
@@ -181,7 +181,7 @@ public:
     virtual bool IsOpened();
     virtual int GetNumVars();
     virtual int GetNumVisibleVars();
-    virtual size_t GetSortedVars(const char** pszArray, size_t numItems, const char* szPrefix = 0);
+    virtual size_t GetSortedVars(AZStd::vector& pszArray, const char* szPrefix = 0);
     virtual int GetNumCheatVars();
     virtual void SetCheatVarHashRange(size_t firstVar, size_t lastVar);
     virtual void CalcCheatVarHash();
diff --git a/Code/Legacy/CrySystem/XConsoleVariable.h b/Code/Legacy/CrySystem/XConsoleVariable.h
index e4f9c14355..122389407f 100644
--- a/Code/Legacy/CrySystem/XConsoleVariable.h
+++ b/Code/Legacy/CrySystem/XConsoleVariable.h
@@ -179,8 +179,11 @@ public:
     CXConsoleVariableString(CXConsole* pConsole, const char* sName, const char* szDefault, int nFlags, const char* help)
         : CXConsoleVariableBase(pConsole, sName, nFlags, help)
     {
-        m_sValue = szDefault;
-        m_sDefault = szDefault;
+        if (szDefault)
+        {
+            m_sValue = szDefault;
+            m_sDefault = szDefault;
+        }
     }
 
     // interface ICVar --------------------------------------------------------------------------------------
diff --git a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp
index 24faf2ccaa..aa439116a0 100644
--- a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp
+++ b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp
@@ -446,10 +446,10 @@ bool SRemoteClient::SendPackage(const char* buffer, int size)
 /////////////////////////////////////////////////////////////////////////////////////////////
 void SRemoteClient::FillAutoCompleteList(AZStd::vector& list)
 {
-    AZStd::vector cmds;
-    size_t count = gEnv->pConsole->GetSortedVars(nullptr, 0);
+    AZStd::vector cmds;
+    size_t count = gEnv->pConsole->GetSortedVars(cmds);
     cmds.resize(count);
-    count = gEnv->pConsole->GetSortedVars(&cmds[0], count);
+    count = gEnv->pConsole->GetSortedVars(cmds);
     for (size_t i = 0; i < count; ++i)
     {
         list.push_back(cmds[i]);

From b4bf775647c3d2bc03a94988226e1751644ed9ae Mon Sep 17 00:00:00 2001
From: pappeste 
Date: Wed, 16 Jun 2021 17:14:27 -0700
Subject: [PATCH 062/205] enable the warning

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 cmake/Platform/Common/MSVC/Configurations_msvc.cmake | 1 -
 1 file changed, 1 deletion(-)

diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake
index 4024e45bad..118a515e30 100644
--- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake
+++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake
@@ -38,7 +38,6 @@ ly_append_configurations_options(
         /wd4201 # nonstandard extension used: nameless struct/union. This actually became part of the C++11 std, MS has an open issue: https://developercommunity.visualstudio.com/t/warning-level-4-generates-a-bogus-warning-c4201-no/103064
 
         # Disabling these warnings while they get fixed
-        /wd4018 # signed/unsigned mismatch
         /wd4244 # conversion, possible loss of data
         /wd4245 # conversion, signed/unsigned mismatch
         /wd4389 # comparison, signed/unsigned mismatch

From 97354ce90a9ddd6600271df1e663e21790fc8dc1 Mon Sep 17 00:00:00 2001
From: pappeste 
Date: Fri, 18 Jun 2021 16:36:30 -0700
Subject: [PATCH 063/205] Sandbox

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/ViewportTitleDlg.cpp | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp
index c1e1afb908..cbf2958eea 100644
--- a/Code/Editor/ViewportTitleDlg.cpp
+++ b/Code/Editor/ViewportTitleDlg.cpp
@@ -451,19 +451,19 @@ void CViewportTitleDlg::AddFOVMenus(QMenu* menu, std::function call
     {
         for (size_t i = 0; i < customPresets.size(); ++i)
         {
-            if (customPresets[i].isEmpty())
+            if (customPresets[static_cast(i)].isEmpty())
             {
                 break;
             }
 
             float fov = gSettings.viewports.fDefaultFov;
             bool ok;
-            float f = customPresets[i].toDouble(&ok);
+            float f = customPresets[static_cast(i)].toDouble(&ok);
             if (ok)
             {
                 fov = std::max(1.0f, f);
                 fov = std::min(120.0f, f);
-                QAction* action = menu->addAction(customPresets[i]);
+                QAction* action = menu->addAction(customPresets[static_cast(i)]);
                 connect(action, &QAction::triggered, action, [fov, callback](){ callback(fov); });
             }
         }
@@ -537,13 +537,13 @@ void CViewportTitleDlg::AddAspectRatioMenus(QMenu* menu, std::function(i)].isEmpty())
         {
             break;
         }
 
         static QRegularExpression regex(QStringLiteral("^(\\d+):(\\d+)$"));
-        QRegularExpressionMatch matches = regex.match(customPresets[i]);
+        QRegularExpressionMatch matches = regex.match(customPresets[static_cast(i)]);
         if (matches.hasMatch())
         {
             bool ok;
@@ -551,7 +551,7 @@ void CViewportTitleDlg::AddAspectRatioMenus(QMenu* menu, std::functionaddAction(customPresets[i]);
+            QAction* action = menu->addAction(customPresets[static_cast(i)]);
             connect(action, &QAction::triggered, action, [width, height, callback]() {callback(width, height); });
         }
     }
@@ -668,13 +668,13 @@ void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::function(i)].isEmpty())
         {
             break;
         }
 
         static QRegularExpression regex(QStringLiteral("^(\\d+) x (\\d+)$"));
-        QRegularExpressionMatch matches = regex.match(customPresets[i]);
+        QRegularExpressionMatch matches = regex.match(customPresets[static_cast(i)]);
         if (matches.hasMatch())
         {
             bool ok;
@@ -682,7 +682,7 @@ void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::functionaddAction(customPresets[i]);
+            QAction* action = menu->addAction(customPresets[static_cast(i)]);
             connect(action, &QAction::triggered, action, [width, height, callback](){ callback(width, height); });
         }
     }

From 10f950b726ca9e6d8fe7f3c776b6094d9027dcce Mon Sep 17 00:00:00 2001
From: pappeste 
Date: Fri, 18 Jun 2021 17:45:51 -0700
Subject: [PATCH 064/205]  fix w4018

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Prefab/Benchmark/PrefabBenchmarkFixture.cpp |  4 ++--
 .../Prefab/Benchmark/PrefabCreateBenchmarks.cpp |  6 +++---
 .../Benchmark/PrefabInstantiateBenchmarks.cpp   |  2 +-
 .../Prefab/Benchmark/PrefabLoadBenchmarks.cpp   |  2 +-
 Code/Legacy/CrySystem/SystemWin32.cpp           |  2 +-
 .../SDKWrapper/AssImpMaterialWrapper.cpp        |  2 +-
 .../Importers/AssImpAnimationImporter.cpp       |  4 ++--
 .../Importers/AssImpBitangentStreamImporter.cpp |  4 ++--
 .../Importers/AssImpBlendShapeImporter.cpp      |  8 ++++----
 .../Importers/AssImpColorStreamImporter.cpp     |  9 ++++-----
 .../Importers/AssImpMaterialImporter.cpp        |  2 +-
 .../Importers/AssImpTangentStreamImporter.cpp   |  4 ++--
 .../Importers/AssImpUvMapImporter.cpp           |  6 +++---
 .../Utilities/AssImpMeshImporterUtilities.cpp   |  8 ++++----
 .../Code/Source/AWSCoreSystemComponent.cpp      |  2 +-
 .../Attribution/AWSCoreAttributionManager.cpp   |  2 +-
 Gems/AWSMetrics/Code/Source/MetricsManager.cpp  |  4 ++--
 Gems/AWSMetrics/Code/Source/MetricsQueue.cpp    |  2 +-
 .../AtomFont/Code/Source/FontRenderer.cpp       |  4 ++--
 .../Code/Source/Family/BlastFamilyImpl.cpp      |  2 +-
 Gems/Blast/Code/Tests/Mocks/BlastMocks.h        |  2 +-
 Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp  |  2 +-
 .../Code/Tests/GradientSignalImageTests.cpp     |  8 ++++----
 Gems/ImGui/Code/Source/ImGuiManager.cpp         |  2 +-
 .../Code/Source/Shape/ShapeGeometryUtil.cpp     | 17 ++++++++---------
 .../Editor/Animation/UiAnimViewSequence.cpp     |  4 ++--
 Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp |  4 ++--
 .../LyShine/Code/Source/EditorPropertyTypes.cpp |  3 ++-
 Gems/LyShine/Code/Source/UiImageComponent.cpp   | 12 ++++++------
 .../LyShine/Code/Source/UiInteractableState.cpp |  2 +-
 .../Code/Source/UiParticleEmitterComponent.cpp  |  4 ++--
 Gems/LyShine/Code/Source/UiTextComponent.cpp    |  2 +-
 Gems/PhysXDebug/Code/Source/SystemComponent.cpp |  4 ++--
 33 files changed, 72 insertions(+), 73 deletions(-)

diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabBenchmarkFixture.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabBenchmarkFixture.cpp
index 7e47fa9569..9925d5bff3 100644
--- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabBenchmarkFixture.cpp
+++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabBenchmarkFixture.cpp
@@ -85,7 +85,7 @@ namespace Benchmark
 
     void BM_Prefab::CreateEntities(const unsigned int entityCount, AZStd::vector& entities)
     {
-        for (int entityIndex = 0; entityIndex < entityCount; ++entityIndex)
+        for (unsigned int entityIndex = 0; entityIndex < entityCount; ++entityIndex)
         {
             AZStd::string entityName = "TestEntity";
             entityName = entityName + AZStd::to_string(entityIndex);
@@ -101,7 +101,7 @@ namespace Benchmark
     void BM_Prefab::CreateFakePaths(const unsigned int pathCount)
     {
         //setup fake paths
-        for (int number = 0; number < pathCount; ++number)
+        for (unsigned int number = 0; number < pathCount; ++number)
         {
             AZStd::string path = m_pathString;
             m_paths.push_back(path + AZStd::to_string(number) + "_" + AZStd::to_string(pathCount));
diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp
index b809a20944..12efea1cc8 100644
--- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp
+++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp
@@ -32,7 +32,7 @@ namespace Benchmark
 
             state.ResumeTiming();
 
-            for (int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter)
+            for (unsigned int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter)
             {
                 newInstances.push_back(m_prefabSystemComponent->CreatePrefab(
                     { entities[instanceCounter] },
@@ -110,7 +110,7 @@ namespace Benchmark
             AZStd::vector> testInstances;
             testInstances.resize(numInstancesToAdd);
 
-            for (int instanceCounter = 0; instanceCounter < numInstancesToAdd; ++instanceCounter)
+            for (unsigned int instanceCounter = 0; instanceCounter < numInstancesToAdd; ++instanceCounter)
             {
                 testInstances[instanceCounter] = (m_prefabSystemComponent->CreatePrefab(
                     { entities[instanceCounter] }
@@ -161,7 +161,7 @@ namespace Benchmark
 
             state.ResumeTiming();
 
-            for (int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter)
+            for (unsigned int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter)
             {
                 nestedInstanceRoot = m_prefabSystemComponent->CreatePrefab(
                     {},
diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp
index 3e9f0ab08e..90ff30a30e 100644
--- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp
+++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp
@@ -33,7 +33,7 @@ namespace Benchmark
 
             state.ResumeTiming();
 
-            for (int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter)
+            for (unsigned int instanceCounter = 0; instanceCounter < numInstances; ++instanceCounter)
             {
                 newInstances[instanceCounter] = m_prefabSystemComponent->InstantiatePrefab(templateToInstantiateId);
             }
diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp
index 7e64fa886c..a6c1e27caf 100644
--- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp
+++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp
@@ -29,7 +29,7 @@ namespace Benchmark
 
             state.ResumeTiming();
 
-            for (int templateCounter = 0; templateCounter < numTemplates; ++templateCounter)
+            for (unsigned int templateCounter = 0; templateCounter < numTemplates; ++templateCounter)
             {
                 m_prefabLoaderInterface->LoadTemplateFromFile(m_paths[templateCounter]);
             }
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index 2cc41adc08..3e499f9853 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -410,7 +410,7 @@ void CSystem::debug_GetCallStack(const char** pFunctions, int& nCount)
     unsigned int numFrames = StackRecorder::Record(frames, nMaxCount, 1);
     SymbolStorage::StackLine* textLines = (SymbolStorage::StackLine*)AZ_ALLOCA(sizeof(SymbolStorage::StackLine)*nMaxCount);
     SymbolStorage::DecodeFrames(frames, numFrames, textLines);
-    for (int i = 0; i < numFrames; i++)
+    for (unsigned int i = 0; i < numFrames; i++)
     {
         pFunctions[i] = textLines[i];
     }
diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp
index c24577a6de..8ea25a2ff0 100644
--- a/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp
+++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpMaterialWrapper.cpp
@@ -194,7 +194,7 @@ namespace AZ
         AZStd::string AssImpMaterialWrapper::GetTextureFileName(MaterialMapType textureType) const
         {
             /// Engine currently doesn't support multiple textures. Right now we only use first texture.
-            int textureIndex = 0;
+            unsigned int textureIndex = 0;
             aiString absTexturePath;
             switch (textureType)
             {
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp
index aadb834aa9..da1db22d5e 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp
@@ -612,10 +612,10 @@ namespace AZ
                 ValueToKeyDataMap valueToKeyDataMap;
                 // Key time can be less than zero, normalize to have zero be the lowest time.
                 double keyOffset = 0;
-                for (int keyIdx = 0; keyIdx < meshMorphAnim->mNumKeys; keyIdx++)
+                for (unsigned int keyIdx = 0; keyIdx < meshMorphAnim->mNumKeys; keyIdx++)
                 {
                     aiMeshMorphKey& key = meshMorphAnim->mKeys[keyIdx];
-                    for (int valIdx = 0; valIdx < key.mNumValuesAndWeights; ++valIdx)
+                    for (unsigned int valIdx = 0; valIdx < key.mNumValuesAndWeights; ++valIdx)
                     {
                         int currentValue = key.mValues[valIdx];
                         KeyData thisKey(key.mWeights[valIdx], key.mTime);
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBitangentStreamImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBitangentStreamImporter.cpp
index 51e0147599..b9b9af1e65 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBitangentStreamImporter.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBitangentStreamImporter.cpp
@@ -89,11 +89,11 @@ namespace AZ
 
                 bitangentStream->SetGenerationMethod(AZ::SceneAPI::DataTypes::TangentGenerationMethod::FromSourceScene);
                 bitangentStream->ReserveContainerSpace(vertexCount);
-                for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
+                for (unsigned int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
                 {
                     const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
 
-                    for (int v = 0; v < mesh->mNumVertices; ++v)
+                    for (unsigned int v = 0; v < mesh->mNumVertices; ++v)
                     {
                         if (!mesh->HasTangentsAndBitangents())
                         {
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp
index d139a1c86c..e8eb5ecf68 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp
@@ -85,7 +85,7 @@ namespace AZ
                 {
                     int sceneMeshIdx = context.m_sourceNode.GetAssImpNode()->mMeshes[nodeMeshIdx];
                     const aiMesh* aiMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[sceneMeshIdx];
-                    for (int animIdx = 0; animIdx < aiMesh->mNumAnimMeshes; animIdx++)
+                    for (unsigned int animIdx = 0; animIdx < aiMesh->mNumAnimMeshes; animIdx++)
                     {
                         aiAnimMesh* aiAnimMesh = aiMesh->mAnimMeshes[animIdx];
                         animToMeshToAnimMeshIndices[aiAnimMesh->mName.C_Str()].emplace_back(nodeMeshIdx, animIdx);
@@ -130,7 +130,7 @@ namespace AZ
                         blendShapeData->ReserveData(
                             aiAnimMesh->mNumVertices, aiAnimMesh->HasTangentsAndBitangents(), uvSetUsedFlags, colorSetUsedFlags);
 
-                        for (int vertIdx = 0; vertIdx < aiAnimMesh->mNumVertices; ++vertIdx)
+                        for (unsigned int vertIdx = 0; vertIdx < aiAnimMesh->mNumVertices; ++vertIdx)
                         {
                             AZ::Vector3 vertex(AssImpSDKWrapper::AssImpTypeConverter::ToVector3(aiAnimMesh->mVertices[vertIdx]));
                    
@@ -184,7 +184,7 @@ namespace AZ
                         }
 
                         // aiAnimMesh just has a list of positions for vertices. The face indices are on the original mesh.
-                        for (int faceIdx = 0; faceIdx < aiMesh->mNumFaces; ++faceIdx)
+                        for (unsigned int faceIdx = 0; faceIdx < aiMesh->mNumFaces; ++faceIdx)
                         {
                             aiFace face = aiMesh->mFaces[faceIdx];
                             DataTypes::IBlendShapeData::Face blendFace;
@@ -199,7 +199,7 @@ namespace AZ
                                     face.mNumIndices);
                                 continue;
                             }
-                            for (int idx = 0; idx < face.mNumIndices; ++idx)
+                            for (unsigned int idx = 0; idx < face.mNumIndices; ++idx)
                             {
                                 blendFace.vertexIndex[idx] = face.mIndices[idx] + vertexOffset;
                             }
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpColorStreamImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpColorStreamImporter.cpp
index 438e56e8ad..4043f529df 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpColorStreamImporter.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpColorStreamImporter.cpp
@@ -56,7 +56,7 @@ namespace AZ
                 const aiScene* scene = context.m_sourceScene.GetAssImpScene();
 
                 // This node has at least one mesh, verify that the color channel counts are the same for all meshes.
-                const int expectedColorChannels = scene->mMeshes[currentNode->mMeshes[0]]->GetNumColorChannels();
+                const unsigned int expectedColorChannels = scene->mMeshes[currentNode->mMeshes[0]]->GetNumColorChannels();
                 const bool allMeshesHaveSameNumberOfColorChannels =
                     AZStd::all_of(currentNode->mMeshes + 1, currentNode->mMeshes + currentNode->mNumMeshes, [scene, expectedColorChannels](const unsigned int meshIndex)
                         {
@@ -80,17 +80,16 @@ namespace AZ
                 const uint64_t vertexCount = GetVertexCountForAllMeshesOnNode(*currentNode, *scene);
 
                 Events::ProcessingResultCombiner combinedVertexColorResults;
-                for (int colorSetIndex = 0; colorSetIndex < expectedColorChannels; ++colorSetIndex)
+                for (unsigned int colorSetIndex = 0; colorSetIndex < expectedColorChannels; ++colorSetIndex)
                 {
-
                     AZStd::shared_ptr vertexColors =
                         AZStd::make_shared();
                     vertexColors->ReserveContainerSpace(vertexCount);
 
-                    for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
+                    for (unsigned int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
                     {
                         const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
-                        for (int v = 0; v < mesh->mNumVertices; ++v)
+                        for (unsigned int v = 0; v < mesh->mNumVertices; ++v)
                         {
                             if (colorSetIndex < mesh->GetNumColorChannels())
                             {
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp
index 4880c8d736..8983c76bac 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpMaterialImporter.cpp
@@ -56,7 +56,7 @@ namespace AZ
                 Events::ProcessingResultCombiner combinedMaterialImportResults;
 
                 AZStd::unordered_map> materialMap;
-                for (int idx = 0; idx < context.m_sourceNode.m_assImpNode->mNumMeshes; ++idx)
+                for (unsigned int idx = 0; idx < context.m_sourceNode.m_assImpNode->mNumMeshes; ++idx)
                 {
                     int meshIndex = context.m_sourceNode.m_assImpNode->mMeshes[idx];
                     const aiMesh* assImpMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[meshIndex];
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpTangentStreamImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpTangentStreamImporter.cpp
index 6f1c364399..fbafd3d24f 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpTangentStreamImporter.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpTangentStreamImporter.cpp
@@ -91,11 +91,11 @@ namespace AZ
 
                 tangentStream->SetGenerationMethod(AZ::SceneAPI::DataTypes::TangentGenerationMethod::FromSourceScene);
                 tangentStream->ReserveContainerSpace(vertexCount);
-                for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
+                for (unsigned int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
                 {
                     const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
 
-                    for (int v = 0; v < mesh->mNumVertices; ++v)
+                    for (unsigned int v = 0; v < mesh->mNumVertices; ++v)
                     {
                         if (!mesh->HasTangentsAndBitangents())
                         {
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp
index 12e13422cf..fc0ac15244 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp
@@ -62,7 +62,7 @@ namespace AZ
                 // so they can be separated by engine code instead.
                 bool foundTextureCoordinates = false;
                 AZStd::array meshesPerTextureCoordinateIndex = {};
-                for (int localMeshIndex = 0; localMeshIndex < currentNode->mNumMeshes; ++localMeshIndex)
+                for (unsigned int localMeshIndex = 0; localMeshIndex < currentNode->mNumMeshes; ++localMeshIndex)
                 {
                     aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[localMeshIndex]];
                     for (int texCoordIndex = 0; texCoordIndex < meshesPerTextureCoordinateIndex.size(); ++texCoordIndex)
@@ -110,7 +110,7 @@ namespace AZ
                     uvMap->ReserveContainerSpace(vertexCount);
                     bool customNameFound = false;
                     AZStd::string name(AZStd::string::format("%s%d", m_defaultNodeName, texCoordIndex));
-                    for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
+                    for (unsigned int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
                     {
                         const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
                         if(mesh->mTextureCoords[texCoordIndex])
@@ -136,7 +136,7 @@ namespace AZ
                             }
                         }
 
-                        for (int v = 0; v < mesh->mNumVertices; ++v)
+                        for (unsigned int v = 0; v < mesh->mNumVertices; ++v)
                         {
                             if (mesh->mTextureCoords[texCoordIndex])
                             {
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.cpp
index a9ab292d25..de94018c9b 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.cpp
@@ -40,7 +40,7 @@ namespace AZ::SceneAPI::SceneBuilder
         // This code re-combines them to match previous FBX SDK behavior,
         // so they can be separated by engine code instead.
         int vertOffset = 0;
-        for (int m = 0; m < currentNode->mNumMeshes; ++m)
+        for (unsigned int m = 0; m < currentNode->mNumMeshes; ++m)
         {
             const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[m]];
 
@@ -50,7 +50,7 @@ namespace AZ::SceneAPI::SceneBuilder
                 assImpMatIndexToLYIndex.insert(AZStd::pair(mesh->mMaterialIndex, lyMeshIndex++));
             }
 
-            for (int vertIdx = 0; vertIdx < mesh->mNumVertices; ++vertIdx)
+            for (unsigned int vertIdx = 0; vertIdx < mesh->mNumVertices; ++vertIdx)
             {
                 AZ::Vector3 vertex(mesh->mVertices[vertIdx].x, mesh->mVertices[vertIdx].y, mesh->mVertices[vertIdx].z);
 
@@ -68,7 +68,7 @@ namespace AZ::SceneAPI::SceneBuilder
                 }
             }
 
-            for (int faceIdx = 0; faceIdx < mesh->mNumFaces; ++faceIdx)
+            for (unsigned int faceIdx = 0; faceIdx < mesh->mNumFaces; ++faceIdx)
             {
                 aiFace face = mesh->mFaces[faceIdx];
                 AZ::SceneAPI::DataTypes::IMeshData::Face meshFace;
@@ -82,7 +82,7 @@ namespace AZ::SceneAPI::SceneBuilder
                         face.mNumIndices);
                     continue;
                 }
-                for (int idx = 0; idx < face.mNumIndices; ++idx)
+                for (unsigned int idx = 0; idx < face.mNumIndices; ++idx)
                 {
                     meshFace.vertexIndex[idx] = face.mIndices[idx] + vertOffset;
                 }
diff --git a/Gems/AWSCore/Code/Source/AWSCoreSystemComponent.cpp b/Gems/AWSCore/Code/Source/AWSCoreSystemComponent.cpp
index c24518a4d7..92a5aa493f 100644
--- a/Gems/AWSCore/Code/Source/AWSCoreSystemComponent.cpp
+++ b/Gems/AWSCore/Code/Source/AWSCoreSystemComponent.cpp
@@ -160,7 +160,7 @@ namespace AWSCore
                 // assigned to a specific CPU starting with the specified CPU.
                 AZ::JobManagerDesc jobManagerDesc{};
                 AZ::JobManagerThreadDesc threadDesc(m_firstThreadCPU, m_threadPriority, m_threadStackSize);
-                for (unsigned int i = 0; i < m_threadCount; ++i)
+                for (int i = 0; i < m_threadCount; ++i)
                 {
                     jobManagerDesc.m_workerThreads.push_back(threadDesc);
                     if (threadDesc.m_cpuId > -1)
diff --git a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp
index e0b4db9165..85dd1469cb 100644
--- a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp
+++ b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionManager.cpp
@@ -139,7 +139,7 @@ namespace AWSCore
         AZStd::chrono::seconds lastSendTimeStamp = AZStd::chrono::seconds(lastSendTimeStampSeconds);
         AZStd::chrono::seconds secondsSinceLastSend =
             AZStd::chrono::duration_cast(AZStd::chrono::system_clock::now().time_since_epoch()) - lastSendTimeStamp;
-        if (secondsSinceLastSend.count() >= delayInSeconds)
+        if (static_cast(secondsSinceLastSend.count()) >= delayInSeconds)
         {
             return true;
         }
diff --git a/Gems/AWSMetrics/Code/Source/MetricsManager.cpp b/Gems/AWSMetrics/Code/Source/MetricsManager.cpp
index 5c4d910658..03e31770ee 100644
--- a/Gems/AWSMetrics/Code/Source/MetricsManager.cpp
+++ b/Gems/AWSMetrics/Code/Source/MetricsManager.cpp
@@ -106,7 +106,7 @@ namespace AWSMetrics
         AZStd::lock_guard lock(m_metricsMutex);
         m_metricsQueue.AddMetrics(metricsEvent);
 
-        if (m_metricsQueue.GetSizeInBytes() >= m_clientConfiguration->GetMaxQueueSizeInBytes())
+        if (m_metricsQueue.GetSizeInBytes() >= static_cast(m_clientConfiguration->GetMaxQueueSizeInBytes()))
         {
             // Flush the metrics queue when the accumulated metrics size hits the limit
             m_waitEvent.release();
@@ -431,7 +431,7 @@ namespace AWSMetrics
                 AZStd::lock_guard lock(m_metricsMutex);
                 m_metricsQueue.AddMetrics(offlineRecords[index]);
 
-                if (m_metricsQueue.GetSizeInBytes() >= m_clientConfiguration->GetMaxQueueSizeInBytes())
+                if (m_metricsQueue.GetSizeInBytes() >= static_cast(m_clientConfiguration->GetMaxQueueSizeInBytes()))
                 {
                     // Flush the metrics queue when the accumulated metrics size hits the limit
                     m_waitEvent.release();
diff --git a/Gems/AWSMetrics/Code/Source/MetricsQueue.cpp b/Gems/AWSMetrics/Code/Source/MetricsQueue.cpp
index ab54fb9e3e..4cc037189a 100644
--- a/Gems/AWSMetrics/Code/Source/MetricsQueue.cpp
+++ b/Gems/AWSMetrics/Code/Source/MetricsQueue.cpp
@@ -216,7 +216,7 @@ namespace AWSMetrics
             return false;
         }
 
-        for (int metricsIndex = 0; metricsIndex < doc.Size(); metricsIndex++)
+        for (rapidjson::SizeType metricsIndex = 0; metricsIndex < doc.Size(); metricsIndex++)
         {
             MetricsEvent metrics;
             if (!metrics.ReadFromJson(doc[metricsIndex]))
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
index 101a506ddc..225b6d5ff6 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp
@@ -252,8 +252,8 @@ int AZ::FontRenderer::GetGlyph(GlyphBitmap* glyphBitmap, int* horizontalAdvance,
     const int textureSlotBufferHeight = glyphBitmap->GetHeight();
 
     // might happen if font characters are too big or cache dimenstions in font.xml is too small ""
-    const bool charWidthFits = iX + m_glyph->bitmap.width <= textureSlotBufferWidth;
-    const bool charHeightFits = iY + m_glyph->bitmap.rows <= textureSlotBufferHeight;
+    const bool charWidthFits = static_cast(iX + m_glyph->bitmap.width) <= textureSlotBufferWidth;
+    const bool charHeightFits = static_cast(iY + m_glyph->bitmap.rows) <= textureSlotBufferHeight;
     const bool charFitsInSlot = charWidthFits && charHeightFits;
     AZ_Error("Font", charFitsInSlot, "Character code %d doesn't fit in font texture; check 'sizeRatio' attribute in font XML or adjust this character's sizing in the font.", characterCode);
 
diff --git a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp
index ec4925fe51..2690a12f24 100644
--- a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp
+++ b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp
@@ -450,7 +450,7 @@ namespace Blast
             const auto buffer = m_asset.GetAccelerator()->fillDebugRender(-1, mode == DebugRenderAabbTreeSegments);
             if (buffer.lineCount)
             {
-                for (int i = 0; i < buffer.lineCount; ++i)
+                for (uint32_t i = 0; i < buffer.lineCount; ++i)
                 {
                     auto& line = buffer.lines[i];
                     AZ::Color color;
diff --git a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h
index 0733862e25..dddd1e275a 100644
--- a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h
+++ b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h
@@ -562,7 +562,7 @@ namespace Blast
     public:
         FakeEntityProvider(uint32_t entityCount)
         {
-            for (int i = 0; i < entityCount; ++i)
+            for (uint32 i = 0; i < entityCount; ++i)
             {
                 m_entities.push_back(AZStd::make_shared());
             }
diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp
index 833f8a14f3..a6368ac088 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp
@@ -1555,7 +1555,7 @@ namespace EMotionFX
         const uint32 geomLODLevel = 0;
         const uint32 numNodes = mSkeleton->GetNumNodes();
 
-        for (int nodeIndex = 0; nodeIndex < numNodes; nodeIndex++)
+        for (uint32 nodeIndex = 0; nodeIndex < numNodes; nodeIndex++)
         {
             // check if this node has a mesh, if not we can skip it
             Mesh* mesh = GetMesh(geomLODLevel, nodeIndex);
diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp b/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp
index b1aa74c397..ea9a1d380f 100644
--- a/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp
+++ b/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp
@@ -116,9 +116,9 @@ namespace UnitTest
             size_t value = 0;
             AZStd::hash_combine(value, seed);
 
-            for (int x = 0; x < width; ++x)
+            for (AZ::u32 x = 0; x < width; ++x)
             {
-                for (int y = 0; y < height; ++y)
+                for (AZ::u32 y = 0; y < height; ++y)
                 {
                     AZStd::hash_combine(value, x);
                     AZStd::hash_combine(value, y);
@@ -141,9 +141,9 @@ namespace UnitTest
             const AZ::u8 pixelValue = 255;
 
             // Image data should be stored inverted on the y axis relative to our engine, so loop backwards through y.
-            for (int y = height - 1; y >= 0; --y)
+            for (int y = static_cast(height) - 1; y >= 0; --y)
             {
-                for (int x = 0; x < width; ++x)
+                for (AZ::u32 x = 0; x < width; ++x)
                 {
                     if ((x == pixelX) && (y == pixelY))
                     {
diff --git a/Gems/ImGui/Code/Source/ImGuiManager.cpp b/Gems/ImGui/Code/Source/ImGuiManager.cpp
index ac3247b6a4..427af6d7dc 100644
--- a/Gems/ImGui/Code/Source/ImGuiManager.cpp
+++ b/Gems/ImGui/Code/Source/ImGuiManager.cpp
@@ -409,7 +409,7 @@ void ImGuiManager::Render()
             break;
 
         case ImGuiResolutionMode::MatchToMaxRenderResolution:
-            if (backBufferWidth <= static_cast(m_renderResolution.x))
+            if (backBufferWidth <= static_cast(m_renderResolution.x))
             {
                 renderRes[0] = backBufferWidth;
                 renderRes[1] = backBufferHeight;
diff --git a/Gems/LmbrCentral/Code/Source/Shape/ShapeGeometryUtil.cpp b/Gems/LmbrCentral/Code/Source/Shape/ShapeGeometryUtil.cpp
index cdb97d2702..3b54447fdd 100644
--- a/Gems/LmbrCentral/Code/Source/Shape/ShapeGeometryUtil.cpp
+++ b/Gems/LmbrCentral/Code/Source/Shape/ShapeGeometryUtil.cpp
@@ -353,10 +353,10 @@ namespace LmbrCentral
             const AZ::u32 sides, const AZ::u32 segments, const AZ::u32 capSegments,
             AZ::u32* indices)
         {
-            const auto capSegmentTipVerts = capSegments > 0 ? 1 : 0;
-            const auto totalSegments = segments + capSegments * 2;
-            const auto numVerts = sides * (totalSegments + 1) + 2 * capSegmentTipVerts;
-            const auto hasEnds = capSegments > 0;
+            const AZ::u32 capSegmentTipVerts = capSegments > 0 ? 1 : 0;
+            const AZ::u32 totalSegments = segments + capSegments * 2;
+            const AZ::u32 numVerts = sides * (totalSegments + 1) + 2 * capSegmentTipVerts;
+            const AZ::u32 hasEnds = capSegments > 0;
 
             // Start Faces (start point of tube)
             // Each starting face shares the same vertex at the beginning of the vertex buffer
@@ -365,8 +365,7 @@ namespace LmbrCentral
             // 1 face per side
             if (hasEnds)
             {
-
-                for (auto i = 0; i < sides; ++i)
+                for (AZ::u32 i = 0; i < sides; ++i)
                 {
                     AZ::u32 a = i + 1;
                     AZ::u32 b = a + 1;
@@ -383,9 +382,9 @@ namespace LmbrCentral
             // Middle Faces
             // 2 triangles per face.
             // 1 face per side.
-            for (auto i = 0; i < totalSegments; ++i)
+            for (AZ::u32 i = 0; i < totalSegments; ++i)
             {
-                for (auto j = 0; j < sides; ++j)
+                for (AZ::u32 j = 0; j < sides; ++j)
                 {
                     // 4 corners for each face
                     // a ------ d
@@ -416,7 +415,7 @@ namespace LmbrCentral
             // 1 face per side
             if (hasEnds)
             {
-                for (auto i = 0; i < sides; ++i)
+                for (AZ::u32 i = 0; i < sides; ++i)
                 {
                     AZ::u32 a = totalSegments * sides + i + 1;
                     AZ::u32 b = a + 1;
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
index 86554c2004..b4c98c39bf 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequence.cpp
@@ -1093,7 +1093,7 @@ void CUiAnimViewSequence::DeselectAllKeys()
     CUiAnimViewSequenceNotificationContext context(this);
 
     CUiAnimViewKeyBundle selectedKeys = GetSelectedKeys();
-    for (int i = 0; i < selectedKeys.GetKeyCount(); ++i)
+    for (unsigned int i = 0; i < selectedKeys.GetKeyCount(); ++i)
     {
         CUiAnimViewKeyHandle keyHandle = selectedKeys.GetKey(i);
         keyHandle.Select(false);
@@ -1237,7 +1237,7 @@ float CUiAnimViewSequence::ClipTimeOffsetForSliding(const float timeOffset)
     for (pTrackIter = tracks.begin(); pTrackIter != tracks.end(); ++pTrackIter)
     {
         CUiAnimViewTrack* pTrack = *pTrackIter;
-        for (int i = 0; i < pTrack->GetKeyCount(); ++i)
+        for (unsigned int i = 0; i < pTrack->GetKeyCount(); ++i)
         {
             CUiAnimViewKeyHandle keyHandle = pTrack->GetKey(i);
 
diff --git a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
index 1d8de3598e..e46073284b 100644
--- a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
+++ b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp
@@ -191,9 +191,9 @@ void SpriteBorderEditor::UpdateSpriteSheetCellInfo(int newNumRows, int newNumCol
 
     // Calculate uniformly sized sprite-sheet cell UVs based on the given
     // row and column cell configuration.
-    for (int row = 0; row < m_numRows; ++row)
+    for (unsigned int row = 0; row < m_numRows; ++row)
     {
-        for (int col = 0; col < m_numCols; ++col)
+        for (unsigned int col = 0; col < m_numCols; ++col)
         {
             AZ::Vector2 min(col / floatNumCols, row / floatNumRows);
             AZ::Vector2 max((col + 1) / floatNumCols, (row + 1) / floatNumRows);
diff --git a/Gems/LyShine/Code/Source/EditorPropertyTypes.cpp b/Gems/LyShine/Code/Source/EditorPropertyTypes.cpp
index 77a9f59732..695412819d 100644
--- a/Gems/LyShine/Code/Source/EditorPropertyTypes.cpp
+++ b/Gems/LyShine/Code/Source/EditorPropertyTypes.cpp
@@ -17,8 +17,9 @@ LyShine::AZu32ComboBoxVec LyShine::GetEnumSpriteIndexList(AZ::EntityId entityId,
 
     int indexCount = 0;
     EBUS_EVENT_ID_RESULT(indexCount, entityId, UiIndexableImageBus, GetImageIndexCount);
+    const AZ::u32 indexCountu32 = static_cast(indexCount);
 
-    if (indexCount > 0 && (indexMax <= indexCount - 1) && indexMin <= indexMax)
+    if (indexCount > 0 && (indexMax <= indexCountu32 - 1) && indexMin <= indexMax)
     {
         for (AZ::u32 i = indexMin; i <= indexMax; ++i)
         {
diff --git a/Gems/LyShine/Code/Source/UiImageComponent.cpp b/Gems/LyShine/Code/Source/UiImageComponent.cpp
index 1e48bdff51..e56d9957b0 100644
--- a/Gems/LyShine/Code/Source/UiImageComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiImageComponent.cpp
@@ -224,9 +224,9 @@ namespace
         IDraw2d::Rounding pixelRounding = isPixelAligned ? IDraw2d::Rounding::Nearest : IDraw2d::Rounding::None;
         float z = 1.0f;
         int i = 0;
-        for (int y = 0; y < numY; ++y)
+        for (uint32 y = 0; y < numY; ++y)
         {
-            for (int x = 0; x < numX; x += 1)
+            for (uint32 x = 0; x < numX; x += 1)
             {
                 AZ::Vector3 point3(xValues[x], yValues[y], z);
                 point3 = transform * point3;
@@ -2030,7 +2030,7 @@ void UiImageComponent::ClipValuesForSlicedLinearFill(uint32 numValues, float* xV
     float previousPercentage = 0;
     int previousIndex = startClip;
     int clampIndex = -1; // to clamp all values greater than m_fillAmount in specified direction.
-    for (int arrayPos = 1; arrayPos < numValues; ++arrayPos)
+    for (uint32 arrayPos = 1; arrayPos < numValues; ++arrayPos)
     {
         int currentIndex = startClip + arrayPos * clipInc;
         float thisPercentage = (clipPosition[currentIndex] - clipPosition[startClip]) / totalLength;
@@ -2102,7 +2102,7 @@ void UiImageComponent::ClipAndRenderForSlicedRadialFill(uint32 numVertsPerSide,
     if (m_fillAmount < 0.5f)
     {
         // Clips against first half line and then rotating line and adds results to render list.
-        for (int currentIndex = 0; currentIndex < totalIndices; currentIndex += 3)
+        for (uint32 currentIndex = 0; currentIndex < totalIndices; currentIndex += 3)
         {
             SVF_P2F_C4B_T2F_F4B intermediateVerts[maxTemporaryVerts];
             uint16 intermediateIndices[maxTemporaryIndices];
@@ -2118,7 +2118,7 @@ void UiImageComponent::ClipAndRenderForSlicedRadialFill(uint32 numVertsPerSide,
     else
     {
         // Clips against first half line and adds results to render list then clips against the second half line and rotating line and also adds those results to render list.
-        for (int currentIndex = 0; currentIndex < totalIndices; currentIndex += 3)
+        for (uint32 currentIndex = 0; currentIndex < totalIndices; currentIndex += 3)
         {
             SVF_P2F_C4B_T2F_F4B intermediateVerts[maxTemporaryVerts];
             uint16 intermediateIndices[maxTemporaryIndices];
@@ -2201,7 +2201,7 @@ void UiImageComponent::ClipAndRenderForSlicedRadialCornerOrEdgeFill(uint32 numVe
 
     int numIndicesToRender = 0;
     int vertexOffset = 0;
-    for (int ix = 0; ix < totalIndices; ix += 3)
+    for (uint32 ix = 0; ix < totalIndices; ix += 3)
     {
         int indicesUsed = ClipToLine(verts, &indices[ix], renderVerts, renderIndices, vertexOffset, numIndicesToRender, lineOrigin, lineEnd);
         numIndicesToRender += indicesUsed;
diff --git a/Gems/LyShine/Code/Source/UiInteractableState.cpp b/Gems/LyShine/Code/Source/UiInteractableState.cpp
index d3440a9354..7e87782d00 100644
--- a/Gems/LyShine/Code/Source/UiInteractableState.cpp
+++ b/Gems/LyShine/Code/Source/UiInteractableState.cpp
@@ -616,7 +616,7 @@ UiInteractableStateFont::FontEffectComboBoxVec UiInteractableStateFont::Populate
     // NOTE: Curently, in order for this to work, when the font is changed we need to do
     // "RefreshEntireTree" to get the combo box list refreshed.
     unsigned int numEffects = m_fontFamily ? m_fontFamily->normal->GetNumEffects() : 0;
-    for (int i = 0; i < numEffects; ++i)
+    for (unsigned int i = 0; i < numEffects; ++i)
     {
         const char* name = m_fontFamily->normal->GetEffectName(i);
         result.push_back(AZStd::make_pair(i, name));
diff --git a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp
index 9668ebf463..a8b678947b 100644
--- a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp
@@ -830,7 +830,7 @@ void UiParticleEmitterComponent::Render(LyShine::IRenderGraph* renderGraph)
     AZ::u32 totalVerticesInserted = 0;
 
     // particlesToRender is the max particles we will render, we could render less if some have zero alpha
-    for (int i = 0; i < particlesToRender; ++i)
+    for (AZ::u32 i = 0; i < particlesToRender; ++i)
     {
         SVF_P2F_C4B_T2F_F4B* firstVertexOfParticle = &m_cachedPrimitive.m_vertices[totalVerticesInserted];
 
@@ -1827,7 +1827,7 @@ void UiParticleEmitterComponent::ResetParticleBuffers()
 
     const int verticesPerParticle = 4;
     int baseIndex = 0;
-    for (int i = 0; i < numIndices; i += indicesPerParticle)
+    for (AZ::u32 i = 0; i < numIndices; i += indicesPerParticle)
     {
         m_cachedPrimitive.m_indices[i + 0] = 0 + baseIndex;
         m_cachedPrimitive.m_indices[i + 1] = 1 + baseIndex;
diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp
index d95b15622b..87eb4524a2 100644
--- a/Gems/LyShine/Code/Source/UiTextComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp
@@ -3527,7 +3527,7 @@ UiTextComponent::FontEffectComboBoxVec UiTextComponent::PopulateFontEffectList()
     if (m_font)
     {
         unsigned int numEffects = m_font->GetNumEffects();
-        for (int i = 0; i < numEffects; ++i)
+        for (unsigned int i = 0; i < numEffects; ++i)
         {
             const char* name = m_font->GetEffectName(i);
             result.push_back(AZStd::make_pair(i, name));
diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
index 7e1c3630cb..992a2a3697 100644
--- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
+++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp
@@ -697,7 +697,7 @@ namespace PhysXDebug
         if (GetCurrentPxScene())
         {
             // Reserve vector capacity
-            const int numTriangles = rb.getNbTriangles();
+            const physx::PxU32 numTriangles = static_cast(rb.getNbTriangles());
             m_trianglePoints.reserve(numTriangles * 3);
             m_triangleColors.reserve(numTriangles * 3);
 
@@ -731,7 +731,7 @@ namespace PhysXDebug
 
         if (GetCurrentPxScene())
         {
-            const int numLines = rb.getNbLines();
+            const physx::PxU32 numLines = static_cast(rb.getNbLines());
 
             // Reserve vector capacity
             m_linePoints.reserve(numLines * 2);

From eb3e0b0998463b52e877ab4d2dd63d3c72dfe1b6 Mon Sep 17 00:00:00 2001
From: pappeste 
Date: Thu, 24 Jun 2021 18:40:11 -0700
Subject: [PATCH 065/205] updates after merging development

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp      | 2 +-
 .../SceneBuilder/Importers/AssImpAnimationImporter.cpp        | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp
index 9d35081895..54e53a6ebc 100644
--- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp
+++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp
@@ -33,7 +33,7 @@ namespace Benchmark
             AZStd::vector> spawnables;
             spawnables.reserve(numSpawnables);
             
-            for (int spwanableCounter = 0; spwanableCounter < numSpawnables; ++spwanableCounter)
+            for (unsigned int spwanableCounter = 0; spwanableCounter < numSpawnables; ++spwanableCounter)
             {
                 AZStd::unique_ptr spawnable = AZStd::make_unique();
                 AzToolsFramework::Prefab::SpawnableUtils::CreateSpawnable(*spawnable, prefabDom);
diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp
index da1db22d5e..150a50138e 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp
@@ -445,11 +445,11 @@ namespace AZ
 
                 AZStd::unordered_set boneList;
 
-                for (int meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex)
+                for (unsigned int meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex)
                 {
                     aiMesh* mesh = scene->mMeshes[meshIndex];
 
-                    for (int boneIndex = 0; boneIndex < mesh->mNumBones; ++boneIndex)
+                    for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; ++boneIndex)
                     {
                         aiBone* bone = mesh->mBones[boneIndex];
 

From 9f18b6f1be67a6cfadce79047d8a8d77e8adaa74 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 19:58:46 -0700
Subject: [PATCH 066/205] fixes for new code

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../SceneBuilder/Importers/AssImpImporterUtilities.cpp        | 4 ++--
 Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp       | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp
index 81feff7d69..861d6dd85c 100644
--- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp
+++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp
@@ -105,7 +105,7 @@ namespace AZ
                         nodesWithNoMesh.emplace(currentNode->mName.C_Str());
                     }
 
-                    for (int childIndex = 0; childIndex < currentNode->mNumChildren; ++childIndex)
+                    for (unsigned int childIndex = 0; childIndex < currentNode->mNumChildren; ++childIndex)
                     {
                         queue.push(currentNode->mChildren[childIndex]);
                     }
@@ -176,7 +176,7 @@ namespace AZ
                     return true;
                 }
 
-                for (int childIndex = 0; childIndex < node->mNumChildren; ++childIndex)
+                for (unsigned int childIndex = 0; childIndex < node->mNumChildren; ++childIndex)
                 {
                     const aiNode* childNode = node->mChildren[childIndex];
                     if (RecursiveHasChildBone(childNode, boneByNameMap))
diff --git a/Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp
index e9f5d04314..b45cee6948 100644
--- a/Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp
+++ b/Gems/LyShine/Code/Editor/Animation/UiAVEventsDialog.cpp
@@ -352,7 +352,7 @@ int UiAVEventsModel::GetNumberOfUsageAndFirstTimeUsed(const char* eventName, flo
         {
             CUiAnimViewTrack* pTrack = tracks.GetTrack(currentTrack);
 
-            for (int currentKey = 0; currentKey < pTrack->GetKeyCount(); ++currentKey)
+            for (unsigned int currentKey = 0; currentKey < pTrack->GetKeyCount(); ++currentKey)
             {
                 CUiAnimViewKeyHandle keyHandle = pTrack->GetKey(currentKey);
 

From c85e5a688668da4e2c1a4aff6564a0ca8d5fded1 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Thu, 5 Aug 2021 21:49:00 -0700
Subject: [PATCH 067/205] Some more build fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Platform/Android/GridMate/Carrier/Utils_Android.cpp       | 4 ++--
 .../Platform/Linux/GridMate/Session/LANSession_Linux.cpp      | 2 ++
 .../GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp | 2 ++
 Code/Legacy/CrySystem/LocalizedStringManager.cpp              | 4 ++--
 4 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp b/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp
index 87bb0c3cda..f48e2c2da8 100644
--- a/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp
+++ b/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp
@@ -18,9 +18,9 @@
 
 namespace GridMate
 {
-    string Utils::GetMachineAddress(int familyType)
+    AZStd::string Utils::GetMachineAddress(int familyType)
     {
-        string machineName;
+        AZStd::string machineName;
         struct RTMRequest
         {
             nlmsghdr m_msghdr;
diff --git a/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp b/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp
index 05fb56dfc1..ac887bb624 100644
--- a/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp
+++ b/Code/Framework/GridMate/Platform/Linux/GridMate/Session/LANSession_Linux.cpp
@@ -8,6 +8,8 @@
 
 #include 
 
+#include 
+
 namespace GridMate
 {
     namespace Platform
diff --git a/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp b/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp
index 05fb56dfc1..ac887bb624 100644
--- a/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp
+++ b/Code/Framework/GridMate/Platform/Mac/GridMate/Session/LANSession_Mac.cpp
@@ -8,6 +8,8 @@
 
 #include 
 
+#include 
+
 namespace GridMate
 {
     namespace Platform
diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
index 6013b44f92..68a8a6659b 100644
--- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp
+++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp
@@ -2337,8 +2337,8 @@ void InternalFormatStringMessage(AZStd::string& outString, const AZStd::string&
     static const char tokens2[3] = { token, token, '\0' };
 
     int maxArgUsed = 0;
-    int lastPos = 0;
-    int curPos = 0;
+    size_t lastPos = 0;
+    size_t curPos = 0;
     const int sourceLen = static_cast(sString.length());
     while (true)
     {

From ae9d15c977f1394f5783dd76dadaa407031bbd28 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 6 Aug 2021 09:59:35 -0700
Subject: [PATCH 068/205] Mac/iOS fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
index 5555704040..5b2d2af34f 100644
--- a/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
+++ b/Code/Framework/AzCore/Platform/Mac/AzCore/IPC/SharedMemory_Mac.cpp
@@ -29,20 +29,19 @@ namespace AZ
         return errno;
     }
 
-    void ComposeMutexName(char* dest, size_t length, const char* name)
+    void ComposeName(char* dest, size_t length, const char* name, const char* suffix)
     {
-        azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
-
         // sem_open doesn't support paths bigger than 31, so call it s_Mtx.
         // While this is enough for Profiler, maybe the code should be smarter
         // and trim the name instead
-        azsnprintf(dest, length, "/tmp/%s_Mtx", name);
+        azsnprintf(dest, length, "/tmp/%s_%s", name, suffix);
     }
 
     SharedMemory_Common::CreateResult SharedMemory_Mac::Create(const char* name, unsigned int size, bool openIfCreated)
     {
         char fullName[256];
-        ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name);
+        azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
+        ComposeName(fullName, AZ_ARRAY_SIZE(fullName), name, "Mtx");
 
         m_globalMutex = sem_open(fullName, O_CREAT | O_EXCL, 0600, 1);
         int error = errno;
@@ -59,7 +58,7 @@ namespace AZ
         }
 
         // Create the file mapping.
-        azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name);
+        ComposeName(fullName, AZ_ARRAY_SIZE(fullName), name, "Data");
         m_mapHandle = shm_open(fullName, O_RDWR | O_CREAT | O_EXCL, 0600);
         error = errno;
         if (error == EEXIST)
@@ -80,7 +79,8 @@ namespace AZ
     bool SharedMemory_Mac::Open(const char* name)
     {
         char fullName[256];
-        ComposeMutexName(fullName, AZ_ARRAY_SIZE(fullName), name);
+        azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
+        ComposeName(fullName, AZ_ARRAY_SIZE(fullName), name, "Mtx");
 
         m_globalMutex = sem_open(fullName, 0);
         AZ_Warning("AZSystem", m_globalMutex != nullptr, "Failed to open OS mutex [%s]\n", m_name);
@@ -90,7 +90,7 @@ namespace AZ
             return false;
         }
 
-        azsnprintf(fullName, AZ_ARRAY_SIZE(fullName), "%s_Data", name);
+        ComposeName(fullName, AZ_ARRAY_SIZE(fullName), name, "Data");
         m_mapHandle = shm_open(fullName, O_RDWR, 0600);
         if (m_mapHandle == -1)
         {

From 8adf8fd7a11309bc4388ab5d63538a1b6d8bfbd9 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 6 Aug 2021 10:00:58 -0700
Subject: [PATCH 069/205] PR comments

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Framework/AzCore/AzCore/std/string/conversions.h     | 8 ++++----
 .../Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp  | 2 ++
 2 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index 473c327143..c5c9b29cdb 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -338,9 +338,9 @@ namespace AZStd
         if (srcLen > 0)
         {
             char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen);
-            if (endStr < (dest + destSize) && *(endStr - 1) != '\0')
+            if (endStr < (dest + destSize))
             {
-                *endStr = '\0'; // copy null terminator
+                *endStr = '\0'; // null terminator
             }
         }
     }
@@ -495,9 +495,9 @@ namespace AZStd
         if (srcLen > 0)
         {
             wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen);
-            if (endWStr < (dest + destSize) && *(endWStr - 1) != '\0')
+            if (endWStr < (dest + destSize))
             {
-                *endWStr = '\0'; // copy null terminator
+                *endWStr = '\0'; // null terminator
             }
         }
     }
diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
index 20c126f7a8..d9149bdb44 100644
--- a/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
+++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IPC/SharedMemory_Windows.cpp
@@ -31,6 +31,7 @@ namespace AZ
 
     SharedMemory_Common::CreateResult SharedMemory_Windows::Create(const char* name, unsigned int size, bool openIfCreated)
     {
+        azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
         AZStd::fixed_wstring<256> fullName;
         ComposeName(fullName, name, L"Mutex");
 
@@ -67,6 +68,7 @@ namespace AZ
 
     bool SharedMemory_Windows::Open(const char* name)
     {
+        azstrncpy(m_name, AZ_ARRAY_SIZE(m_name), name, strlen(name));
         AZStd::fixed_wstring<256> fullName;
         ComposeName(fullName, name, L"Mutex");
 

From 03cf71b12d7322ac15e6dbcf9a00cdaef4e8ecea Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 6 Aug 2021 10:01:20 -0700
Subject: [PATCH 070/205] android fixes

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../Platform/Android/GridMate/Carrier/Utils_Android.cpp         | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp b/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp
index f48e2c2da8..75259fbe64 100644
--- a/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp
+++ b/Code/Framework/GridMate/Platform/Android/GridMate/Carrier/Utils_Android.cpp
@@ -67,7 +67,7 @@ namespace GridMate
 
                 char address[INET6_ADDRSTRLEN] = { 0 };
                 bool isLoopback = false;
-                string devname;
+                AZStd::string devname;
                 for (int rtattrlen = IFA_PAYLOAD(nlmp); RTA_OK(rtatp, rtattrlen); rtatp = RTA_NEXT(rtatp, rtattrlen))
                 {
                     if (rtatp->rta_type == IFA_ADDRESS)

From db942e2cf5b70bcf63992ba5631a8a086d534307 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 6 Aug 2021 10:36:53 -0700
Subject: [PATCH 071/205] addresses PR comments

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/ViewportTitleDlg.cpp | 24 ++++++++++++------------
 1 file changed, 12 insertions(+), 12 deletions(-)

diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp
index cbf2958eea..b9c86bf72b 100644
--- a/Code/Editor/ViewportTitleDlg.cpp
+++ b/Code/Editor/ViewportTitleDlg.cpp
@@ -449,21 +449,21 @@ void CViewportTitleDlg::AddFOVMenus(QMenu* menu, std::function call
 
     if (!customPresets.empty())
     {
-        for (size_t i = 0; i < customPresets.size(); ++i)
+        for (const QString& customPreset : customPresets)
         {
-            if (customPresets[static_cast(i)].isEmpty())
+            if (customPreset.isEmpty())
             {
                 break;
             }
 
             float fov = gSettings.viewports.fDefaultFov;
             bool ok;
-            float f = customPresets[static_cast(i)].toDouble(&ok);
+            float f = customPreset.toDouble(&ok);
             if (ok)
             {
                 fov = std::max(1.0f, f);
                 fov = std::min(120.0f, f);
-                QAction* action = menu->addAction(customPresets[static_cast(i)]);
+                QAction* action = menu->addAction(customPreset);
                 connect(action, &QAction::triggered, action, [fov, callback](){ callback(fov); });
             }
         }
@@ -535,15 +535,15 @@ void CViewportTitleDlg::AddAspectRatioMenus(QMenu* menu, std::functionaddSeparator();
 
-    for (size_t i = 0; i < customPresets.size(); ++i)
+    for (const QString& customPreset : customPresets)
     {
-        if (customPresets[static_cast(i)].isEmpty())
+        if (customPreset.isEmpty())
         {
             break;
         }
 
         static QRegularExpression regex(QStringLiteral("^(\\d+):(\\d+)$"));
-        QRegularExpressionMatch matches = regex.match(customPresets[static_cast(i)]);
+        QRegularExpressionMatch matches = regex.match(customPreset);
         if (matches.hasMatch())
         {
             bool ok;
@@ -551,7 +551,7 @@ void CViewportTitleDlg::AddAspectRatioMenus(QMenu* menu, std::functionaddAction(customPresets[static_cast(i)]);
+            QAction* action = menu->addAction(customPreset);
             connect(action, &QAction::triggered, action, [width, height, callback]() {callback(width, height); });
         }
     }
@@ -666,15 +666,15 @@ void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::functionaddSeparator();
 
-    for (size_t i = 0; i < customPresets.size(); ++i)
+    for (const QString& customPreset : customPresets)
     {
-        if (customPresets[static_cast(i)].isEmpty())
+        if (customPreset.isEmpty())
         {
             break;
         }
 
         static QRegularExpression regex(QStringLiteral("^(\\d+) x (\\d+)$"));
-        QRegularExpressionMatch matches = regex.match(customPresets[static_cast(i)]);
+        QRegularExpressionMatch matches = regex.match(customPreset);
         if (matches.hasMatch())
         {
             bool ok;
@@ -682,7 +682,7 @@ void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::functionaddAction(customPresets[static_cast(i)]);
+            QAction* action = menu->addAction(customPreset);
             connect(action, &QAction::triggered, action, [width, height, callback](){ callback(width, height); });
         }
     }

From d6744690ee281aeda4dfc0759412d2711db13a98 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 6 Aug 2021 15:10:21 -0700
Subject: [PATCH 072/205] platform.h cleanup

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/Include/IObjectManager.h          |   1 +
 Code/Editor/Objects/ObjectLoader.h            |   2 +
 .../PerforcePlugin/PerforceSourceControl.cpp  |   1 +
 Code/Legacy/CryCommon/AndroidSpecific.h       |   1 -
 Code/Legacy/CryCommon/AppleSpecific.h         |   7 -
 Code/Legacy/CryCommon/BitFiddling.h           |  11 -
 Code/Legacy/CryCommon/CryArray.h              |  18 +-
 Code/Legacy/CryCommon/CryAssert.h             |   3 +-
 Code/Legacy/CryCommon/CrySizer.h              |   4 +-
 .../Legacy/CryCommon/CryThreadImpl_pthreads.h |   8 +-
 Code/Legacy/CryCommon/CryThreadImpl_windows.h |   2 +-
 Code/Legacy/CryCommon/CryThread_pthreads.h    |   2 +-
 Code/Legacy/CryCommon/CryThread_windows.h     |   2 +-
 Code/Legacy/CryCommon/IFunctorBase.h          |   1 +
 Code/Legacy/CryCommon/IMaterial.h             |   1 +
 Code/Legacy/CryCommon/ISystem.h               |   2 +-
 Code/Legacy/CryCommon/Linux32Specific.h       |   1 -
 Code/Legacy/CryCommon/Linux64Specific.h       |   1 -
 Code/Legacy/CryCommon/LinuxSpecific.h         |  17 -
 Code/Legacy/CryCommon/MTPseudoRandom.cpp      |   2 +-
 Code/Legacy/CryCommon/ProjectDefines.h        | 186 ++-----
 Code/Legacy/CryCommon/Win32specific.h         |   1 -
 Code/Legacy/CryCommon/Win64specific.h         |   1 -
 Code/Legacy/CryCommon/WinBase.cpp             |  41 --
 Code/Legacy/CryCommon/platform.h              | 477 ++----------------
 Code/Legacy/CryCommon/platform_impl.cpp       |  53 --
 Code/Legacy/CryCommon/smartptr.h              |  13 +-
 Code/Legacy/CrySystem/IDebugCallStack.cpp     |   2 +-
 Code/Legacy/CrySystem/SystemInit.cpp          |   2 +-
 Code/Legacy/CrySystem/SystemWin32.cpp         |  39 +-
 .../CrySystem/ViewSystem/ViewSystem.cpp       |   2 +-
 Code/Legacy/CrySystem/XML/xml.cpp             |   2 +-
 .../Source/Animation/UiAnimationSystem.cpp    |   8 +-
 Gems/Maestro/Code/Source/Cinematics/Movie.cpp |   8 +-
 34 files changed, 145 insertions(+), 777 deletions(-)

diff --git a/Code/Editor/Include/IObjectManager.h b/Code/Editor/Include/IObjectManager.h
index ce9d69681b..efc1955a56 100644
--- a/Code/Editor/Include/IObjectManager.h
+++ b/Code/Editor/Include/IObjectManager.h
@@ -14,6 +14,7 @@
 #include 
 #include 
 #include 
+#include 
 
 // forward declarations.
 class CEntityObject;
diff --git a/Code/Editor/Objects/ObjectLoader.h b/Code/Editor/Objects/ObjectLoader.h
index ccfaeb78f0..fc526970dd 100644
--- a/Code/Editor/Objects/ObjectLoader.h
+++ b/Code/Editor/Objects/ObjectLoader.h
@@ -15,6 +15,8 @@
 #include "Util/GuidUtil.h"
 #include "ErrorReport.h"
 
+#include 
+
 class CPakFile;
 class CErrorRecord;
 struct IObjectManager;
diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp
index 581f9a576d..1ea70e8c22 100644
--- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp
+++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp
@@ -9,6 +9,7 @@
 #include "CryFile.h"
 #include "PerforceSourceControl.h"
 #include "PasswordDlg.h"
+#include 
 
 #include 
 #include 
diff --git a/Code/Legacy/CryCommon/AndroidSpecific.h b/Code/Legacy/CryCommon/AndroidSpecific.h
index 0cb4a6786c..a0f57553ca 100644
--- a/Code/Legacy/CryCommon/AndroidSpecific.h
+++ b/Code/Legacy/CryCommon/AndroidSpecific.h
@@ -35,7 +35,6 @@
 // to what some structs/classes need.
 #define CRY_FORCE_MALLOC_NEW_ALIGN
 
-#define DEBUG_BREAK raise(SIGTRAP)
 #define RC_EXECUTABLE "rc"
 #define USE_CRT 1
 #define SIZEOF_PTR 4
diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h
index 4d17c18bac..ed76de8986 100644
--- a/Code/Legacy/CryCommon/AppleSpecific.h
+++ b/Code/Legacy/CryCommon/AppleSpecific.h
@@ -18,7 +18,6 @@
 #endif
 
 
-#define DEBUG_BREAK __builtin_trap()
 #define RC_EXECUTABLE "rc"
 
 //////////////////////////////////////////////////////////////////////////
@@ -52,12 +51,6 @@
 #define __COUNTER__ __LINE__
 #endif
 
-#ifdef __FUNC__
-#undef __FUNC__
-#endif
-
-#define __FUNC__ __func__
-
 typedef void*                               LPVOID;
 #define VOID                    void
 #define PVOID                               void*
diff --git a/Code/Legacy/CryCommon/BitFiddling.h b/Code/Legacy/CryCommon/BitFiddling.h
index 901dd0a49a..342aad9a82 100644
--- a/Code/Legacy/CryCommon/BitFiddling.h
+++ b/Code/Legacy/CryCommon/BitFiddling.h
@@ -36,7 +36,6 @@ ILINE uint32 countLeadingZeros32(uint32 x)
 {
     DWORD result = 32 ^ 31; // assumes result is unmodified if _BitScanReverse returns 0
     _BitScanReverse(&result, x);
-    PREFAST_SUPPRESS_WARNING(6102);
     result ^= 31; // needed because the index is from LSB (whereas all other implementations are from MSB)
     return result;
 }
@@ -73,16 +72,6 @@ inline bool IsPowerOfTwo(TInteger x)
     return (x & (x - 1)) == 0;
 }
 
-// compile time version of IsPowerOfTwo, useful for STATIC_CHECK
-template 
-struct IsPowerOfTwoCompileTime
-{
-    enum
-    {
-        IsPowerOfTwo = ((nValue & (nValue - 1)) == 0)
-    };
-};
-
 inline uint32 NextPower2(uint32 n)
 {
     n--;
diff --git a/Code/Legacy/CryCommon/CryArray.h b/Code/Legacy/CryCommon/CryArray.h
index b304df28af..5b4684fdd2 100644
--- a/Code/Legacy/CryCommon/CryArray.h
+++ b/Code/Legacy/CryCommon/CryArray.h
@@ -15,24 +15,10 @@
 
 //---------------------------------------------------------------------------
 // Convenient iteration macros
-#define for_iter(IT, it, b, e)          for (IT it = (b), _e = (e); it != _e; ++it)
-#define for_container(CT, it, cont) for_iter (CT::iterator, it, (cont).begin(), (cont).end())
 
 #define for_ptr(T, it, b, e)                for (T* it = (b), * _e = (e); it != _e; ++it)
-#define for_array_ptr(T, it, arr)       for_ptr (T, it, (arr).begin(), (arr).end())
-
-#define for_array(i, arr)                       for (int i = 0, _e = (arr).size(); i < _e; i++)
-#define for_all(cont)                               for_array (_i, cont) cont[_i]
-
-//---------------------------------------------------------------------------
-// Stack array helper
-#define ALIGNED_STACK_ARRAY(T, name, size, alignment)           \
-    PREFAST_SUPPRESS_WARNING(6255)                              \
-    T * name = (T*) alloca((size) * sizeof(T) + alignment - 1); \
-    name = Align(name, alignment);
-
-#define STACK_ARRAY(T, name, size)                 \
-    ALIGNED_STACK_ARRAY(T, name, size, alignof(T)) \
+#define for_array_ptr(T, it, arr)           for_ptr (T, it, (arr).begin(), (arr).end())
+#define for_array(i, arr)                   for (int i = 0, _e = (arr).size(); i < _e; i++)
 
 //---------------------------------------------------------------------------
 // Specify semantics for moving objects.
diff --git a/Code/Legacy/CryCommon/CryAssert.h b/Code/Legacy/CryCommon/CryAssert.h
index 1cb5d37c43..1494654d87 100644
--- a/Code/Legacy/CryCommon/CryAssert.h
+++ b/Code/Legacy/CryCommon/CryAssert.h
@@ -71,7 +71,6 @@
 #if defined(USE_CRY_ASSERT) && CRYASSERT_H_TRAIT_USE_CRY_ASSERT_MESSAGE
 void CryAssertTrace(const char*, ...);
 bool CryAssert(const char*, const char*, unsigned int, bool*);
-void CryDebugBreak();
 
     #define CRY_ASSERT(condition) CRY_ASSERT_MESSAGE(condition, NULL)
 
@@ -86,7 +85,7 @@ void CryDebugBreak();
             CryAssertTrace parenthese_message;                               \
             if (CryAssert(#condition, __FILE__, __LINE__, &s_bIgnoreAssert)) \
             {                                                                \
-                DEBUG_BREAK;                                                 \
+                AZ::Debug::Trace::Break();                                   \
             }                                                                \
         }                                                                    \
     } while (0)
diff --git a/Code/Legacy/CryCommon/CrySizer.h b/Code/Legacy/CryCommon/CrySizer.h
index 9301360bd5..583de5bee8 100644
--- a/Code/Legacy/CryCommon/CrySizer.h
+++ b/Code/Legacy/CryCommon/CrySizer.h
@@ -581,7 +581,7 @@ protected:
 
 // use this to push (and automatically pop) the sizer component name at the beginning of the
 // getSize() function
-#define SIZER_COMPONENT_NAME(pSizerPointer, szComponentName) PREFAST_SUPPRESS_WARNING(6246) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, false)
-#define SIZER_SUBCOMPONENT_NAME(pSizerPointer, szComponentName) PREFAST_SUPPRESS_WARNING(6246) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, true)
+#define SIZER_COMPONENT_NAME(pSizerPointer, szComponentName) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, false)
+#define SIZER_SUBCOMPONENT_NAME(pSizerPointer, szComponentName) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, true)
 
 #endif // CRYINCLUDE_CRYCOMMON_CRYSIZER_H
diff --git a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
index c94d4fca90..c3dee7339f 100644
--- a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
+++ b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
@@ -14,13 +14,7 @@
 
 #include "CryThread_pthreads.h"
 
-#if PLATFORM_SUPPORTS_THREADLOCAL
-THREADLOCAL CrySimpleThreadSelf
-* CrySimpleThreadSelf::m_Self = NULL;
-#else
-TLS_DEFINE(CrySimpleThreadSelf*, g_CrySimpleThreadSelf)
-#endif
-
+AZ_THREAD_LOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL;
 
 //////////////////////////////////////////////////////////////////////////
 // CryEvent(Timed) implementation
diff --git a/Code/Legacy/CryCommon/CryThreadImpl_windows.h b/Code/Legacy/CryCommon/CryThreadImpl_windows.h
index 5cf970414d..4ddbaedac5 100644
--- a/Code/Legacy/CryCommon/CryThreadImpl_windows.h
+++ b/Code/Legacy/CryCommon/CryThreadImpl_windows.h
@@ -20,7 +20,7 @@ struct SThreadNameDesc
     DWORD dwFlags;
 };
 
-THREADLOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL;
+AZ_THREAD_LOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL;
 
 //////////////////////////////////////////////////////////////////////////
 CryEvent::CryEvent()
diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h
index 72b29344ec..2c6b389dbb 100644
--- a/Code/Legacy/CryCommon/CryThread_pthreads.h
+++ b/Code/Legacy/CryCommon/CryThread_pthreads.h
@@ -672,7 +672,7 @@ protected:
         m_Self = pSelf;
     }
 private:
-    static THREADLOCAL CrySimpleThreadSelf* m_Self;
+    static AZ_THREAD_LOCAL CrySimpleThreadSelf* m_Self;
 
 #else
 
diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h
index cc09cc530b..98517133c1 100644
--- a/Code/Legacy/CryCommon/CryThread_windows.h
+++ b/Code/Legacy/CryCommon/CryThread_windows.h
@@ -189,7 +189,7 @@ public:
     virtual ~CrySimpleThreadSelf();
 protected:
     void StartThread(unsigned (__stdcall * func)(void*), void* argList);
-    static THREADLOCAL CrySimpleThreadSelf* m_Self;
+    static AZ_THREAD_LOCAL CrySimpleThreadSelf* m_Self;
 private:
     CrySimpleThreadSelf(const CrySimpleThreadSelf&);
     CrySimpleThreadSelf& operator = (const CrySimpleThreadSelf&);
diff --git a/Code/Legacy/CryCommon/IFunctorBase.h b/Code/Legacy/CryCommon/IFunctorBase.h
index 2a8af50d33..1ac37a0e47 100644
--- a/Code/Legacy/CryCommon/IFunctorBase.h
+++ b/Code/Legacy/CryCommon/IFunctorBase.h
@@ -14,6 +14,7 @@
 #define CRYINCLUDE_CRYCOMMON_IFUNCTORBASE_H
 #pragma once
 
+#include 
 
 // Base class for functor storage.
 // Not intended for direct usage.
diff --git a/Code/Legacy/CryCommon/IMaterial.h b/Code/Legacy/CryCommon/IMaterial.h
index 1faee0eef9..f1967324d8 100644
--- a/Code/Legacy/CryCommon/IMaterial.h
+++ b/Code/Legacy/CryCommon/IMaterial.h
@@ -37,6 +37,7 @@ struct IRenderMesh;
 #include 
 #include 
 #include 
+#include 
 
 #ifdef MAX_SUB_MATERIALS
 // This checks that the values are in sync in the different files.
diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h
index d934995b4d..7cea690687 100644
--- a/Code/Legacy/CryCommon/ISystem.h
+++ b/Code/Legacy/CryCommon/ISystem.h
@@ -1419,7 +1419,7 @@ namespace Detail
         } DummyStaticInstance;                                                           \
         if (!(gEnv->pConsole != 0 ? gEnv->pConsole->Register(&DummyStaticInstance) : 0)) \
         {                                                                                \
-            DEBUG_BREAK;                                                                 \
+            AZ::Debug::Trace::Break();                                                   \
             CryFatalError("Can not register dummy CVar");                                \
         }                                                                                \
     } while (0)
diff --git a/Code/Legacy/CryCommon/Linux32Specific.h b/Code/Legacy/CryCommon/Linux32Specific.h
index b3f06a80b7..e66838f431 100644
--- a/Code/Legacy/CryCommon/Linux32Specific.h
+++ b/Code/Legacy/CryCommon/Linux32Specific.h
@@ -18,7 +18,6 @@
 #define _CPU_X86
 //#define _CPU_SSE
 
-#define DEBUG_BREAK raise(SIGTRAP)
 #define RC_EXECUTABLE "rc"
 #define USE_CRT 1
 #define SIZEOF_PTR 4
diff --git a/Code/Legacy/CryCommon/Linux64Specific.h b/Code/Legacy/CryCommon/Linux64Specific.h
index 11b526ee4b..0aa9321025 100644
--- a/Code/Legacy/CryCommon/Linux64Specific.h
+++ b/Code/Legacy/CryCommon/Linux64Specific.h
@@ -20,7 +20,6 @@
 #define _CPU_AMD64
 #define _CPU_SSE
 
-#define DEBUG_BREAK ::raise(SIGTRAP)
 #define RC_EXECUTABLE "rc"
 #define USE_CRT 1
 #define SIZEOF_PTR 8
diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h
index 5fc1f7b801..cbffae5957 100644
--- a/Code/Legacy/CryCommon/LinuxSpecific.h
+++ b/Code/Legacy/CryCommon/LinuxSpecific.h
@@ -42,23 +42,6 @@
 #include 
 #include 
 
-#ifdef __FUNC__
-#undef __FUNC__
-#endif
-#if defined(__GNUC__) || defined(__clang__)
-#define __FUNC__ __func__
-#else
-#define __FUNC__                                             \
-    ({                                                       \
-         static char __f[sizeof(__PRETTY_FUNCTION__) + 1];   \
-         strcpy(__f, __PRETTY_FUNCTION__);                   \
-         char* __p = (char*)strchr(__f, '(');                \
-         *__p = 0;                                           \
-         while (*(__p) != ' ' && __p != (__f - 1)) {--__p; } \
-         (__p + 1);                                          \
-     })
-#endif
-
 typedef void*                               LPVOID;
 #define VOID                    void
 #define PVOID                               void*
diff --git a/Code/Legacy/CryCommon/MTPseudoRandom.cpp b/Code/Legacy/CryCommon/MTPseudoRandom.cpp
index 6f163e682f..f8a3950ff0 100644
--- a/Code/Legacy/CryCommon/MTPseudoRandom.cpp
+++ b/Code/Legacy/CryCommon/MTPseudoRandom.cpp
@@ -63,7 +63,7 @@ void CMTRand_int32::seed(const uint32* array, int size)   // init by array
     }
     for (int k = n - 1; k; --k)
     {
-        PREFAST_SUPPRESS_WARNING(6385)  PREFAST_SUPPRESS_WARNING(6386)  m_nState[i] = (m_nState[i] ^ ((m_nState[i - 1] ^ (m_nState[i - 1] >> 30)) * 1566083941UL)) - i;
+        m_nState[i] = (m_nState[i] ^ ((m_nState[i - 1] ^ (m_nState[i - 1] >> 30)) * 1566083941UL)) - i;
         if ((++i) == n)
         {
             m_nState[0] = m_nState[n - 1];
diff --git a/Code/Legacy/CryCommon/ProjectDefines.h b/Code/Legacy/CryCommon/ProjectDefines.h
index 3d635c491c..eda5bb8b5f 100644
--- a/Code/Legacy/CryCommon/ProjectDefines.h
+++ b/Code/Legacy/CryCommon/ProjectDefines.h
@@ -16,10 +16,6 @@
 #include "BaseTypes.h"
 #include 
 
-#if defined(_RELEASE) && !defined(RELEASE)
-    #define RELEASE
-#endif
-
 // Section dictionary
 #if defined(AZ_RESTRICTED_PLATFORM)
 #define PROJECTDEFINES_H_SECTION_STATS_AGENT 1
@@ -31,57 +27,51 @@
     #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_STATS_AGENT
     #include AZ_RESTRICTED_FILE(ProjectDefines_h)
 #elif defined(WIN32) || defined(WIN64)
-#if !defined(_RELEASE) || defined(PERFORMANCE_BUILD)
-#define ENABLE_STATS_AGENT
-#endif
+    #if !defined(_RELEASE) || defined(PERFORMANCE_BUILD)
+        #define ENABLE_STATS_AGENT
+    #endif
 #endif
 
-// The following definitions are used by Sandbox and RC to determine which platform support is needed
-#define TOOLS_SUPPORT_POWERVR
-#define TOOLS_SUPPORT_ETC2COMP
 
 // Type used for vertex indices
 // WARNING: If you change this typedef, you need to update AssetProcessorPlatformConfig.ini to convert cgf and abc files to the proper index format.
 #if defined(RESOURCE_COMPILER)
-typedef uint32 vtx_idx;
-#define AZ_RESTRICTED_SECTION_IMPLEMENTED
+    typedef uint32 vtx_idx;
+    #define AZ_RESTRICTED_SECTION_IMPLEMENTED
 #elif defined(MOBILE)
-typedef uint16 vtx_idx;
-#define AZ_RESTRICTED_SECTION_IMPLEMENTED
+    typedef uint16 vtx_idx;
+    #define AZ_RESTRICTED_SECTION_IMPLEMENTED
 #elif defined(AZ_RESTRICTED_PLATFORM)
     #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_VTX_IDX
     #include AZ_RESTRICTED_FILE(ProjectDefines_h)
 #endif
 #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
+    #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
 #else
-// Uncomment one of the two following typedefs:
-typedef uint32 vtx_idx;
-//typedef uint16 vtx_idx;
+    // Uncomment one of the two following typedefs:
+    typedef uint32 vtx_idx;
+    //typedef uint16 vtx_idx;
 #endif
 
 
-// 0=off, 1=on
-#define TERRAIN_USE_CIE_COLORSPACE 0
-
 // When non-zero, const cvar accesses (by name) are logged in release-mode on consoles.
 // This can be used to find non-optimal usage scenario's, where the constant should be used directly instead.
 // Since read accesses tend to be used in flow-control logic, constants allow for better optimization by the compiler.
 #define LOG_CONST_CVAR_ACCESS 0
 
 #if defined(WIN32) || defined(WIN64) || LOG_CONST_CVAR_ACCESS
-#define RELEASE_LOGGING
+    #define RELEASE_LOGGING
 #endif
 
 #if defined(_RELEASE) && !defined(RELEASE_LOGGING)
-#define EXCLUDE_NORMAL_LOG
+    #define EXCLUDE_NORMAL_LOG
 #endif
 
 // Add the "REMOTE_ASSET_PROCESSOR" define except in release
 // this makes it so that asset processor functions.  Without this, all assets must be present and on local media
 // with this, the asset processor can be used to remotely process assets.
 #if !defined(_RELEASE)
-#   define REMOTE_ASSET_PROCESSOR
+    #define REMOTE_ASSET_PROCESSOR
 #endif
 
 #if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD))
@@ -93,132 +83,68 @@ typedef uint32 vtx_idx;
     #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_TRAITS
     #include AZ_RESTRICTED_FILE(ProjectDefines_h)
 #else
-#define PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS 1
-#if !defined(LINUX) && !defined(APPLE)
-#define PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM 1
-#endif
-#if defined(WIN32) || defined(WIN64) || defined(LINUX) || defined(APPLE)
-#define PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES 1
-#endif
-#define PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION 1
-#if defined(WIN32)
-#define PROJECTDEFINES_H_TRAIT_USE_SVO_GI 1
-#endif
-#if defined(APPLE) || defined(LINUX)
-#define AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS 1
-#define AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS 1
-#endif
-#endif
-
-#define USE_GLOBAL_BUCKET_ALLOCATOR
-
-#ifdef IS_PROSDK
-#   define USING_TAGES_SECURITY                 // Wrapper for TGVM security
-# if defined(LINUX) || defined(APPLE)
-#   error LINUX and Mac does not support evaluation version
-# endif
-#endif
-
-#ifdef USING_TAGES_SECURITY
-#   define TAGES_EXPORT __declspec(dllexport)
-#else
-#   define TAGES_EXPORT
-#endif // USING_TAGES_SECURITY
-// test -------------------------------------
-
-#define _DATAPROBE
-
-
-
-//This feature allows automatic crash submission to JIRA, but does not work outside of O3DE
-//Note: This #define will be commented out during code export
-#define ENABLE_CRASH_HANDLER
-
-#if !defined(PHYSICS_STACK_SIZE)
-# define PHYSICS_STACK_SIZE (128U << 10)
+    #define PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS 1
+    #if !defined(LINUX) && !defined(APPLE)
+        #define PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM 1
+    #endif
+    #if defined(WIN32) || defined(WIN64) || defined(LINUX) || defined(APPLE)
+        #define PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES 1
+    #endif
+    #define PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION 1
+    #if defined(WIN32)
+        #define PROJECTDEFINES_H_TRAIT_USE_SVO_GI 1
+    #endif
+    #if defined(APPLE) || defined(LINUX)
+        #define AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS 1
+        #define AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS 1
+    #endif
 #endif
 
 #if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !defined(RESOURCE_COMPILER)
-#ifndef ENABLE_PROFILING_CODE
-    #define ENABLE_PROFILING_CODE
-#endif
-#if !(defined(SANDBOX_EXPORTS) || defined(PLUGIN_EXPORTS) || (defined(AZ_MONOLITHIC_BUILD) && PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS))
-    #define ENABLE_PROFILING_MARKERS
-#endif
+    #ifndef ENABLE_PROFILING_CODE
+        #define ENABLE_PROFILING_CODE
+    #endif
 
-//lightweight profilers, disable for submissions, disables displayinfo inside 3dengine as well
-#ifndef ENABLE_LW_PROFILERS
-    #define ENABLE_LW_PROFILERS
-#endif
-#endif
-
-#if defined(ENABLE_PROFILING_CODE)
-#define ENABLE_ART_RT_TIME_ESTIMATE
-#endif
-
-#if defined(ENABLE_PROFILING_CODE) && !defined(_RELEASE)
-    #define FMOD_STREAMING_DEBUGGING 1
-#endif
-
-#if defined(WIN32) || defined(WIN64) || defined(APPLE) || defined(AZ_PLATFORM_LINUX)
-#define FLARES_SUPPORT_EDITING
+    //lightweight profilers, disable for submissions, disables displayinfo inside 3dengine as well
+    #ifndef ENABLE_LW_PROFILERS
+        #define ENABLE_LW_PROFILERS
+    #endif
 #endif
 
 // Reflect texture slot information - only used in the editor
 #if defined(WIN32) || defined(WIN64) || defined(AZ_PLATFORM_MAC)
-#define SHADER_REFLECT_TEXTURE_SLOTS 1
+    #define SHADER_REFLECT_TEXTURE_SLOTS 1
 #else
-#define SHADER_REFLECT_TEXTURE_SLOTS 0
+    #define SHADER_REFLECT_TEXTURE_SLOTS 0
 #endif
 
-// these enable and disable certain net features to give compatibility between PCs and consoles / profile and performance builds
-#define PC_CONSOLE_NET_COMPATIBLE 0
-#define PROFILE_PERFORMANCE_NET_COMPATIBLE 0
-
-#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !PROFILE_PERFORMANCE_NET_COMPATIBLE
-#define USE_LAGOMETER (1)
-#else
-#define USE_LAGOMETER (0)
-#endif
-
-// enable this in order to support old style material names in old data ("engine/material.mtl" or "mygame/material.mtl" as opposed to just "material.mtl")
-// previously, material names could have the game folder in it, but this is not necessary anymore and would not work with things like gems
-// note that if you use any older projects such as GameSDK this should remain enabled
-#define SUPPORT_LEGACY_MATERIAL_NAMES
-
-// Enable additional structures and code for sprite motion blur. Currently non-functional and disabled
-// #define PARTICLE_MOTION_BLUR
-
-// a special ticker thread to run during load and unload of levels
-#define USE_NETWORK_STALL_TICKER_THREAD
-
 #if !defined(MOBILE)
-//---------------------------------------------------------------------
-// Enable Tessellation Features
-// (displacement mapping, subdivision, water tessellation)
-//---------------------------------------------------------------------
-// Modules   : 3DEngine, Renderer
-// Depends on: DX11
+    //---------------------------------------------------------------------
+    // Enable Tessellation Features
+    // (displacement mapping, subdivision, water tessellation)
+    //---------------------------------------------------------------------
+    // Modules   : 3DEngine, Renderer
+    // Depends on: DX11
 
-// Global tessellation feature flag
+    // Global tessellation feature flag
     #define TESSELLATION
     #ifdef TESSELLATION
-// Specific features flags
+        // Specific features flags
         #define WATER_TESSELLATION
         #define PARTICLES_TESSELLATION
 
         #if PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION
-// Mesh tessellation (displacement, smoothing, subd)
+            // Mesh tessellation (displacement, smoothing, subd)
             #define MESH_TESSELLATION
-// Mesh tessellation also in motion blur passes
+            // Mesh tessellation also in motion blur passes
             #define MOTIONBLUR_TESSELLATION
         #endif
 
-// Dependencies
+        // Dependencies
         #ifdef MESH_TESSELLATION
             #define MESH_TESSELLATION_ENGINE
         #endif
-            #ifndef NULL_RENDERER
+        #ifndef NULL_RENDERER
             #ifdef WATER_TESSELLATION
                 #define WATER_TESSELLATION_RENDERER
             #endif
@@ -230,7 +156,7 @@ typedef uint32 vtx_idx;
             #endif
 
             #if defined(WATER_TESSELLATION_RENDERER) || defined(PARTICLES_TESSELLATION_RENDERER) || defined(MESH_TESSELLATION_RENDERER)
-// Common tessellation flag enabling tessellation stages in renderer
+                // Common tessellation flag enabling tessellation stages in renderer
                 #define TESSELLATION_RENDERER
             #endif
         #endif // !NULL_RENDERER
@@ -249,14 +175,8 @@ typedef uint32 vtx_idx;
 #endif
 
 #if defined(ENABLE_PROFILING_CODE)
-#   define USE_DISK_PROFILER
-#   define ENABLE_LOADING_PROFILER  // requires AZ_PROFILE_TELEMETRY to also be defined
-#endif
-
-#if PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES && !defined(NULL_RENDERER)
-    #define GPU_PARTICLES 1
-#else
-    #define GPU_PARTICLES 0
+    #define USE_DISK_PROFILER
+    #define ENABLE_LOADING_PROFILER  // requires AZ_PROFILE_TELEMETRY to also be defined
 #endif
 
 // The maximum number of joints in an animation
diff --git a/Code/Legacy/CryCommon/Win32specific.h b/Code/Legacy/CryCommon/Win32specific.h
index 650a4946a0..0519bb1022 100644
--- a/Code/Legacy/CryCommon/Win32specific.h
+++ b/Code/Legacy/CryCommon/Win32specific.h
@@ -23,7 +23,6 @@
 #define ILINE __forceinline
 #endif
 
-#define DEBUG_BREAK _asm { int 3 }
 #define RC_EXECUTABLE "rc.exe"
 #define DEPRECATED __declspec(deprecated)
 #define TYPENAME(x) typeid(x).name()
diff --git a/Code/Legacy/CryCommon/Win64specific.h b/Code/Legacy/CryCommon/Win64specific.h
index a3cb11ce32..b1e86f9250 100644
--- a/Code/Legacy/CryCommon/Win64specific.h
+++ b/Code/Legacy/CryCommon/Win64specific.h
@@ -19,7 +19,6 @@
 #define _CPU_SSE
 #define ILINE __forceinline
 
-#define DEBUG_BREAK CryDebugBreak()
 #define RC_EXECUTABLE "rc.exe"
 #define DEPRECATED __declspec(deprecated)
 #define TYPENAME(x) typeid(x).name()
diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp
index 15146fbac1..2861b4470e 100644
--- a/Code/Legacy/CryCommon/WinBase.cpp
+++ b/Code/Legacy/CryCommon/WinBase.cpp
@@ -1127,20 +1127,6 @@ void CrySleep(unsigned int dwMilliseconds)
     Sleep(dwMilliseconds);
 }
 
-//////////////////////////////////////////////////////////////////////////
-void CryLowLatencySleep(unsigned int dwMilliseconds)
-{
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_6
-    #include AZ_RESTRICTED_FILE(WinBase_cpp)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-    CrySleep(dwMilliseconds);
-#endif
-}
-
 //////////////////////////////////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////////
 int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType)
@@ -1284,14 +1270,6 @@ int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType)
 #endif
 }
 
-//////////////////////////////////////////////////////////////////////////
-short CryGetAsyncKeyState(int vKey)
-{
-    //TODO: implement
-    CRY_ASSERT_MESSAGE(0, "CryGetAsyncKeyState not implemented yet");
-    return 0;
-}
-
 #if defined(LINUX) || defined(APPLE) || defined(DEFINE_CRY_INTERLOCKED_INCREMENT)
 //[K01]: http://www.memoryhole.net/kyle/2007/05/atomic_incrementing.html
 //http://forums.devx.com/archive/index.php/t-160558.html
@@ -1382,10 +1360,6 @@ threadID CryGetCurrentThreadId()
     return GetCurrentThreadId();
 }
 
-void CryDebugBreak()
-{
-    __builtin_trap();
-}
 #endif//LINUX APPLE
 
 #if defined(APPLE) || defined(LINUX)
@@ -1398,11 +1372,6 @@ DLL_EXPORT void OutputDebugString(const char* outputString)
 #endif
 }
 
-DLL_EXPORT void DebugBreak()
-{
-    CryDebugBreak();
-}
-
 #endif
 
 // This code does not have a long life span and will be replaced soon
@@ -1626,16 +1595,6 @@ DWORD GetFileAttributes(LPCSTR lpFileName)
     return (ret == 0) ? FILE_ATTRIBUTE_NORMAL : ret;//return file attribute normal as the default value, must only be set if no other attributes have been found
 }
 
-uint32 CryGetFileAttributes(const char* lpFileName)
-{
-    
-    string fn = lpFileName;
-    adaptFilenameToLinux(fn);
-    const char* buffer = fn.c_str();
-    return GetFileAttributes(buffer);
-    
-}
-
 __finddata64_t::~__finddata64_t()
 {
     if (m_Dir != FS_DIR_NULL)
diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h
index 6aad8dd043..fb96056beb 100644
--- a/Code/Legacy/CryCommon/platform.h
+++ b/Code/Legacy/CryCommon/platform.h
@@ -7,136 +7,31 @@
  */
 
 
-// Description : Platform dependend stuff.
+// Description : Platform dependent stuff.
 //               Include this file instead of windows h
 
 #pragma once
 
 #if defined(AZ_RESTRICTED_PLATFORM)
 #undef AZ_RESTRICTED_SECTION
-#define PLATFORM_H_SECTION_1 1
-#define PLATFORM_H_SECTION_2 2
 #define PLATFORM_H_SECTION_3 3
-#define PLATFORM_H_SECTION_4 4
 #define PLATFORM_H_SECTION_5 5
 #define PLATFORM_H_SECTION_6 6
 #define PLATFORM_H_SECTION_7 7
 #define PLATFORM_H_SECTION_8 8
-#define PLATFORM_H_SECTION_9 9
 #define PLATFORM_H_SECTION_10 10
 #define PLATFORM_H_SECTION_11 11
 #define PLATFORM_H_SECTION_12 12
 #define PLATFORM_H_SECTION_13 13
 #define PLATFORM_H_SECTION_14 14
-#define PLATFORM_H_SECTION_15 15
 #endif
 
-// certain C++ features are not available in some compiler versions
-// turn them off here:
-// #define _ALLOW_KEYWORD_MACROS
-// #define _DISALLOW_INITIALIZER_LISTS
-// #define _DISALLOW_ENUM_CLASS
-
-#if defined(_MSC_VER)
-    #define _ALLOW_KEYWORD_MACROS
-
-    #define alignof _alignof
-    #if !defined(_HAS_EXCEPTIONS)
-        #define _HAS_EXCEPTIONS 0
-    #endif
-#elif defined(__GNUC__)
-    #define alignof __alignof__
-#endif
-
-// Alignment|InitializerList support.
-#define _ALLOW_INITIALIZER_LISTS
-
 #if (defined(LINUX) && !defined(ANDROID)) || defined(APPLE)
-#define _FILE_OFFSET_BITS 64 // define large file support > 2GB
+    #define _FILE_OFFSET_BITS 64 // define large file support > 2GB
 #endif
 
 #include 
 
-#include 
-
-#if defined(_MSC_VER) // We want the class name to be included, but __FUNCTION__ doesn't contain that on GCC/clang
-    #define __FUNC__ __FUNCTION__
-#else
-    #define __FUNC__ __PRETTY_FUNCTION__
-#endif
-
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_1
-    #include AZ_RESTRICTED_FILE(platform_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#elif defined(_DEBUG) && !defined(LINUX) && !defined(APPLE)
-    #include 
-#endif
-
-#define RESTRICT_POINTER __restrict
-
-// we have to use it because of VS doesn't support restrict reference variables
-#if defined(APPLE) || defined(LINUX)
-    #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
-        #define GCC411_OR_LATER
-    #endif
-    #define RESTRICT_REFERENCE __restrict
-#else
-    #define RESTRICT_REFERENCE
-#endif
-
-
-#ifndef CHECK_REFERENCE_COUNTS //define that in your StdAfx.h to override per-project
-# define CHECK_REFERENCE_COUNTS 0 //default value
-#endif
-
-#if CHECK_REFERENCE_COUNTS
-# define CHECK_REFCOUNT_CRASH(x) { if (!(x)) {*((int*)0) = 0; } \
-}
-#else
-# define CHECK_REFCOUNT_CRASH(x)
-#endif
-
-#ifndef GARBAGE_MEMORY_ON_FREE //define that in your StdAfx.h to override per-project
-# define GARBAGE_MEMORY_ON_FREE 0 //default value
-#endif
-
-#if GARBAGE_MEMORY_ON_FREE
-# ifndef GARBAGE_MEMORY_RANDOM          //define that in your StdAfx.h to override per-project
-#  define GARBAGE_MEMORY_RANDOM 1   //0 to change it to progressive pattern
-# endif
-#endif
-
-//////////////////////////////////////////////////////////////////////////
-// Available predefined compiler macros for Visual C++.
-//      _MSC_VER                                        // Indicates MS Visual C compiler version
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_2
-    #include AZ_RESTRICTED_FILE(platform_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-//      _WIN32, _WIN64       // Indicates target OS
-#endif
-//      _M_IX86, _M_PPC                         // Indicates target processor
-//      _DEBUG                                          // Building in Debug mode
-//      _DLL                                                // Linking with DLL runtime libs
-//      _MT                                                 // Linking with multi-threaded runtime libs
-//////////////////////////////////////////////////////////////////////////
-
-//
-// Translate some predefined macros.
-//
-
-// NDEBUG disables std asserts, etc.
-// Define it automatically if not compiling with Debug libs, or with ADEBUG flag.
-#if !defined(_DEBUG) && !defined(ADEBUG) && !defined(NDEBUG)
-    #define NDEBUG
-#endif
-
 #if defined(AZ_RESTRICTED_PLATFORM)
     #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_3
     #include AZ_RESTRICTED_FILE(platform_h)
@@ -147,44 +42,6 @@
     #define CONSOLE
 #endif
 
-//render thread settings, as this is accessed inside 3dengine and renderer and needs to be compile time defined, we need to do it here
-//enable this macro to strip out the overhead for render thread
-//  #define STRIP_RENDER_THREAD
-#ifdef STRIP_RENDER_THREAD
-    #define RT_COMMAND_BUF_COUNT 1
-#else
-//can be enhanced to triple buffering, FlushFrame needs to be adjusted and RenderObj would become 132 bytes
-    #define RT_COMMAND_BUF_COUNT 2
-#endif
-
-
-// We use WIN macros without _.
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_4
-    #include AZ_RESTRICTED_FILE(platform_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-#if defined(_WIN32) && !defined(LINUX32) && !defined(LINUX64) && !defined(APPLE) && !defined(WIN32)
-    #define WIN32
-#endif
-#if defined(_WIN64) && !defined(WIN64)
-    #define WIN64
-#endif
-#endif
-
-// In Win32 Release we use static linkage
-#ifdef WIN32
-    #if !defined(_RELEASE) || defined(RESOURCE_COMPILER) || defined(EDITOR) || defined(_FORCEDLL)
-// All windows targets not in Release built as DLLs.
-        #ifndef _USRDLL
-            #define _USRDLL
-        #endif
-    #endif
-
-#endif //WIN32
-
 #if defined(AZ_RESTRICTED_PLATFORM)
     #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_5
     #include AZ_RESTRICTED_FILE(platform_h)
@@ -205,19 +62,17 @@
         #define PRId64 "lld"
         #define PRIu64 "llu"
     #endif
-    #define PLATFORM_I64(x) x##ll
 #else
     #include 
-    #define PLATFORM_I64(x) x##i64
 #endif
 
 #if !defined(PRISIZE_T)
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_6
-    #include AZ_RESTRICTED_FILE(platform_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
+    #if defined(AZ_RESTRICTED_PLATFORM)
+        #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_6
+        #include AZ_RESTRICTED_FILE(platform_h)
+    #endif
+    #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
+        #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
     #elif defined(WIN64)
         #define PRISIZE_T "I64u" //size_t defined as unsigned __int64
     #elif defined(WIN32) || defined(LINUX32)
@@ -228,13 +83,14 @@
         #error "Please defined PRISIZE_T for this platform"
     #endif
 #endif
+
 #if !defined(PRI_THREADID)
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_7
-    #include AZ_RESTRICTED_FILE(platform_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
+    #if defined(AZ_RESTRICTED_PLATFORM)
+        #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_7
+        #include AZ_RESTRICTED_FILE(platform_h)
+    #endif
+    #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
+        #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
     #elif defined(MAC) || defined(IOS) && defined(__LP64__) && defined(__LP64__)
         #define PRI_THREADID "lld"
     #elif defined(LINUX64) || defined(ANDROID)
@@ -243,6 +99,7 @@
         #define PRI_THREADID "d"
     #endif
 #endif
+
 #include "ProjectDefines.h"                         // to get some defines available in every CryEngine project
 
 // Function attribute for printf/scanf-style parameters.
@@ -277,47 +134,6 @@
   #define PRINTF_EMPTY_FORMAT ""
 #endif
 
-#if defined(IOS)
-#define USE_PTHREAD_TLS
-#endif
-
-// Storage class modifier for thread local storage.
-// THEADLOCAL should NOT be defined to empty because that creates some
-// really hard to find issues.
-#if !defined(USE_PTHREAD_TLS)
-#   define THREADLOCAL AZ_TRAIT_COMPILER_THREAD_LOCAL
-#endif //!defined(USE_PTHREAD_TLS)
-
-
-
-//////////////////////////////////////////////////////////////////////////
-// define Read Write Barrier macro needed for lockless programming
-//////////////////////////////////////////////////////////////////////////
-#if   defined(__arm__)
-/**
- * (ARMv7) Full memory barriar.
- *
- * None of GCC 4.6/4.8 or clang 3.3/3.4 have a builtin intrinsic for ARM's ldrex/strex or dmb
- * instructions.  This is a placeholder until supplied by the toolchain.
- */
-inline void  __dmb()
-{
-    // The linux kernel uses "dmb ish" to only sync with local monitor (arch/arm/include/asm/barrier.h):
-    //#define dmb(option) __asm__ __volatile__ ("dmb " #option : : : "memory")
-    //#define smp_mb()        dmb(ish)
-    __asm__ __volatile__ ("dmb ish" : : : "memory");
-}
-
-#define READ_WRITE_BARRIER {__dmb(); }
-#else
-    #define READ_WRITE_BARRIER
-#endif
-//////////////////////////////////////////////////////////////////////////
-
-//////////////////////////////////////////////////////////////////////////
-// define macro to prevent memory reoderings of reads/and writes
-//TODO implement for all GCC platforms, else there are potential crashes with strict aliasing
-    #define MEMORY_RW_REORDERING_BARRIER do { /*not implemented*/} while (0)
 
 //default stack size for threads, currently only used on pthread platforms
 #if defined(AZ_RESTRICTED_PLATFORM)
@@ -325,7 +141,7 @@ inline void  __dmb()
     #include AZ_RESTRICTED_FILE(platform_h)
 #endif
 #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
+    #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
 #elif defined(LINUX) || defined(APPLE)
     #if !defined(_DEBUG)
         #define SIMPLE_THREAD_STACK_SIZE_KB (256)
@@ -362,22 +178,6 @@ inline void  __dmb()
 #else
     #define _HELP(x) ""
 #endif
-//////////////////////////////////////////////////////////////////////////
-
-//////////////////////////////////////////////////////////////////////////
-// Globally Used Defines.
-//////////////////////////////////////////////////////////////////////////
-// CPU Types: _CPU_X86,_CPU_AMD64,_CPU_G5
-// Platform: WIN23,WIN64,LINUX32,LINUX64,MAC
-// CPU supported functionality: _CPU_SSE
-//////////////////////////////////////////////////////////////////////////
-
-
-  #if defined(_MSC_VER)
-    #define PREFAST_SUPPRESS_WARNING(W) __pragma(warning(suppress: W))
-  #else
-    #define PREFAST_SUPPRESS_WARNING(W)
-  #endif
 
 #ifdef _PREFAST_
 #   define PREFAST_ASSUME(cond) __analysis_assume(cond)
@@ -385,47 +185,21 @@ inline void  __dmb()
 #   define PREFAST_ASSUME(cond)
 #endif
 
-
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_9
-    #include AZ_RESTRICTED_FILE(platform_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-    #if defined(WIN32) && !defined(WIN64)
-        #include "Win32specific.h"
-    #endif
-
-    #if defined(WIN64)
-        #include "Win64specific.h"
-    #endif
-#endif
-
-#if defined(LINUX64) && !defined(ANDROID)
-#include "Linux64Specific.h"
-#endif
-
-#if defined(LINUX32) && !defined(ANDROID)
-#include "Linux32Specific.h"
-#endif
-
-#if defined(ANDROID)
-#include "AndroidSpecific.h"
-#endif
-
-
 #if defined(AZ_RESTRICTED_PLATFORM)
     #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_10
     #include AZ_RESTRICTED_FILE(platform_h)
-#endif
-
-#if defined(MAC)
-#include "MacSpecific.h"
-#endif
-
-#if defined(IOS)
-#include "iOSSpecific.h"
+#else
+    #if defined(WIN64)
+        #include "Win64specific.h"
+    #elif defined(LINUX64)
+        #include "Linux64Specific.h"
+    #elif defined(MAC)
+        #include "MacSpecific.h"
+    #elif defined(ANDROID)
+        #include "AndroidSpecific.h"
+    #elif defined(IOS)
+    #include "iOSSpecific.h"
+    #endif
 #endif
 
 
@@ -480,12 +254,6 @@ ILINE DestinationType alias_cast(SourceType pPtr)
 #define DEPRECATED
 #endif
 
-//////////////////////////////////////////////////////////////////////////
-// compile time error stuff
-//////////////////////////////////////////////////////////////////////////
-#undef STATIC_CHECK
-#define STATIC_CHECK(expr, msg) static_assert(expr, #msg)
-
 // Assert dialog box macros
 #include "CryAssert.h"
 
@@ -500,30 +268,8 @@ ILINE DestinationType alias_cast(SourceType pPtr)
 // Platform dependent functions that emulate Win32 API.
 // Mostly used only for debugging!
 //////////////////////////////////////////////////////////////////////////
-void   CryDebugBreak();
 void   CrySleep(unsigned int dwMilliseconds);
-void   CryLowLatencySleep(unsigned int dwMilliseconds);
 int    CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType);
-short  CryGetAsyncKeyState(int vKey);
-unsigned int CryGetFileAttributes(const char* lpFileName);
-
-inline void CryHeapCheck()
-{
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_11
-    #include AZ_RESTRICTED_FILE(platform_h)
-#elif !defined(LINUX) && !defined(APPLE) // todo: this might be readded with later xdks?
-#if !defined(NDEBUG)
-    int Result =
-#endif
-        _heapchk();
-    assert(Result != _HEAPBADBEGIN);
-    assert(Result != _HEAPBADNODE);
-    assert(Result != _HEAPBADPTR);
-    assert(Result != _HEAPEMPTY);
-    assert(Result == _HEAPOK);
-#endif
-}
 
 //---------------------------------------------------------------------------
 // Useful function to clean the structure.
@@ -554,77 +300,6 @@ inline D check_cast(S const& s)
     return d;
 }
 
-// Convert one type to another, asserting there is no conversion loss.
-// Usage: DestType dest;  check_convert(dest, src);
-template
-inline D& check_convert(D& d, S const& s)
-{
-    d = D(s);
-    assert(S(d) == s);
-    return d;
-}
-
-// Convert one type to another, asserting there is no conversion loss.
-// Usage: DestType dest;  check_convert(dest) = src;
-template
-struct CheckConvert
-{
-    CheckConvert(D& d)
-        : dest(&d) {}
-
-    template
-    D& operator=(S const& s)
-    {
-        return check_convert(*dest, s);
-    }
-
-protected:
-    D*  dest;
-};
-
-template
-inline CheckConvert check_convert(D& d)
-{
-    return d;
-}
-
-//---------------------------------------------------------------------------
-// Use NoCopy as a base class to easily prevent copy init & assign for any class.
-struct NoCopy
-{
-    NoCopy() {}
-private:
-    NoCopy(const NoCopy&);
-    NoCopy& operator =(const NoCopy&);
-};
-
-//---------------------------------------------------------------------------
-// ZeroInit: base class to zero the memory of the derived class before initialization, so local objects initialize the same as static.
-// Usage:
-//      class MyClass: ZeroInit {...}
-//      class MyChild: public MyClass, ZeroInit {...}      // ZeroInit must be the last base class
-
-template
-struct ZeroInit
-{
-#if defined(__clang__) || defined(__GNUC__)
-    bool __dummy;                           // Dummy var to create non-zero size, ensuring proper placement in TDerived
-#endif
-
-    ZeroInit(bool bZero = true)
-    {
-        // Optional bool arg to selectively disable zeroing.
-        if (bZero)
-        {
-            // Infer offset of this base class by static casting to derived class.
-            // Zero only the additional memory of the derived class.
-            TDerived* struct_end = static_cast(this) + 1;
-            size_t memory_size = (char*)struct_end - (char*)this;
-            memset(this, 0, memory_size);
-        }
-    }
-};
-
 //---------------------------------------------------------------------------
 // Quick const-manipulation macros
 
@@ -705,29 +380,19 @@ threadID CryGetCurrentThreadId();
     #include "CryFixedString.h"
 #endif
 
-// need this in a common header file and any other file would be too misleading
-enum ETriState
-{
-    eTS_false,
-    eTS_true,
-    eTS_maybe
-};
-
-    #ifdef __GNUC__
-        #define NO_INLINE __attribute__ ((noinline))
-#   define NO_INLINE_WEAK __attribute__ ((noinline)) __attribute__((weak)) // marks a function as no_inline, but also as weak to prevent multiple-defined errors
-
-#   define __PACKED __attribute__ ((packed))
-    #else
-        #define NO_INLINE _declspec(noinline)
-#   define NO_INLINE_WEAK _declspec(noinline) inline
-
-#   define __PACKED
-    #endif
+#ifdef __GNUC__
+    #define NO_INLINE __attribute__ ((noinline))
+    #define NO_INLINE_WEAK __attribute__ ((noinline)) __attribute__((weak)) // marks a function as no_inline, but also as weak to prevent multiple-defined errors
+    #define __PACKED __attribute__ ((packed))
+#else
+    #define NO_INLINE _declspec(noinline)
+    #define NO_INLINE_WEAK _declspec(noinline) inline
+    #define __PACKED
+#endif
 
 // Fallback for Alignment macro of GCC/CLANG (must be after the class definition)
 #if !defined(_ALIGN)
-        #define _ALIGN(num) AZ_POP_DISABLE_WARNING
+    #define _ALIGN(num) AZ_POP_DISABLE_WARNING
 #endif
 
 // Fallback for Alignment macro of MSVC (must be before the class definition)
@@ -735,60 +400,13 @@ enum ETriState
         #define _MS_ALIGN(num) AZ_PUSH_DISABLE_WARNING(4324, "-Wunknown-warning-option")
 #endif
 
-#if defined(WIN32) || defined(WIN64)
-extern "C" {
-__declspec(dllimport) unsigned long __stdcall TlsAlloc();
-__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long dwTlsIndex);
-__declspec(dllimport) int __stdcall TlsSetValue(unsigned long dwTlsIndex, void* lpTlsValue);
-}
-
-    #define TLS_DECLARE(type, var) extern int var##idx;
-    #define TLS_DEFINE(type, var)              \
-    int var##idx;                              \
-    struct Init##var {                         \
-        Init##var() { var##idx = TlsAlloc(); } \
-    };                                         \
-    Init##var g_init##var;
-    #define TLS_DEFINE_DEFAULT_VALUE(type, var, value)                                \
-    int var##idx;                                                                     \
-    struct Init##var {                                                                \
-        Init##var() { var##idx = TlsAlloc(); TlsSetValue(var##idx, reinterpret_cast(value)); } \
-    };                                                                                \
-    Init##var g_init##var;
-    #define TLS_GET(type, var) (type)TlsGetValue(var##idx)
-    #define TLS_SET(var, val) TlsSetValue(var##idx, reinterpret_cast(val))
-#elif defined(USE_PTHREAD_TLS)
-    #define TLS_DECLARE(_TYPE, _VAR) extern SCryPthreadTLS<_TYPE> _VAR##TLSKey;
-    #define TLS_DEFINE(_TYPE, _VAR) SCryPthreadTLS<_TYPE> _VAR##TLSKey;
-    #define TLS_DEFINE_DEFAULT_VALUE(_TYPE, _VAR, _DEFAULT) SCryPthreadTLS<_TYPE> _VAR##TLSKey = _DEFAULT;
-    #define TLS_GET(_TYPE, _VAR) _VAR##TLSKey.Get()
-    #define TLS_SET(_VAR, _VALUE) _VAR##TLSKey.Set(_VALUE)
-#elif defined(THREADLOCAL)
-    #define TLS_DECLARE(type, var) extern THREADLOCAL type var;
-#if defined(LINUX) || defined(MAC)
-    #define TLS_DEFINE(type, var) THREADLOCAL type var = 0;
-#else
-    #define TLS_DEFINE(type, var) THREADLOCAL type var;
-#endif // defined(LINUX) || defined(MAC)
-    #define TLS_DEFINE_DEFAULT_VALUE(type, var, value) THREADLOCAL type var = value;
-    #define TLS_GET(type, var) (var)
-    #define TLS_SET(var, val) (var = (val))
-#else // defined(THREADLOCAL)
-    #error "There's no support for thread local storage"
-#endif
-
 #if defined(AZ_RESTRICTED_PLATFORM)
     #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_13
     #include AZ_RESTRICTED_FILE(platform_h)
 #elif !defined(LINUX) && !defined(APPLE)
-typedef int socklen_t;
+    typedef int socklen_t;
 #endif
 
-
-// Include MultiThreading support.
-#include "CryThread.h"
-#include "MultiThread.h"
-
 // In RELEASE disable printf and fprintf
 #if defined(_RELEASE) && !defined(RELEASE_LOGGING)
     #if defined(AZ_RESTRICTED_PLATFORM)
@@ -797,19 +415,4 @@ typedef int socklen_t;
     #endif
 #endif
 
-#define _STRINGIFY(x) #x
-#define STRINGIFY(x) _STRINGIFY(x)
-
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_15
-    #include AZ_RESTRICTED_FILE(platform_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#elif defined(WIN32) || defined(WIN64)
-    #define MESSAGE(msg) message(__FILE__ "(" STRINGIFY(__LINE__) "): " msg)
-#else
-    #define MESSAGE(msg)
-#endif
-
 void InitRootDir(char szExeFileName[] = nullptr, uint nExeSize = 0, char szExeRootName[] = nullptr, uint nRootSize = 0);
diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp
index a677ba30b6..a919b9a002 100644
--- a/Code/Legacy/CryCommon/platform_impl.cpp
+++ b/Code/Legacy/CryCommon/platform_impl.cpp
@@ -204,17 +204,6 @@ void __stl_debug_message(const char* format_str, ...)
 
 #include "CryAssert_impl.h"
 
-//////////////////////////////////////////////////////////////////////////
-void CryDebugBreak()
-{
-#if defined(WIN32) && !defined(RELEASE)
-    if (IsDebuggerPresent())
-#endif
-    {
-        DebugBreak();
-    }
-}
-
 //////////////////////////////////////////////////////////////////////////
 void CrySleep(unsigned int dwMilliseconds)
 {
@@ -222,21 +211,6 @@ void CrySleep(unsigned int dwMilliseconds)
     Sleep(dwMilliseconds);
 }
 
-//////////////////////////////////////////////////////////////////////////
-void CryLowLatencySleep(unsigned int dwMilliseconds)
-{
-    AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System);
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYLOWLATENCYSLEEP
-    #include AZ_RESTRICTED_FILE(platform_impl_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-    CrySleep(dwMilliseconds);
-#endif
-}
-
 //////////////////////////////////////////////////////////////////////////
 int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const char* lpCaption, [[maybe_unused]] unsigned int uType)
 {
@@ -302,16 +276,6 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], [[ma
     }
 }
 
-//////////////////////////////////////////////////////////////////////////
-short CryGetAsyncKeyState([[maybe_unused]] int vKey)
-{
-#ifdef WIN32
-    return GetAsyncKeyState(vKey);
-#else
-    return 0;
-#endif
-}
-
 //////////////////////////////////////////////////////////////////////////
 LONG  CryInterlockedIncrement(int volatile* lpAddend)
 {
@@ -417,23 +381,6 @@ void  CryLeaveCriticalSection(void* cs)
     LeaveCriticalSection((CRITICAL_SECTION*)cs);
 }
 
-//////////////////////////////////////////////////////////////////////////
-uint32 CryGetFileAttributes(const char* lpFileName)
-{
-    WIN32_FILE_ATTRIBUTE_DATA data;
-    BOOL res;
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYGETFILEATTRIBUTES
-    #include AZ_RESTRICTED_FILE(platform_impl_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-    res = GetFileAttributesEx(lpFileName, GetFileExInfoStandard, &data);
-#endif
-    return res ? data.dwFileAttributes : -1;
-}
-
 //////////////////////////////////////////////////////////////////////////
 bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes)
 {
diff --git a/Code/Legacy/CryCommon/smartptr.h b/Code/Legacy/CryCommon/smartptr.h
index 246e18d541..6953348d47 100644
--- a/Code/Legacy/CryCommon/smartptr.h
+++ b/Code/Legacy/CryCommon/smartptr.h
@@ -13,6 +13,7 @@
 
 #include 
 #include 
+#include 
 
 void CryFatalError(const char*, ...) PRINTF_PARAMS(1, 2);
 #if defined(APPLE)
@@ -171,13 +172,13 @@ public:
 
     void AddRef()
     {
-        CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0);
+        AZ_Assert(m_nRefCounter >= 0, "Invalid ref count");
         ++m_nRefCounter;
     }
 
     void Release()
     {
-        CHECK_REFCOUNT_CRASH(m_nRefCounter > 0);
+        AZ_Assert(m_nRefCounter > 0, "Invalid ref count");
         if (--m_nRefCounter == 0)
         {
             delete static_cast(this);
@@ -215,13 +216,13 @@ public:
 
     void AddRef()
     {
-        CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0);
+        AZ_Assert(m_nRefCounter >= 0, "Invalid ref count");
         ++m_nRefCounter;
     }
 
     void Release()
     {
-        CHECK_REFCOUNT_CRASH(m_nRefCounter > 0);
+        AZ_Assert(m_nRefCounter > 0, "Invalid ref count");
         if (--m_nRefCounter == 0)
         {
             delete this;
@@ -272,13 +273,13 @@ public:
 
     void AddRef()
     {
-        CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0);
+        AZ_Assert(m_nRefCounter >= 0, "Invalid ref count");
         ++m_nRefCounter;
     }
 
     void Release()
     {
-        CHECK_REFCOUNT_CRASH(m_nRefCounter > 0);
+        AZ_Assert(m_nRefCounter > 0, "Invalid ref count");
         if (--m_nRefCounter == 0)
         {
             assert(m_pDeleteFnc);
diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp
index 4ca481be88..85b9ff4b79 100644
--- a/Code/Legacy/CrySystem/IDebugCallStack.cpp
+++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp
@@ -227,7 +227,7 @@ void IDebugCallStack::FatalError(const char* description)
 
 #if defined(WIN32) || !defined(_RELEASE)
     int* p = 0x0;
-    PREFAST_SUPPRESS_WARNING(6011) * p = 1; // we're intentionally crashing here
+    *p = 1; // we're intentionally crashing here
 #endif
 }
 
diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp
index cce3cf4aec..8ea653fb81 100644
--- a/Code/Legacy/CrySystem/SystemInit.cpp
+++ b/Code/Legacy/CrySystem/SystemInit.cpp
@@ -252,7 +252,7 @@ static void CmdCrashTest(IConsoleCmdArgs* pArgs)
         case 1:
         {
             int* p = 0;
-            PREFAST_SUPPRESS_WARNING(6011) * p = 0xABCD;
+            *p = 0xABCD;
         }
         break;
         case 2:
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index 2cc41adc08..1f5dc7d0b0 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -355,32 +355,25 @@ void CSystem::FatalError(const char* format, ...)
     IDebugCallStack::instance()->FatalError(szBuffer);
 #endif
 
-    CryDebugBreak();
-
     // app can not continue
+    AZ::Debug::Trace::Break();
+
 #ifdef _DEBUG
+    #if defined(WIN32) || defined(WIN64)
+        _flushall();
+        // on windows, _exit does all sorts of things which can cause cleanup to fail during a crash, we need to terminate instead.
+        TerminateProcess(GetCurrentProcess(), 1);
+    #endif
 
-#if defined(WIN32) && !defined(WIN64)
-    DEBUG_BREAK;
-#endif
-
-#else
-
-#if defined(WIN32) || defined(WIN64)
-    _flushall();
-    // on windows, _exit does all sorts of things which can cause cleanup to fail during a crash, we need to terminate instead.
-    TerminateProcess(GetCurrentProcess(), 1);
-#endif
-
-#if defined(AZ_RESTRICTED_PLATFORM)
-#define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_2
-#include AZ_RESTRICTED_FILE(SystemWin32_cpp)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-    _exit(1);
-#endif
+    #if defined(AZ_RESTRICTED_PLATFORM)
+        #define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_2
+        #include AZ_RESTRICTED_FILE(SystemWin32_cpp)
+    #endif
+    #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
+        #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
+    #else
+        _exit(1);
+    #endif
 #endif
 }
 
diff --git a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp
index a82e78c08c..3280c8daa9 100644
--- a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp
+++ b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp
@@ -26,7 +26,7 @@
         if (count > 0)                                                                                              \
         {                                                                                                           \
             const size_t memSize = count * sizeof(IViewSystemListener*);                                            \
-            PREFAST_SUPPRESS_WARNING(6255) IViewSystemListener * *pArray = (IViewSystemListener**) alloca(memSize); \
+            IViewSystemListener* *pArray = (IViewSystemListener**) alloca(memSize);                                 \
             memcpy(pArray, &*m_listeners.begin(), memSize);                                                         \
             while (count--)                                                                                         \
             {                                                                                                       \
diff --git a/Code/Legacy/CrySystem/XML/xml.cpp b/Code/Legacy/CrySystem/XML/xml.cpp
index 0493a64ca8..4fec4d3fd9 100644
--- a/Code/Legacy/CrySystem/XML/xml.cpp
+++ b/Code/Legacy/CrySystem/XML/xml.cpp
@@ -1390,7 +1390,7 @@ protected:
     {
         ((XmlParserImp*)userData)->onEndElement(name);
     }
-    static void characterData(void* userData, const char* s, int len) PREFAST_SUPPRESS_WARNING(6262)
+    static void characterData(void* userData, const char* s, int len)
     {
         char str[32700];
         if (len > sizeof(str) - 1)
diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
index d61090f79d..c28c13ba94 100644
--- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
+++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp
@@ -26,12 +26,12 @@
 //////////////////////////////////////////////////////////////////////////
 // Serialization for anim nodes & param types
 #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(eUiAnimNodeType_ ## name) == g_animNodeEnumToStringMap.end()); \
-    g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = STRINGIFY(name);                                                            \
-    g_animNodeStringToEnumMap[string(STRINGIFY(name))] = eUiAnimNodeType_ ## name;
+    g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = AZ_STRINGIZE(name);                                                            \
+    g_animNodeStringToEnumMap[string(AZ_STRINGIZE(name))] = eUiAnimNodeType_ ## name;
 
 #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(eUiAnimParamType_ ## name) == g_animParamEnumToStringMap.end()); \
-    g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = STRINGIFY(name);                                                              \
-    g_animParamStringToEnumMap[string(STRINGIFY(name))] = eUiAnimParamType_ ## name;
+    g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = AZ_STRINGIZE(name);                                                              \
+    g_animParamStringToEnumMap[string(AZ_STRINGIZE(name))] = eUiAnimParamType_ ## name;
 
 namespace
 {
diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
index b781dd6c82..589a084426 100644
--- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
+++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp
@@ -74,12 +74,12 @@ static SMovieSequenceAutoComplete s_movieSequenceAutoComplete;
 //////////////////////////////////////////////////////////////////////////
 // Serialization for anim nodes & param types
 #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(AnimNodeType::name) == g_animNodeEnumToStringMap.end()); \
-    g_animNodeEnumToStringMap[AnimNodeType::name] = STRINGIFY(name);                                                            \
-    g_animNodeStringToEnumMap[string(STRINGIFY(name))] = AnimNodeType::name;
+    g_animNodeEnumToStringMap[AnimNodeType::name] = AZ_STRINGIZE(name);                                                            \
+    g_animNodeStringToEnumMap[string(AZ_STRINGIZE(name))] = AnimNodeType::name;
 
 #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(AnimParamType::name) == g_animParamEnumToStringMap.end()); \
-    g_animParamEnumToStringMap[AnimParamType::name] = STRINGIFY(name);                                                              \
-    g_animParamStringToEnumMap[string(STRINGIFY(name))] = AnimParamType::name;
+    g_animParamEnumToStringMap[AnimParamType::name] = AZ_STRINGIZE(name);                                                              \
+    g_animParamStringToEnumMap[string(AZ_STRINGIZE(name))] = AnimParamType::name;
 
 namespace
 {

From 360d0bdd0bde6fe56b1fdccc9bf017e221f3fd98 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Fri, 6 Aug 2021 16:42:38 -0700
Subject: [PATCH 073/205] removing more unused stuff

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../GridMate/Carrier/SocketDriver.cpp         | 42 +++++-----
 Code/Legacy/CryCommon/AndroidSpecific.h       | 13 ---
 Code/Legacy/CryCommon/AppleSpecific.h         | 67 ---------------
 Code/Legacy/CryCommon/BaseTypes.h             | 47 +++++------
 Code/Legacy/CryCommon/BitFiddling.h           | 40 ---------
 Code/Legacy/CryCommon/CompileTimeAssert.h     | 56 -------------
 Code/Legacy/CryCommon/CryArray.h              |  2 +-
 Code/Legacy/CryCommon/CryCustomTypes.h        |  4 +-
 Code/Legacy/CryCommon/CryHeaders.h            |  2 +-
 Code/Legacy/CryCommon/CryLibrary.h            |  1 -
 Code/Legacy/CryCommon/CryRandomInternal.h     | 27 +++---
 Code/Legacy/CryCommon/CryWindows.h            | 19 -----
 Code/Legacy/CryCommon/IMaterial.h             |  2 +-
 Code/Legacy/CryCommon/ISystem.h               | 83 +++++++++---------
 Code/Legacy/CryCommon/ITexture.h              |  4 +-
 Code/Legacy/CryCommon/Linux32Specific.h       |  8 --
 Code/Legacy/CryCommon/Linux64Specific.h       |  8 --
 Code/Legacy/CryCommon/LinuxSpecific.h         | 84 -------------------
 Code/Legacy/CryCommon/Linux_Win32Wrapper.h    |  2 -
 Code/Legacy/CryCommon/MacSpecific.h           | 34 --------
 Code/Legacy/CryCommon/Options.h               |  2 +-
 Code/Legacy/CryCommon/StringUtils.h           |  4 +-
 Code/Legacy/CryCommon/UnicodeBinding.h        | 42 +++++-----
 Code/Legacy/CryCommon/UnicodeEncoding.h       |  4 +-
 Code/Legacy/CryCommon/UnicodeFunctions.h      |  4 +-
 Code/Legacy/CryCommon/UnicodeIterator.h       |  4 +-
 Code/Legacy/CryCommon/Win32specific.h         |  8 --
 Code/Legacy/CryCommon/Win64specific.h         |  8 --
 Code/Legacy/CryCommon/crycommon_files.cmake   |  2 -
 Code/Legacy/CryCommon/iOSSpecific.h           |  2 -
 Code/Legacy/CryCommon/platform.h              |  1 -
 Code/Legacy/CryCommon/stridedptr.h            |  4 +-
 Code/Legacy/CrySystem/CrySystem_precompiled.h |  2 +-
 .../CrySystem/LevelSystem/LevelSystem.cpp     |  4 -
 Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp |  2 +-
 Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp |  2 +-
 36 files changed, 139 insertions(+), 501 deletions(-)
 delete mode 100644 Code/Legacy/CryCommon/CompileTimeAssert.h
 delete mode 100644 Code/Legacy/CryCommon/CryWindows.h

diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
index b75de6f383..a72c6b54f6 100644
--- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
+++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp
@@ -1528,7 +1528,7 @@ namespace GridMate
         if (0 != WSAIoctl( m_socket, SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, &functionTableId,
             sizeof(GUID), (void**)&m_RIO_FN_TABLE,  sizeof(m_RIO_FN_TABLE), &dwBytes, 0, 0))
         {
-            AZ_Error("GridMate", false, "Could not initialize RIO: %u\n", ::WSAGetLastError());
+            AZ_Error("GridMate", false, "Could not initialize RIO: %u\n", GridMate::Platform::GetSocketError());
             return EC_SOCKET_CREATE;
         }
         else
@@ -1543,13 +1543,13 @@ namespace GridMate
 
             if ((m_events[WakeupOnSend] = WSACreateEvent()) == WSA_INVALID_EVENT)
             {
-                AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
             if ((m_events[ReceiveEvent] = WSACreateEvent()) == WSA_INVALID_EVENT)
             {
-                AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
             RIO_NOTIFICATION_COMPLETION typeRecv;
@@ -1559,13 +1559,13 @@ namespace GridMate
             m_RIORecvQueue = m_RIO_FN_TABLE.RIOCreateCompletionQueue(maxOutstandingReceive, &typeRecv);
             if (m_RIORecvQueue == RIO_INVALID_CQ)
             {
-                AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
             if ((m_events[SendEvent] = WSACreateEvent()) == WSA_INVALID_EVENT)
             {
-                AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
             RIO_NOTIFICATION_COMPLETION typeSend;
@@ -1575,7 +1575,7 @@ namespace GridMate
             m_RIOSendQueue = m_RIO_FN_TABLE.RIOCreateCompletionQueue(maxOutstandingSend, &typeSend);
             if (m_RIOSendQueue == RIO_INVALID_CQ)
             {
-                AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
@@ -1583,7 +1583,7 @@ namespace GridMate
                 maxReceiveDataBuffers, maxOutstandingSend, maxSendDataBuffers, m_RIORecvQueue,  m_RIOSendQueue, pContext);
             if (m_requestQueue == RIO_INVALID_RQ)
             {
-                AZ_Error("GridMate", m_requestQueue != NULL, "Could not RIOCreateRequestQueue: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", m_requestQueue != NULL, "Could not RIOCreateRequestQueue: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
@@ -1596,24 +1596,24 @@ namespace GridMate
             //Setup Recv raw buffer and RIO record
             if (nullptr == (m_rawRecvBuffer = AllocRIOBuffer(bufferSize, m_RIORecvBufferCount, &recvAllocated)))
             {
-                AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
             if (RIO_INVALID_BUFFERID == (recvBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawRecvBuffer, bufferSize * m_RIORecvBufferCount)))
             {
-                AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
             //Setup Recv address raw buffer and RIO record
             if (nullptr == (m_rawRecvAddressBuffer = AllocRIOBuffer(sizeof(SOCKADDR_INET), m_RIORecvBufferCount, &recvAddrsAllocated)))
             {
-                AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
             if (RIO_INVALID_BUFFERID == (recvAddressBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawRecvAddressBuffer, sizeof(SOCKADDR_INET) * m_RIORecvBufferCount)))
             {
-                AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
@@ -1640,7 +1640,7 @@ namespace GridMate
                 //Start Receive Handler
                 if (false == m_RIO_FN_TABLE.RIOReceiveEx(m_requestQueue, &m_RIORecvBuffer[i], 1, NULL, &m_RIORecvAddressBuffer[i], NULL, NULL, 0, pBuffer))
                 {
-                    AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", ::WSAGetLastError());
+                    AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", GridMate::Platform::GetSocketError());
                     return EC_SOCKET_CREATE;
                 }
             }
@@ -1650,25 +1650,25 @@ namespace GridMate
             //setup send raw buffer and RIO record
             if (nullptr == (m_rawSendBuffer = AllocRIOBuffer(bufferSize, m_RIOSendBufferCount, &sendAllocated)))
             {
-                AZ_Error("GridMate", false, "Could not allocate buffer: %u", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not allocate buffer: %u", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
             if (RIO_INVALID_BUFFERID == (sendBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawSendBuffer, m_RIOSendBufferCount * bufferSize)))
             {
-                AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
             //setup send address raw buffer and RIO record
             if (nullptr == (m_rawSendAddressBuffer = AllocRIOBuffer(sizeof(SOCKADDR_INET), m_RIOSendBufferCount, &sendAddrsAllocated)))
             {
-                AZ_Error("GridMate", false, "Could not allocate send address buffer: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not allocate send address buffer: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
             if (RIO_INVALID_BUFFERID == (sendAddressBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawSendAddressBuffer, m_RIOSendBufferCount * sizeof(SOCKADDR_INET))))
             {
-                AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError());
                 return EC_SOCKET_CREATE;
             }
 
@@ -1726,7 +1726,7 @@ namespace GridMate
                     if (!m_RIO_FN_TABLE.RIOSendEx(m_requestQueue, &m_RIOSendBuffer[m_workerNextSendBuffer],
                         bufferCount, NULL, &m_RIOSendAddressBuffer[m_workerNextSendBuffer], NULL, NULL, 0, 0))
                     {
-                        const DWORD lastError = ::WSAGetLastError();
+                        const DWORD lastError = GridMate::Platform::GetSocketError();
                         if (lastError == WSAENOBUFS)
                         {
                             continue;   //spin until free
@@ -1836,7 +1836,7 @@ namespace GridMate
             if (false == m_RIO_FN_TABLE.RIOReceiveEx(m_requestQueue, &m_RIORecvBuffer[m_RIONextRecvBuffer],
                 bufferCount, NULL, &m_RIORecvAddressBuffer[m_RIONextRecvBuffer], NULL, NULL, 0, 0))
             {
-                AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", ::WSAGetLastError());
+                AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", GridMate::Platform::GetSocketError());
             }
 
             if (recvd)
@@ -1867,7 +1867,7 @@ namespace GridMate
         {
             if (!WSAResetEvent(m_events[Index - WSA_WAIT_EVENT_0]))
             {
-                AZ_Assert(false, "WSAResetEvent failed with error = %d\n", ::WSAGetLastError());
+                AZ_Assert(false, "WSAResetEvent failed with error = %d\n", GridMate::Platform::GetSocketError());
             }
         };
 
@@ -1926,7 +1926,7 @@ namespace GridMate
         }
         else if (isFailed(Index))
         {
-            AZ_Assert(false, "WSAWaitForMultipleEvents failed with error = %d\n", ::WSAGetLastError());
+            AZ_Assert(false, "WSAWaitForMultipleEvents failed with error = %d\n", GridMate::Platform::GetSocketError());
             return false;
         }
         else
@@ -1945,7 +1945,7 @@ namespace GridMate
     {
         if (!SetEvent(m_events[WakeupOnSend])) //Wake thread
         {
-            AZ_Assert(false, "SetEvent failed with error = %d\n", ::WSAGetLastError());
+            AZ_Assert(false, "SetEvent failed with error = %d\n", GridMate::Platform::GetSocketError());
         }
     }
 
diff --git a/Code/Legacy/CryCommon/AndroidSpecific.h b/Code/Legacy/CryCommon/AndroidSpecific.h
index a0f57553ca..cf4359ba47 100644
--- a/Code/Legacy/CryCommon/AndroidSpecific.h
+++ b/Code/Legacy/CryCommon/AndroidSpecific.h
@@ -30,15 +30,6 @@
 #define MOBILE
 #endif
 
-// Force all allocations to be aligned to TARGET_DEFAULT_ALIGN.
-// This is because malloc on Android 32 bit returns memory that is not aligned
-// to what some structs/classes need.
-#define CRY_FORCE_MALLOC_NEW_ALIGN
-
-#define RC_EXECUTABLE "rc"
-#define USE_CRT 1
-#define SIZEOF_PTR 4
-
 //////////////////////////////////////////////////////////////////////////
 // Standard includes.
 //////////////////////////////////////////////////////////////////////////
@@ -120,10 +111,6 @@ typedef unsigned char               byte;
 
 #define DEFINE_ALIGNED_DATA(type, name, alignment) \
     type __attribute__ ((aligned(alignment))) name;
-#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \
-    static type __attribute__ ((aligned(alignment))) name;
-#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \
-    const type __attribute__ ((aligned(alignment))) name;
 
 #include "LinuxSpecific.h"
 // these functions do not exist int the wchar.h header
diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h
index ed76de8986..87aea0fbb5 100644
--- a/Code/Legacy/CryCommon/AppleSpecific.h
+++ b/Code/Legacy/CryCommon/AppleSpecific.h
@@ -17,9 +17,6 @@
 #pragma diagnostic ignore "-W#pragma-messages"
 #endif
 
-
-#define RC_EXECUTABLE "rc"
-
 //////////////////////////////////////////////////////////////////////////
 // Standard includes.
 //////////////////////////////////////////////////////////////////////////
@@ -260,10 +257,6 @@ typedef uint64 __uint64;
 
 #define DEFINE_ALIGNED_DATA(type, name, alignment) \
     type __attribute__ ((aligned(alignment))) name;
-#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \
-    static type __attribute__ ((aligned(alignment))) name;
-#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \
-    const type __attribute__ ((aligned(alignment))) name;
 
 #define BST_UNCHECKED   0x0000
 
@@ -296,17 +289,6 @@ enum
     IDCONTINUE  = 11
 };
 
-#define ES_MULTILINE    0x0004L
-#define ES_AUTOVSCROLL  0x0040L
-#define ES_AUTOHSCROLL  0x0080L
-#define ES_WANTRETURN   0x1000L
-
-#define LB_ERR  (-1)
-
-#define LB_ADDSTRING    0x0180
-#define LB_GETCOUNT     0x018B
-#define LB_SETTOPINDEX  0x0197
-
 #define MB_OK                0x00000000L
 #define MB_OKCANCEL          0x00000001L
 #define MB_ABORTRETRYIGNORE  0x00000002L
@@ -326,22 +308,16 @@ enum
 
 #define MB_APPLMODAL    0x00000000L
 
-#define MF_STRING   0x00000000L
-
 #define MK_LBUTTON  0x0001
 #define MK_RBUTTON  0x0002
 #define MK_SHIFT    0x0004
 #define MK_CONTROL  0x0008
 #define MK_MBUTTON  0x0010
 
-#define MK_ALT  ( 0x20 )
-
 #define SM_MOUSEPRESENT 0x00000000L
 
 #define SM_CMOUSEBUTTONS    43
 
-#define USER_TIMER_MINIMUM  0x0000000A
-
 #define VK_TAB      0x09
 #define VK_SHIFT    0x10
 #define VK_MENU     0x12
@@ -349,11 +325,6 @@ enum
 #define VK_SPACE    0x20
 #define VK_DELETE   0x2E
 
-#define VK_NUMPAD1  0x61
-#define VK_NUMPAD2  0x62
-#define VK_NUMPAD3  0x63
-#define VK_NUMPAD4  0x64
-
 #define VK_OEM_COMMA    0xBC   // ',' any country
 #define VK_OEM_PERIOD   0xBE   // '.' any country
 #define VK_OEM_3        0xC0   // '`~' for US
@@ -496,36 +467,6 @@ typedef HANDLE HMENU;
 
 #endif //__cplusplus
 
-inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength)
-{
-    char path[PATH_MAX];
-    
-    if (realpath(relPath, path) == NULL)
-    {
-        return NULL;
-    }
-    const size_t len = std::min(strlen(path), maxLength - 1);
-    memcpy(absPath, path, len);
-    absPath[len] = 0;
-    return absPath;
-}
-
-typedef union _LARGE_INTEGER
-{
-    struct
-    {
-        DWORD LowPart;
-        LONG HighPart;
-    };
-    struct
-    {
-        DWORD LowPart;
-        LONG HighPart;
-    } u;
-
-    long long QuadPart;
-} LARGE_INTEGER;
-
 extern bool QueryPerformanceCounter(LARGE_INTEGER*);
 extern bool QueryPerformanceFrequency(LARGE_INTEGER* frequency);
 
@@ -566,14 +507,6 @@ inline int closesocket(int s)
     return ::close(s);
 }
 
-inline int WSAGetLastError()
-{
-    return errno;
-}
-
-//we take the definition of the pthread_t type directly from the pthread file
-#define THREADID_NULL 0
-
 template 
 char (*RtlpNumberOf( T (&)[N] ))[N];
 
diff --git a/Code/Legacy/CryCommon/BaseTypes.h b/Code/Legacy/CryCommon/BaseTypes.h
index e8b6ae8ab7..0c588184a5 100644
--- a/Code/Legacy/CryCommon/BaseTypes.h
+++ b/Code/Legacy/CryCommon/BaseTypes.h
@@ -11,12 +11,9 @@
 #define CRYINCLUDE_CRYCOMMON_BASETYPES_H
 #pragma once
 
-#include "CompileTimeAssert.h"
-
-
-COMPILE_TIME_ASSERT(sizeof(char) == 1);
-COMPILE_TIME_ASSERT(sizeof(float) == 4);
-COMPILE_TIME_ASSERT(sizeof(int) >= 4);
+static_assert(sizeof(char) == 1);
+static_assert(sizeof(float) == 4);
+static_assert(sizeof(int) >= 4);
 
 
 typedef unsigned char  uchar;
@@ -36,35 +33,35 @@ typedef signed   long  slong;
 typedef unsigned long long ulonglong;
 typedef signed   long long slonglong;
 
-COMPILE_TIME_ASSERT(sizeof(uchar)     == sizeof(schar));
-COMPILE_TIME_ASSERT(sizeof(ushort)    == sizeof(sshort));
-COMPILE_TIME_ASSERT(sizeof(uint)      == sizeof(sint));
-COMPILE_TIME_ASSERT(sizeof(ulong)     == sizeof(slong));
-COMPILE_TIME_ASSERT(sizeof(ulonglong) == sizeof(slonglong));
+static_assert(sizeof(uchar)     == sizeof(schar));
+static_assert(sizeof(ushort)    == sizeof(sshort));
+static_assert(sizeof(uint)      == sizeof(sint));
+static_assert(sizeof(ulong)     == sizeof(slong));
+static_assert(sizeof(ulonglong) == sizeof(slonglong));
 
-COMPILE_TIME_ASSERT(sizeof(uchar)  <= sizeof(ushort));
-COMPILE_TIME_ASSERT(sizeof(ushort) <= sizeof(uint));
-COMPILE_TIME_ASSERT(sizeof(uint)   <= sizeof(ulong));
-COMPILE_TIME_ASSERT(sizeof(ulong)  <= sizeof(ulonglong));
+static_assert(sizeof(uchar)  <= sizeof(ushort));
+static_assert(sizeof(ushort) <= sizeof(uint));
+static_assert(sizeof(uint)   <= sizeof(ulong));
+static_assert(sizeof(ulong)  <= sizeof(ulonglong));
 
 
 typedef schar int8;
 typedef schar sint8;
 typedef uchar uint8;
-COMPILE_TIME_ASSERT(sizeof(uint8) == 1);
-COMPILE_TIME_ASSERT(sizeof(sint8) == 1);
+static_assert(sizeof(uint8) == 1);
+static_assert(sizeof(sint8) == 1);
 
 typedef sshort int16;
 typedef sshort sint16;
 typedef ushort uint16;
-COMPILE_TIME_ASSERT(sizeof(uint16) == 2);
-COMPILE_TIME_ASSERT(sizeof(sint16) == 2);
+static_assert(sizeof(uint16) == 2);
+static_assert(sizeof(sint16) == 2);
 
 typedef sint int32;
 typedef sint sint32;
 typedef uint uint32;
-COMPILE_TIME_ASSERT(sizeof(uint32) == 4);
-COMPILE_TIME_ASSERT(sizeof(sint32) == 4);
+static_assert(sizeof(uint32) == 4);
+static_assert(sizeof(sint32) == 4);
 
 typedef slonglong int64;
 
@@ -72,14 +69,14 @@ typedef slonglong int64;
 #define O3DE_INT64_DEFINED
 typedef slonglong sint64;
 typedef ulonglong uint64;
-COMPILE_TIME_ASSERT(sizeof(uint64) == 8);
-COMPILE_TIME_ASSERT(sizeof(sint64) == 8);
+static_assert(sizeof(uint64) == 8);
+static_assert(sizeof(sint64) == 8);
 #endif
 
 
 typedef float  f32;
 typedef double f64;
-COMPILE_TIME_ASSERT(sizeof(f32) == 4);
-COMPILE_TIME_ASSERT(sizeof(f64) == 8);
+static_assert(sizeof(f32) == 4);
+static_assert(sizeof(f64) == 8);
 
 #endif // CRYINCLUDE_CRYCOMMON_BASETYPES_H
diff --git a/Code/Legacy/CryCommon/BitFiddling.h b/Code/Legacy/CryCommon/BitFiddling.h
index 342aad9a82..36173c5e53 100644
--- a/Code/Legacy/CryCommon/BitFiddling.h
+++ b/Code/Legacy/CryCommon/BitFiddling.h
@@ -12,7 +12,6 @@
 
 #pragma once
 
-#include "CompileTimeAssert.h"
 #include 
 
 // Section dictionary
@@ -188,45 +187,6 @@ ILINE int32 Isel32(int32 v, int32 alt)
     return ((static_cast(v) >> 31) & alt) | ((static_cast(~v) >> 31) & v);
 }
 
-template 
-struct CompileTimeIntegerLog2
-{
-    static const uint32 result = 1 + CompileTimeIntegerLog2<(ILOG >> 1)>::result;
-};
-template <>
-struct CompileTimeIntegerLog2<1>
-{
-    static const uint32 result = 0;
-};
-template <>
-struct CompileTimeIntegerLog2<0>; // keep it undefined, we cannot represent "minus infinity" result
-
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<1>::result == 0);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<2>::result == 1);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<3>::result == 1);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<4>::result == 2);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<5>::result == 2);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<255>::result == 7);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<256>::result == 8);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<257>::result == 8);
-
-template 
-struct CompileTimeIntegerLog2_RoundUp
-{
-    static const uint32 result = CompileTimeIntegerLog2::result + ((ILOG & (ILOG - 1)) != 0);
-};
-template <>
-struct CompileTimeIntegerLog2_RoundUp<0>; // we can return 0, but let's keep it undefined (same as CompileTimeIntegerLog2<0>)
-
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<1>::result == 0);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<2>::result == 1);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<3>::result == 2);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<4>::result == 2);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<5>::result == 3);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<255>::result == 8);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<256>::result == 8);
-COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<257>::result == 9);
-
 // Character-to-bitfield mapping
 
 inline uint32 AlphaBit(char c)
diff --git a/Code/Legacy/CryCommon/CompileTimeAssert.h b/Code/Legacy/CryCommon/CompileTimeAssert.h
deleted file mode 100644
index 80a2ecf6bf..0000000000
--- a/Code/Legacy/CryCommon/CompileTimeAssert.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-// Inspired by the Boost library's BOOST_STATIC_ASSERT(),
-// see http://www.boost.org/doc/libs/1_49_0/doc/html/boost_staticassert/how.html
-// or http://www.boost.org/libs/static_assert
-
-#ifndef CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H
-#define CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H
-#pragma once
-
-#if defined(__cplusplus)
-/*
-template 
-struct COMPILE_TIME_ASSERT_FAIL;
-
-template <>
-struct COMPILE_TIME_ASSERT_FAIL
-{
-};
-
-template 
-struct COMPILE_TIME_ASSERT_TEST
-{
-    enum { dummy = i };
-};
-
-#define COMPILE_TIME_ASSERT_BUILD_NAME2(x, y) x##y
-#define COMPILE_TIME_ASSERT_BUILD_NAME1(x, y) COMPILE_TIME_ASSERT_BUILD_NAME2(x, y)
-#define COMPILE_TIME_ASSERT_BUILD_NAME(x, y) COMPILE_TIME_ASSERT_BUILD_NAME1(x, y)
-
-#ifndef __RECODE__
-    #define COMPILE_TIME_ASSERT(expr) \
-        typedef COMPILE_TIME_ASSERT_TEST)> \
-        COMPILE_TIME_ASSERT_BUILD_NAME(compile_time_assert_test_, __LINE__)
-    // note: for MS Visual Studio we could use __COUNTER__ instead of __LINE__
-#else
-    #define COMPILE_TIME_ASSERT(expr)
-#endif  // __RECODE__
-
-#else
-
-#define COMPILE_TIME_ASSERT(expr)
-*/
-#endif
-
-#define COMPILE_TIME_ASSERT_MSG(expr, msg) static_assert(expr, msg)
-#define COMPILE_TIME_ASSERT(expr) COMPILE_TIME_ASSERT_MSG(expr, "Compile Time Assert")
-
-
-#endif // CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H
diff --git a/Code/Legacy/CryCommon/CryArray.h b/Code/Legacy/CryCommon/CryArray.h
index 5b4684fdd2..ac935e5c45 100644
--- a/Code/Legacy/CryCommon/CryArray.h
+++ b/Code/Legacy/CryCommon/CryArray.h
@@ -771,7 +771,7 @@ namespace NArray
 
             AP& allocator()
             {
-                COMPILE_TIME_ASSERT(sizeof(AP) == sizeof(A));
+                static_assert(sizeof(AP) == sizeof(A));
                 return *(AP*)this;
             }
             const AP& allocator() const
diff --git a/Code/Legacy/CryCommon/CryCustomTypes.h b/Code/Legacy/CryCommon/CryCustomTypes.h
index 9594f5a333..3b5b62e2f6 100644
--- a/Code/Legacy/CryCommon/CryCustomTypes.h
+++ b/Code/Legacy/CryCommon/CryCustomTypes.h
@@ -708,8 +708,8 @@ protected:
 
     static inline S FromFloat(float fIn)
     {
-        COMPILE_TIME_ASSERT(sizeof(S) <= 4);
-        COMPILE_TIME_ASSERT(nEXP_BITS > 0 && nEXP_BITS <= 8 && nEXP_BITS < sizeof(S) * 8 - 4);
+        static_assert(sizeof(S) <= 4);
+        static_assert(nEXP_BITS > 0 && nEXP_BITS <= 8 && nEXP_BITS < sizeof(S) * 8 - 4);
 
         // Clamp to allowed range.
         float fClamped = clamp_tpl(fIn * fROUNDER(), fMIN(), fMAX());
diff --git a/Code/Legacy/CryCommon/CryHeaders.h b/Code/Legacy/CryCommon/CryHeaders.h
index 6b4ea0ba3a..4d037b52d9 100644
--- a/Code/Legacy/CryCommon/CryHeaders.h
+++ b/Code/Legacy/CryCommon/CryHeaders.h
@@ -17,7 +17,7 @@
 
 #ifdef MAX_SUB_MATERIALS
 // This checks that the values are in sync in the different files.
-COMPILE_TIME_ASSERT(MAX_SUB_MATERIALS == 128);
+static_assert(MAX_SUB_MATERIALS == 128);
 #else
     #define MAX_SUB_MATERIALS 128
 #endif
diff --git a/Code/Legacy/CryCommon/CryLibrary.h b/Code/Legacy/CryCommon/CryLibrary.h
index ca1ca5d067..787085af00 100644
--- a/Code/Legacy/CryCommon/CryLibrary.h
+++ b/Code/Legacy/CryCommon/CryLibrary.h
@@ -63,7 +63,6 @@ using DetachEnvironmentFunction = void(*)();
     #if !defined(WIN32_LEAN_AND_MEAN)
         #define WIN32_LEAN_AND_MEAN
     #endif
-    #include 
 
     HMODULE CryLoadLibrary(const char* libName);
     
diff --git a/Code/Legacy/CryCommon/CryRandomInternal.h b/Code/Legacy/CryCommon/CryRandomInternal.h
index 9499ba0774..ca74041189 100644
--- a/Code/Legacy/CryCommon/CryRandomInternal.h
+++ b/Code/Legacy/CryCommon/CryRandomInternal.h
@@ -13,7 +13,6 @@
 #include   // std::numeric_limits
 #include   // std::make_unsigned
 #include "BaseTypes.h"  // uint32, uint64
-#include "CompileTimeAssert.h"
 #include "Cry_Vector2.h"
 #include "Cry_Vector3.h"
 #include "Cry_Vector4.h"
@@ -24,10 +23,10 @@ namespace CryRandom_Internal
     template 
     struct BoundedRandomUint
     {
-        COMPILE_TIME_ASSERT(std::numeric_limits::is_integer);
-        COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed);
-        COMPILE_TIME_ASSERT(sizeof(T) == size);
-        COMPILE_TIME_ASSERT(sizeof(T) <= sizeof(uint32));
+        static_assert(std::numeric_limits::is_integer);
+        static_assert(!std::numeric_limits::is_signed);
+        static_assert(sizeof(T) == size);
+        static_assert(sizeof(T) <= sizeof(uint32));
 
         inline static T Get(R& randomGenerator, const T maxValue)
         {
@@ -41,9 +40,9 @@ namespace CryRandom_Internal
     template 
     struct BoundedRandomUint
     {
-        COMPILE_TIME_ASSERT(std::numeric_limits::is_integer);
-        COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed);
-        COMPILE_TIME_ASSERT(sizeof(T) == sizeof(uint64));
+        static_assert(std::numeric_limits::is_integer);
+        static_assert(!std::numeric_limits::is_signed);
+        static_assert(sizeof(T) == sizeof(uint64));
 
         inline static T Get(R& randomGenerator, const T maxValue)
         {
@@ -65,11 +64,11 @@ namespace CryRandom_Internal
     template 
     struct BoundedRandom
     {
-        COMPILE_TIME_ASSERT(std::numeric_limits::is_integer);
+        static_assert(std::numeric_limits::is_integer);
         typedef typename std::make_unsigned::type UT;
-        COMPILE_TIME_ASSERT(sizeof(T) == sizeof(UT));
-        COMPILE_TIME_ASSERT(std::numeric_limits::is_integer);
-        COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed);
+        static_assert(sizeof(T) == sizeof(UT));
+        static_assert(std::numeric_limits::is_integer);
+        static_assert(!std::numeric_limits::is_signed);
 
         inline static T Get(R& randomGenerator, T minValue, T maxValue)
         {
@@ -84,7 +83,7 @@ namespace CryRandom_Internal
     template 
     struct BoundedRandom
     {
-        COMPILE_TIME_ASSERT(!std::numeric_limits::is_integer);
+        static_assert(!std::numeric_limits::is_integer);
 
         inline static T Get(R& randomGenerator, const T minValue, const T maxValue)
         {
@@ -139,7 +138,7 @@ namespace CryRandom_Internal
     inline VT GetRandomUnitVector(R& randomGenerator)
     {
         typedef typename VT::value_type T;
-        COMPILE_TIME_ASSERT(!std::numeric_limits::is_integer);
+        static_assert(!std::numeric_limits::is_integer);
 
         VT res;
         T lenSquared;
diff --git a/Code/Legacy/CryCommon/CryWindows.h b/Code/Legacy/CryCommon/CryWindows.h
deleted file mode 100644
index 77684384c6..0000000000
--- a/Code/Legacy/CryCommon/CryWindows.h
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-// Description : Specific header to handle Windows.h include
-
-
-#ifndef CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H
-#define CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H
-#pragma once
-
-#include 
-
-#endif // CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H
diff --git a/Code/Legacy/CryCommon/IMaterial.h b/Code/Legacy/CryCommon/IMaterial.h
index f1967324d8..c5cd5712dc 100644
--- a/Code/Legacy/CryCommon/IMaterial.h
+++ b/Code/Legacy/CryCommon/IMaterial.h
@@ -41,7 +41,7 @@ struct IRenderMesh;
 
 #ifdef MAX_SUB_MATERIALS
 // This checks that the values are in sync in the different files.
-COMPILE_TIME_ASSERT(MAX_SUB_MATERIALS == 128);
+static_assert(MAX_SUB_MATERIALS == 128);
 #else
 #define MAX_SUB_MATERIALS 128
 #endif
diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h
index 7cea690687..2820a2fd8d 100644
--- a/Code/Legacy/CryCommon/ISystem.h
+++ b/Code/Legacy/CryCommon/ISystem.h
@@ -24,7 +24,6 @@
 #endif
 
 #include "CryAssert.h"
-#include "CompileTimeAssert.h"
 
 #include 
 
@@ -1428,10 +1427,10 @@ namespace Detail
 # define DeclareConstIntCVar(name, defaultValue) enum : int { name = (defaultValue) }
 # define DeclareStaticConstIntCVar(name, defaultValue) enum : int { name = (defaultValue) }
 
-# define DefineConstIntCVarName(strname, name, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, strname, defaultValue); }
-# define DefineConstIntCVar(name, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, (#name), defaultValue); }
+# define DefineConstIntCVarName(strname, name, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, strname, defaultValue); }
+# define DefineConstIntCVar(name, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, (#name), defaultValue); }
 // DefineConstIntCVar2 is deprecated, any such instance can be converted to the 3 variant by removing the quotes around the first parameter
-# define DefineConstIntCVar3(name, _var_, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(_var_)); REGISTER_DUMMY_CVAR(int, name, defaultValue); }
+# define DefineConstIntCVar3(name, _var_, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(_var_)); REGISTER_DUMMY_CVAR(int, name, defaultValue); }
 # define AllocateConstIntCVar(scope, name)
 
 # define DefineConstFloatCVar(name, flags, help) { REGISTER_DUMMY_CVAR(float, (#name), name ## Default); }
@@ -1543,33 +1542,33 @@ static void AssertConsoleExists(void)
 #define ILLEGAL_DEV_FLAGS (VF_NET_SYNCED | VF_CHEAT | VF_CHEAT_ALWAYS_CHECK | VF_CHEAT_NOCHECK | VF_READONLY | VF_CONST_CVAR)
 
 #if defined(_RELEASE)
-#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment)                                                               NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val
-#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction)                  NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val /* _onchangefunction consumed; callback not available */
-#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment)                                                        NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
-#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)               NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
-#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment)                                                               NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
-#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)                  NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
-#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment)                                                         NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
-#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment)                                                         NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
-#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment)                                                NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val
-#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)       NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val
-#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment)                                                NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val
-#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)       NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val
+#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment)                                                               NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val
+#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction)                  NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val /* _onchangefunction consumed; callback not available */
+#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment)                                                        NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
+#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)               NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
+#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment)                                                               NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
+#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)                  NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
+#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment)                                                         NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
+#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment)                                                         NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)                                  /* consumed; pure cvar not available */
+#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment)                                                NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val
+#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)       NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val
+#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment)                                                NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val
+#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)       NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val
 #define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment)                                                  /* consumed; command not available */
 #else
-#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment)                                                               REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction)                  REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment)                                                        REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)               REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment)                                                               REGISTER_INT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)                  REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment)                                                         REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment)                                                         REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment)                                                REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)       REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment)                                                REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)       REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment)                                                          REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment)                                                               REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction)                  REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment)                                                        REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)               REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment)                                                               REGISTER_INT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)                  REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment)                                                         REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment)                                                         REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment)                                                REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)       REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment)                                                REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)       REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment)                                                          REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
 #endif // defined(_RELEASE)
 //
 ////////////////////////////////////////////////////////////////////////////////
@@ -1586,19 +1585,19 @@ static void AssertConsoleExists(void)
 // TODO Registering all cvars for Dedicated server as well. Currently CrySystems have no concept of Dedicated server with cmake.
 // If we introduce server specific targets for CrySystems, we can add DEDICATED_SERVER flags to those and add the flag back in here.
 #if defined(_RELEASE)
-#define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment)                                                          REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction)                 REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_STRING_DEDI_ONLY(_name, _def_val, _flags, _comment)                                                       REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_STRING_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)          REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_INT_DEDI_ONLY(_name, _def_val, _flags, _comment)                                                          REGISTER_INT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_INT_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)                 REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_INT64_DEDI_ONLY(_name, _def_val, _flags, _comment)                                                        REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_FLOAT_DEDI_ONLY(_name, _def_val, _flags, _comment)                                                        REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR2_DEDI_ONLY(_name, _var, _def_val, _flags, _comment)                                               REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR2_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)  REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR3_DEDI_ONLY(_name, _var, _def_val, _flags, _comment)                                               REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_CVAR3_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)  REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
-#define REGISTER_COMMAND_DEDI_ONLY(_name, _func, _flags, _comment)                                                         REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment)                                                          REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction)                 REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_STRING_DEDI_ONLY(_name, _def_val, _flags, _comment)                                                       REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_STRING_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)          REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_INT_DEDI_ONLY(_name, _def_val, _flags, _comment)                                                          REGISTER_INT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_INT_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction)                 REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_INT64_DEDI_ONLY(_name, _def_val, _flags, _comment)                                                        REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_FLOAT_DEDI_ONLY(_name, _def_val, _flags, _comment)                                                        REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR2_DEDI_ONLY(_name, _var, _def_val, _flags, _comment)                                               REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR2_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)  REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR3_DEDI_ONLY(_name, _var, _def_val, _flags, _comment)                                               REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_CVAR3_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction)  REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
+#define REGISTER_COMMAND_DEDI_ONLY(_name, _func, _flags, _comment)                                                         REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0)
 #else
 #define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment)                                                          REGISTER_CVAR_DEV_ONLY(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment)
 #define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction)                 REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction)
diff --git a/Code/Legacy/CryCommon/ITexture.h b/Code/Legacy/CryCommon/ITexture.h
index 5b9b43ceb5..170e3b6709 100644
--- a/Code/Legacy/CryCommon/ITexture.h
+++ b/Code/Legacy/CryCommon/ITexture.h
@@ -314,8 +314,8 @@ public:
 
     void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const
     {
-        COMPILE_TIME_ASSERT(eTT_MaxTexType <= 255);
-        COMPILE_TIME_ASSERT(eTF_MaxFormat <= 255);
+        static_assert(eTT_MaxTexType <= 255);
+        static_assert(eTF_MaxFormat <= 255);
         /*LATER*/
     }
 
diff --git a/Code/Legacy/CryCommon/Linux32Specific.h b/Code/Legacy/CryCommon/Linux32Specific.h
index e66838f431..6812ddb818 100644
--- a/Code/Legacy/CryCommon/Linux32Specific.h
+++ b/Code/Legacy/CryCommon/Linux32Specific.h
@@ -18,10 +18,6 @@
 #define _CPU_X86
 //#define _CPU_SSE
 
-#define RC_EXECUTABLE "rc"
-#define USE_CRT 1
-#define SIZEOF_PTR 4
-
 //////////////////////////////////////////////////////////////////////////
 // Standard includes.
 //////////////////////////////////////////////////////////////////////////
@@ -97,10 +93,6 @@ typedef unsigned char       byte;
 
 #define DEFINE_ALIGNED_DATA(type, name, alignment) \
     type __attribute__ ((aligned(alignment))) name;
-#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \
-    static type __attribute__ ((aligned(alignment))) name;
-#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \
-    const type __attribute__ ((aligned(alignment))) name;
 
 #include "LinuxSpecific.h"
 
diff --git a/Code/Legacy/CryCommon/Linux64Specific.h b/Code/Legacy/CryCommon/Linux64Specific.h
index 0aa9321025..4dcb5f1e84 100644
--- a/Code/Legacy/CryCommon/Linux64Specific.h
+++ b/Code/Legacy/CryCommon/Linux64Specific.h
@@ -20,10 +20,6 @@
 #define _CPU_AMD64
 #define _CPU_SSE
 
-#define RC_EXECUTABLE "rc"
-#define USE_CRT 1
-#define SIZEOF_PTR 8
-
 //////////////////////////////////////////////////////////////////////////
 // Standard includes.
 //////////////////////////////////////////////////////////////////////////
@@ -103,10 +99,6 @@ typedef uint8               byte;
 
 #define DEFINE_ALIGNED_DATA(type, name, alignment) \
     type __attribute__ ((aligned(alignment))) name;
-#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \
-    static type __attribute__ ((aligned(alignment))) name;
-#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \
-    const type __attribute__ ((aligned(alignment))) name;
 
 #include "LinuxSpecific.h"
 
diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h
index cbffae5957..a587350cb2 100644
--- a/Code/Legacy/CryCommon/LinuxSpecific.h
+++ b/Code/Legacy/CryCommon/LinuxSpecific.h
@@ -182,7 +182,6 @@ typedef int64 __int64;
 typedef uint64 __uint64;
 #endif
 
-#define THREADID_NULL -1
 typedef unsigned long int threadID;
 
 #define TRUE 1
@@ -213,27 +212,6 @@ typedef unsigned long int threadID;
 
 #define _wtof(str) wcstod(str, 0)
 
-/*static unsigned char toupper(unsigned char c)
-{
-  return c & ~0x40;
-}
-*/
-typedef union _LARGE_INTEGER
-{
-    struct
-    {
-        DWORD LowPart;
-        LONG HighPart;
-    };
-    struct
-    {
-        DWORD LowPart;
-        LONG HighPart;
-    } u;
-    long long QuadPart;
-} LARGE_INTEGER;
-
-
 // stdlib.h stuff
 #define _MAX_DRIVE  3   // max. length of drive component
 #define _MAX_DIR    256 // max. length of path component
@@ -257,21 +235,6 @@ typedef union _LARGE_INTEGER
 #define _O_SEQUENTIAL   0x0020  /* file access is primarily sequential */
 #define _O_RANDOM       0x0010  /* file access is primarily random */
 
-// curses.h stubs for PDcurses keys
-#define PADENTER    KEY_MAX + 1
-#define CTL_HOME    KEY_MAX + 2
-#define CTL_END     KEY_MAX + 3
-#define CTL_PGDN    KEY_MAX + 4
-#define CTL_PGUP    KEY_MAX + 5
-
-// stubs for virtual keys, isn't used on Linux
-#define VK_UP               0
-#define VK_DOWN         0
-#define VK_RIGHT        0
-#define VK_LEFT         0
-#define VK_CONTROL  0
-#define VK_SCROLL       0
-
 enum
 {
     IDOK        = 1,
@@ -285,17 +248,6 @@ enum
     IDCONTINUE  = 11
 };
 
-#define ES_MULTILINE    0x0004L
-#define ES_AUTOVSCROLL  0x0040L
-#define ES_AUTOHSCROLL  0x0080L
-#define ES_WANTRETURN   0x1000L
-
-#define LB_ERR  (-1)
-
-#define LB_ADDSTRING    0x0180
-#define LB_GETCOUNT     0x018B
-#define LB_SETTOPINDEX  0x0197
-
 #define MB_OK                0x00000000L
 #define MB_OKCANCEL          0x00000001L
 #define MB_ABORTRETRYIGNORE  0x00000002L
@@ -315,22 +267,16 @@ enum
 
 #define MB_APPLMODAL    0x00000000L
 
-#define MF_STRING   0x00000000L
-
 #define MK_LBUTTON  0x0001
 #define MK_RBUTTON  0x0002
 #define MK_SHIFT    0x0004
 #define MK_CONTROL  0x0008
 #define MK_MBUTTON  0x0010
 
-#define MK_ALT  ( 0x20 )
-
 #define SM_MOUSEPRESENT 0x00000000L
 
 #define SM_CMOUSEBUTTONS    43
 
-#define USER_TIMER_MINIMUM  0x0000000A
-
 #define VK_TAB      0x09
 #define VK_SHIFT    0x10
 #define VK_MENU     0x12
@@ -338,11 +284,6 @@ enum
 #define VK_SPACE    0x20
 #define VK_DELETE   0x2E
 
-#define VK_NUMPAD1  0x61
-#define VK_NUMPAD2  0x62
-#define VK_NUMPAD3  0x63
-#define VK_NUMPAD4  0x64
-
 #define VK_OEM_COMMA    0xBC   // ',' any country
 #define VK_OEM_PERIOD   0xBE   // '.' any country
 #define VK_OEM_3        0xC0   // '`~' for US
@@ -529,36 +470,11 @@ inline int64 CryGetTicksPerSec()
 
 inline int _CrtCheckMemory() { return 1; };
 
-inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength)
-{
-    char path[PATH_MAX];
-
-    if (realpath(relPath, path) == NULL)
-    {
-        return NULL;
-    }
-    const size_t len = std::min(strlen(path), maxLength - 1);
-    memcpy(absPath, path, len);
-    absPath[len] = 0;
-    return absPath;
-}
-
 typedef void* HGLRC;
 typedef void* HDC;
 typedef void* PROC;
 typedef void* PIXELFORMATDESCRIPTOR;
 
-#define SCOPED_ENABLE_FLOAT_EXCEPTIONS
-
-// Linux_Win32Wrapper.h now included directly by platform.h
-//#include "Linux_Win32Wrapper.h"
-
-#define closesocket close
-inline int WSAGetLastError()
-{
-    return errno;
-}
-
 template 
 char (*RtlpNumberOf( T (&)[N] ))[N];
 
diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
index 23cd7faf7f..2de17e6b28 100644
--- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
+++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h
@@ -490,8 +490,6 @@ extern void adaptFilenameToLinux(char* rAdjustedFilename);
 extern const int comparePathNames(const char* cpFirst, const char* cpSecond, unsigned int len);//returns 0 if identical
 extern void replaceDoublePathFilename(char* szFileName);//removes "\.\" to "\" and "/./" to "/"
 
-//////////////////////////////////////////////////////////////////////////
-extern char* _fullpath(char* absPath, const char* relPath, size_t maxLength);
 //////////////////////////////////////////////////////////////////////////
 extern void _makepath(char* path, const char* drive, const char* dir, const char* filename, const char* ext);
 
diff --git a/Code/Legacy/CryCommon/MacSpecific.h b/Code/Legacy/CryCommon/MacSpecific.h
index 30bcd6c6db..0533a1b556 100644
--- a/Code/Legacy/CryCommon/MacSpecific.h
+++ b/Code/Legacy/CryCommon/MacSpecific.h
@@ -24,40 +24,6 @@
 #define _CPU_SSE
 #define PLATFORM_64BIT
 
-#define USE_CRT 1
-#define SIZEOF_PTR 8
-
 typedef uint64_t threadID;
 
-
-// curses.h stubs for PDcurses keys
-#define PADENTER    KEY_MAX + 1
-#define CTL_HOME    KEY_MAX + 2
-#define CTL_END     KEY_MAX + 3
-#define CTL_PGDN    KEY_MAX + 4
-#define CTL_PGUP    KEY_MAX + 5
-
-// stubs for virtual keys, isn't used on Mac
-#define VK_UP               0
-#define VK_DOWN         0
-#define VK_RIGHT        0
-#define VK_LEFT         0
-#define VK_CONTROL  0
-#define VK_SCROLL       0
-
-#define MAC_NOT_IMPLEMENTED assert(false);
-
-
-typedef enum
-{
-    eDAContinue,
-    eDAIgnore,
-    eDAIgnoreAll,
-    eDABreak,
-    eDAStop,
-    eDAReportAsBug
-} EDialogAction;
-
-extern EDialogAction MacOSXHandleAssert(const char* condition, const char* file, int line, const char* reason, bool);
-
 #endif // CRYINCLUDE_CRYCOMMON_MACSPECIFIC_H
diff --git a/Code/Legacy/CryCommon/Options.h b/Code/Legacy/CryCommon/Options.h
index 925f1f747e..935c8bd371 100644
--- a/Code/Legacy/CryCommon/Options.h
+++ b/Code/Legacy/CryCommon/Options.h
@@ -80,7 +80,7 @@ private:
     typedef Struc TThis; typedef Int TInt;                                                      \
     TInt Mask() const { return *(const TInt*)this; }                                            \
     TInt& Mask() { return *(TInt*)this; }                                                       \
-    Struc(TInt init = 0) { COMPILE_TIME_ASSERT(sizeof(TThis) == sizeof(TInt)); Mask() = init; } \
+    Struc(TInt init = 0) { static_assert(sizeof(TThis) == sizeof(TInt)); Mask() = init; } \
 
 #define BIT_VAR(Var)                                     \
     TInt _##Var : 1;                                     \
diff --git a/Code/Legacy/CryCommon/StringUtils.h b/Code/Legacy/CryCommon/StringUtils.h
index ffd1001f95..d6c3d829d2 100644
--- a/Code/Legacy/CryCommon/StringUtils.h
+++ b/Code/Legacy/CryCommon/StringUtils.h
@@ -65,7 +65,7 @@ namespace CryStringUtils_Internal
     template 
     inline bool strcpy_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes)
     {
-        COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t));
+        static_assert(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t));
 
         if (!dst || dst_size_in_bytes < sizeof(TChar))
         {
@@ -97,7 +97,7 @@ namespace CryStringUtils_Internal
     template 
     inline bool strcat_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes)
     {
-        COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t));
+        static_assert(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t));
 
         if (!dst || dst_size_in_bytes < sizeof(TChar))
         {
diff --git a/Code/Legacy/CryCommon/UnicodeBinding.h b/Code/Legacy/CryCommon/UnicodeBinding.h
index e6e82aaf49..7a058650b5 100644
--- a/Code/Legacy/CryCommon/UnicodeBinding.h
+++ b/Code/Legacy/CryCommon/UnicodeBinding.h
@@ -211,7 +211,7 @@ namespace Unicode
                     >::type
                 >::type CharType;
             static const size_t FixedSize = extent::value;
-            COMPILE_TIME_ASSERT(!is_array::value || FixedSize > 0);
+            static_assert(!is_array::value || FixedSize > 0);
             static const bool isConstArray = is_array::value && is_const::type>::value;
             static const bool isBufferArray = is_array::value && !isConstArray;
             static const bool isPointer = is_pointer::value;
@@ -393,7 +393,7 @@ namespace Unicode
                 sizeof(CharType) == 1 ? eEncoding_UTF8 :
                 sizeof(CharType) == 2 ? eEncoding_UTF16 :
                 eEncoding_UTF32;
-            COMPILE_TIME_ASSERT(value != eEncoding_UTF32 || sizeof(CharType) == 4);
+            static_assert(value != eEncoding_UTF32 || sizeof(CharType) == 4);
         };
 
         // SBindCharacter:
@@ -408,7 +408,7 @@ namespace Unicode
         template
         struct SBindCharacter
         {
-            COMPILE_TIME_ASSERT(is_arithmetic::value);
+            static_assert(is_arithmetic::value);
             typedef typename remove_cv::type UnqualifiedType;
             typedef typename conditional::type type;
         };
@@ -417,7 +417,7 @@ namespace Unicode
         {
             typedef typename conditional::type type;
             typedef typename SDependentType::type ActuallyQChar; // Force two-phase name lookup on QChar.
-            COMPILE_TIME_ASSERT(sizeof(ActuallyQChar) == sizeof(type)); // In case Qt ever changes QChar.
+            static_assert(sizeof(ActuallyQChar) == sizeof(type)); // In case Qt ever changes QChar.
         };
 
         // SBindPointer:
@@ -425,7 +425,7 @@ namespace Unicode
         template
         struct SBindPointer
         {
-            COMPILE_TIME_ASSERT(is_pointer::value || is_array::value);
+            static_assert(is_pointer::value || is_array::value);
             typedef typename conditional<
                 is_pointer::value,
                 typename remove_pointer::type,
@@ -458,8 +458,8 @@ namespace Unicode
         {
             // Allow casts from pointer-to-integral to unrelated pointer-to-integral, provided they are of the same size.
             typedef typename remove_pointer::type TargetChar;
-            COMPILE_TIME_ASSERT(is_integral::value && is_integral::value);
-            COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar));
+            static_assert(is_integral::value && is_integral::value);
+            static_assert(sizeof(SourceChar) == sizeof(TargetChar));
             return reinterpret_cast(ptr);
         }
         template
@@ -467,8 +467,8 @@ namespace Unicode
         {
             // Allow casts from pointer-to-QChar to unrelated pointer-to-integral, provided they are of the same size.
             typedef typename remove_pointer::type TargetChar;
-            COMPILE_TIME_ASSERT(is_integral::value);
-            COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar));
+            static_assert(is_integral::value);
+            static_assert(sizeof(SourceChar) == sizeof(TargetChar));
             return reinterpret_cast(ptr);
         }
         template
@@ -612,7 +612,7 @@ namespace Unicode
         template
         inline void Feed(const InputStringType& in, Sink& out, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_array::value && extent::value > 0);
+            static_assert(is_array::value && extent::value > 0);
             typedef typename SBindPointer::type PointerType;
             const size_t length = extent::value - 1;
             PointerType ptr = SafeCast(in);
@@ -630,7 +630,7 @@ namespace Unicode
         template
         inline void Feed(const InputStringType& in, Sink& out, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_array::value && extent::value > 0);
+            static_assert(is_array::value && extent::value > 0);
             typedef typename SBindPointer::type PointerType;
             typedef typename SBindPointer::BoundCharType CharType;
             const size_t length = extent::value;
@@ -652,7 +652,7 @@ namespace Unicode
         template
         inline void Feed(const InputStringType& in, Sink& out, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_pointer::value);
+            static_assert(is_pointer::value);
             typedef typename SBindPointer::type PointerType;
             typedef typename SBindPointer::BoundCharType CharType;
             PointerType ptr = SafeCast(in);
@@ -677,7 +677,7 @@ namespace Unicode
         template
         inline void Feed(const InputCharType& in, Sink& out, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_arithmetic::value);
+            static_assert(is_arithmetic::value);
             const uint32 item = static_cast(in);
             out(item);
         }
@@ -711,7 +711,7 @@ namespace Unicode
         template
         inline size_t EncodedLength(const InputStringType& in, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_array::value && extent::value > 0);
+            static_assert(is_array::value && extent::value > 0);
             return extent::value - 1;
         }
 
@@ -720,7 +720,7 @@ namespace Unicode
         template
         inline size_t EncodedLength(const InputStringType& in, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_array::value && extent::value > 0);
+            static_assert(is_array::value && extent::value > 0);
             typedef typename remove_extent::type CharType;
             return SCharacterTrait::StrNLen(in, extent::value);
         }
@@ -738,7 +738,7 @@ namespace Unicode
         template
         inline size_t EncodedLength(const InputStringType& in, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_pointer::value);
+            static_assert(is_pointer::value);
             typedef typename remove_pointer::type CharType;
             return in ? SCharacterTrait::StrLen(in) : 0;
         }
@@ -748,7 +748,7 @@ namespace Unicode
         template
         inline size_t EncodedLength([[maybe_unused]] const InputCharType& in, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_arithmetic::value);
+            static_assert(is_arithmetic::value);
             return 1;
         }
 
@@ -775,7 +775,7 @@ namespace Unicode
         template
         inline const void* EncodedPointer(const InputStringType& in, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_array::value && extent::value > 0);
+            static_assert(is_array::value && extent::value > 0);
             return in; // We can just let the array type decay to a pointer.
         }
 
@@ -784,7 +784,7 @@ namespace Unicode
         template
         inline const void* EncodedPointer(const InputStringType& in, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_array::value && extent::value > 0);
+            static_assert(is_array::value && extent::value > 0);
             return in; // We can just let the array type decay to a pointer.
         }
 
@@ -793,7 +793,7 @@ namespace Unicode
         template
         inline const void* EncodedPointer(const InputStringType& in, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_pointer::value);
+            static_assert(is_pointer::value);
             return in; // Implied
         }
 
@@ -802,7 +802,7 @@ namespace Unicode
         template
         inline const void* EncodedPointer(const InputCharType& in, integral_constant)
         {
-            COMPILE_TIME_ASSERT(is_arithmetic::value);
+            static_assert(is_arithmetic::value);
             return ∈ // Take the address of the parameter (which is kept on the stack of the caller).
         }
 
diff --git a/Code/Legacy/CryCommon/UnicodeEncoding.h b/Code/Legacy/CryCommon/UnicodeEncoding.h
index a3e20b639c..fb2d398cb6 100644
--- a/Code/Legacy/CryCommon/UnicodeEncoding.h
+++ b/Code/Legacy/CryCommon/UnicodeEncoding.h
@@ -17,7 +17,7 @@
 
 #pragma once
 #include "BaseTypes.h" // For uint8, uint16, uint32
-#include "CompileTimeAssert.h" // For COMPILE_TIME_ASSERT macro
+
 namespace Unicode
 {
     // Supported encoding/conversion types.
@@ -631,7 +631,7 @@ namespace Unicode
         struct SRecoveryFallbackHelper
         {
             // A compilation error here means RecoveryMethod value was unexpected here
-            COMPILE_TIME_ASSERT(
+            static_assert(
                 RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard ||
                 RecoveryMethod == eErrorRecovery_FallbackLatin1ThenReplace ||
                 RecoveryMethod == eErrorRecovery_FallbackWin1252ThenDiscard ||
diff --git a/Code/Legacy/CryCommon/UnicodeFunctions.h b/Code/Legacy/CryCommon/UnicodeFunctions.h
index 48debe9706..31fc7991c3 100644
--- a/Code/Legacy/CryCommon/UnicodeFunctions.h
+++ b/Code/Legacy/CryCommon/UnicodeFunctions.h
@@ -266,7 +266,7 @@ namespace Unicode
         inline size_t LengthSafe(const InputStringType& source)
         {
             // SRequire a safe recovery method.
-            COMPILE_TIME_ASSERT(SIsSafeEncoding::value);
+            static_assert(SIsSafeEncoding::value);
 
             // Bind methods.
             const EBind bindMethod = SBindObject::value;
@@ -379,7 +379,7 @@ namespace Unicode
         inline size_t ConvertSafe(OutputStringType& target, const InputStringType& source)
         {
             // SRequire a safe recovery method.
-            COMPILE_TIME_ASSERT(SIsSafeEncoding::value);
+            static_assert(SIsSafeEncoding::value);
 
             // Bind methods.
             const EBind inputBindMethod = SBindObject::value;
diff --git a/Code/Legacy/CryCommon/UnicodeIterator.h b/Code/Legacy/CryCommon/UnicodeIterator.h
index d939eaa721..c28378ea44 100644
--- a/Code/Legacy/CryCommon/UnicodeIterator.h
+++ b/Code/Legacy/CryCommon/UnicodeIterator.h
@@ -27,7 +27,7 @@ namespace Unicode
         template
         inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, const integral_constant)
         {
-            COMPILE_TIME_ASSERT(
+            static_assert(
                 Encoding == eEncoding_ASCII ||
                 Encoding == eEncoding_UTF32 ||
                 Encoding == eEncoding_Latin1 ||
@@ -88,7 +88,7 @@ namespace Unicode
         template
         inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, const integral_constant)
         {
-            COMPILE_TIME_ASSERT(
+            static_assert(
                 Encoding == eEncoding_ASCII ||
                 Encoding == eEncoding_UTF32 ||
                 Encoding == eEncoding_Latin1 ||
diff --git a/Code/Legacy/CryCommon/Win32specific.h b/Code/Legacy/CryCommon/Win32specific.h
index 0519bb1022..62d32138b4 100644
--- a/Code/Legacy/CryCommon/Win32specific.h
+++ b/Code/Legacy/CryCommon/Win32specific.h
@@ -23,10 +23,7 @@
 #define ILINE __forceinline
 #endif
 
-#define RC_EXECUTABLE "rc.exe"
 #define DEPRECATED __declspec(deprecated)
-#define TYPENAME(x) typeid(x).name()
-#define SIZEOF_PTR 4
 
 #ifndef _WIN32_WINNT
 # define _WIN32_WINNT 0x501
@@ -54,8 +51,6 @@
 //////////////////////////////////////////////////////////////////////////
 #include "BaseTypes.h"
 
-#define THREADID_NULL -1
-
 typedef unsigned char BYTE;
 typedef unsigned int threadID;
 typedef unsigned long DWORD;
@@ -111,14 +106,11 @@ int64 CryGetTicksPerSec();
     __declspec(align(num))
 
 #define DEFINE_ALIGNED_DATA(type, name, alignment) _declspec(align(alignment)) type name;
-#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) static _declspec(align(alignment)) type name;
-#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) const _declspec(align(alignment)) type name;
 
 #ifndef FILE_ATTRIBUTE_NORMAL
     #define FILE_ATTRIBUTE_NORMAL 0x00000080
 #endif
 
-#define FP16_TERRAIN
 #define TARGET_DEFAULT_ALIGN (0x4U)
 
 
diff --git a/Code/Legacy/CryCommon/Win64specific.h b/Code/Legacy/CryCommon/Win64specific.h
index b1e86f9250..47c9c1aad9 100644
--- a/Code/Legacy/CryCommon/Win64specific.h
+++ b/Code/Legacy/CryCommon/Win64specific.h
@@ -19,10 +19,7 @@
 #define _CPU_SSE
 #define ILINE __forceinline
 
-#define RC_EXECUTABLE "rc.exe"
 #define DEPRECATED __declspec(deprecated)
-#define TYPENAME(x) typeid(x).name()
-#define SIZEOF_PTR 8
 
 #ifndef _WIN32_WINNT
 # define _WIN32_WINNT 0x501
@@ -51,7 +48,6 @@
 //////////////////////////////////////////////////////////////////////////
 #include "BaseTypes.h"
 
-#define THREADID_NULL -1
 typedef long LONG;
 typedef unsigned char BYTE;
 typedef unsigned long threadID;
@@ -93,10 +89,6 @@ int64 CryGetTicksPerSec();
     __declspec(align(num))
 
 #define DEFINE_ALIGNED_DATA(type, name, alignment) _declspec(align(alignment)) type name;
-#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) static _declspec(align(alignment)) type name;
-#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) const _declspec(align(alignment)) type name;
-
-#define SIZEOF_PTR 8
 
 #ifndef FILE_ATTRIBUTE_NORMAL
     #define FILE_ATTRIBUTE_NORMAL 0x00000080
diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake
index 0392f11c89..18cbd16f4b 100644
--- a/Code/Legacy/CryCommon/crycommon_files.cmake
+++ b/Code/Legacy/CryCommon/crycommon_files.cmake
@@ -68,7 +68,6 @@ set(FILES
     LCGRandom.h
     CryTypeInfo.cpp
     BaseTypes.h
-    CompileTimeAssert.h
     MemoryAccess.h
     AnimKey.h
     BitFiddling.h
@@ -165,7 +164,6 @@ set(FILES
     CryThread_windows.h
     CryThreadImpl_pthreads.h
     CryThreadImpl_windows.h
-    CryWindows.h
     Linux32Specific.h
     Linux64Specific.h
     Linux_Win32Wrapper.h
diff --git a/Code/Legacy/CryCommon/iOSSpecific.h b/Code/Legacy/CryCommon/iOSSpecific.h
index d2503a7441..ac2461b55b 100644
--- a/Code/Legacy/CryCommon/iOSSpecific.h
+++ b/Code/Legacy/CryCommon/iOSSpecific.h
@@ -47,11 +47,9 @@
 #define VK_SCROLL       0
 
 
-//#define USE_CRT 1
 #if !defined(PLATFORM_64BIT)
 #error "IOS build only supports the 64bit architecture"
 #else
-#define SIZEOF_PTR 8
 typedef uint64_t threadID;
 #endif
 
diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h
index fb96056beb..9ff461543f 100644
--- a/Code/Legacy/CryCommon/platform.h
+++ b/Code/Legacy/CryCommon/platform.h
@@ -263,7 +263,6 @@ ILINE DestinationType alias_cast(SourceType pPtr)
 #define assert CRY_ASSERT
 #endif
 
-#include "CompileTimeAssert.h"
 //////////////////////////////////////////////////////////////////////////
 // Platform dependent functions that emulate Win32 API.
 // Mostly used only for debugging!
diff --git a/Code/Legacy/CryCommon/stridedptr.h b/Code/Legacy/CryCommon/stridedptr.h
index 737a1e40b7..8a74aa97b1 100644
--- a/Code/Legacy/CryCommon/stridedptr.h
+++ b/Code/Legacy/CryCommon/stridedptr.h
@@ -66,9 +66,9 @@ private:
 #       if !defined(eLittleEndian)
 #           error eLittleEndian is not defined, please include CryEndian.h.
 #       endif
-        COMPILE_TIME_ASSERT(metautils::is_const::value || !metautils::is_const::value);
+        static_assert(metautils::is_const::value || !metautils::is_const::value);
         // note: we allow xint32 -> xint16 converting
-        COMPILE_TIME_ASSERT(
+        static_assert(
             (metautils::is_same::type, typename metautils::remove_const::type>::value ||
              ((metautils::is_same::type, sint32>::value ||
                metautils::is_same::type, uint32>::value ||
diff --git a/Code/Legacy/CrySystem/CrySystem_precompiled.h b/Code/Legacy/CrySystem/CrySystem_precompiled.h
index f59adccb7b..daf1c335e4 100644
--- a/Code/Legacy/CrySystem/CrySystem_precompiled.h
+++ b/Code/Legacy/CrySystem/CrySystem_precompiled.h
@@ -68,7 +68,7 @@
 #endif
 
 #ifdef WIN32
-#include 
+#include 
 #include 
 #undef GetCharWidth
 #undef GetUserName
diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
index ffaf0e7210..b1fd9de7c0 100644
--- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
+++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp
@@ -33,10 +33,6 @@
 
 #include 
 
-#ifdef WIN32
-#include 
-#endif
-
 namespace LegacyLevelSystem
 {
 static constexpr const char* ArchiveExtension = ".pak";
diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp
index bd31fb3ba4..be44c4b212 100644
--- a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp
+++ b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp
@@ -194,7 +194,7 @@ void XMLBinary::XMLBinaryReader::CheckHeader(const BinaryFileHeader& header, siz
     // Check the signature of the file to make sure that it is a binary XML file.
     {
         static const char signature[] = "CryXmlB";
-        COMPILE_TIME_ASSERT(sizeof(signature) == sizeof(header.szSignature));
+        static_assert(sizeof(signature) == sizeof(header.szSignature));
         if (memcmp(header.szSignature, signature, sizeof(header.szSignature)) != 0)
         {
             result = eResult_NotBinXml;
diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp
index 1500717ddc..9490e9aae0 100644
--- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp
+++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp
@@ -109,7 +109,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node,
 
     BinaryFileHeader header;
     static const char signature[] = "CryXmlB";
-    COMPILE_TIME_ASSERT(sizeof(signature) == sizeof(header.szSignature));
+    static_assert(sizeof(signature) == sizeof(header.szSignature));
     memcpy(header.szSignature, signature, sizeof(header.szSignature));
     nTheoreticalPosition += sizeof(header);
     align(nTheoreticalPosition, nAlignment);

From 2f5927f1ac43c3f082cd3b3e69084d9d2c14554e Mon Sep 17 00:00:00 2001
From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
Date: Fri, 6 Aug 2021 17:45:54 -0700
Subject: [PATCH 074/205] [redcode/crythread-2nd-pass] remove dependency on cry
 threads in the remote console runtime

Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
---
 .../RemoteConsole/Core/RemoteConsoleCore.cpp  | 88 +++++++++++--------
 .../RemoteConsole/Core/RemoteConsoleCore.h    | 42 ++++++---
 2 files changed, 84 insertions(+), 46 deletions(-)

diff --git a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp
index d4ef5b3ba8..94ae4cbfbf 100644
--- a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp
+++ b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp
@@ -93,40 +93,63 @@ bool RCON_IsRemoteAllowedToConnect(const AZ::AzSock::AzSocketAddress& connectee)
 /////////////////////////////////////////////////////////////////////////////////////////////
 /////////////////////////////////////////////////////////////////////////////////////////////
 /////////////////////////////////////////////////////////////////////////////////////////////
+void SRemoteThreadedObject::Start(const char* name)
+{
+    AZStd::thread_desc desc;
+    desc.m_name = name;
 
+    auto function = AZStd::bind(&SRemoteThreadedObject::ThreadFunction, this);
+    m_thread = AZStd::thread(function, &desc);
+}
+
+void SRemoteThreadedObject::WaitForThread()
+{
+    if (m_thread.joinable())
+    {
+        m_thread.join();
+    }
+}
+
+void SRemoteThreadedObject::ThreadFunction()
+{
+    Run();
+    Terminate();
+}
+
+/////////////////////////////////////////////////////////////////////////////////////////////
+/////////////////////////////////////////////////////////////////////////////////////////////
+/////////////////////////////////////////////////////////////////////////////////////////////
 void SRemoteServer::StartServer()
 {
     StopServer();
     m_bAcceptClients = true;
-    Start(0, kServerThreadName);
+    Start(kServerThreadName);
 }
 
 /////////////////////////////////////////////////////////////////////////////////////////////
 void SRemoteServer::StopServer()
 {
-    Stop();
     m_bAcceptClients = false;
     AZ::AzSock::CloseSocket(m_socket);
     m_socket = SOCKET_ERROR;
-    m_lock.Lock();
-    for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it)
     {
-        it->pClient->StopClient();
+        AZStd::lock_guard lock(m_mutex);
+        for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it)
+        {
+            it->pClient->StopClient();
+        }
     }
-    m_lock.Unlock();
-    m_stopEvent.Wait();
-    m_stopEvent.Set();
-}
+    AZStd::unique_lock lock(m_mutex);
+    m_stopCondition.wait(lock, [this] { return m_clients.empty(); });}
 
 /////////////////////////////////////////////////////////////////////////////////////////////
 void SRemoteServer::ClientDone(SRemoteClient* pClient)
 {
-    m_lock.Lock();
+    AZStd::lock_guard lock(m_mutex);
     for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it)
     {
         if (it->pClient == pClient)
         {
-            it->pClient->Stop();
             delete it->pClient;
             delete it->pEvents;
             m_clients.erase(it);
@@ -136,9 +159,8 @@ void SRemoteServer::ClientDone(SRemoteClient* pClient)
 
     if (m_clients.empty())
     {
-        m_stopEvent.Set();
+        m_stopCondition.notify_all();
     }
-    m_lock.Unlock();
 }
 
 /////////////////////////////////////////////////////////////////////////////////////////////
@@ -149,7 +171,6 @@ void SRemoteServer::Terminate()
 /////////////////////////////////////////////////////////////////////////////////////////////
 void SRemoteServer::Run()
 {
-    SetName(kServerThreadName);
     AZ_TRAIT_REMOTECONSOLE_SET_THREAD_AFFINITY
 
     AZSOCKET sClient;
@@ -232,12 +253,10 @@ void SRemoteServer::Run()
             continue;
         }
 
-        m_lock.Lock();
-        m_stopEvent.Reset();
+        AZStd::lock_guard lock(m_mutex);
         SRemoteClient* pClient = new SRemoteClient(this);
         m_clients.push_back(SRemoteClientInfo(pClient));
         pClient->StartClient(sClient);
-        m_lock.Unlock();
     }
     AZ::AzSock::CloseSocket(m_socket);
     CryLog("Remote console terminating.\n");
@@ -247,43 +266,42 @@ void SRemoteServer::Run()
 /////////////////////////////////////////////////////////////////////////////////////////////
 void SRemoteServer::AddEvent(IRemoteEvent* pEvent)
 {
-    m_lock.Lock();
+    AZStd::lock_guard lock(m_mutex);
     for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it)
     {
         it->pEvents->push_back(pEvent->Clone());
     }
-    m_lock.Unlock();
     delete pEvent;
 }
 
 /////////////////////////////////////////////////////////////////////////////////////////////
 void SRemoteServer::GetEvents(TEventBuffer& buffer)
 {
-    m_lock.Lock();
+    AZStd::lock_guard lock(m_mutex);
     buffer = m_eventBuffer;
     m_eventBuffer.clear();
-    m_lock.Unlock();
 }
 
 /////////////////////////////////////////////////////////////////////////////////////////////
 bool SRemoteServer::WriteBuffer(SRemoteClient* pClient,  char* buffer, int& size)
 {
-    m_lock.Lock();
     IRemoteEvent* pEvent = nullptr;
-    for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it)
     {
-        if (it->pClient == pClient)
+        AZStd::lock_guard lock(m_mutex);
+        for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it)
         {
-            TEventBuffer* pEvents = it->pEvents;
-            if (!pEvents->empty())
+            if (it->pClient == pClient)
             {
-                pEvent = pEvents->front();
-                pEvents->pop_front();
+                TEventBuffer* pEvents = it->pEvents;
+                if (!pEvents->empty())
+                {
+                    pEvent = pEvents->front();
+                    pEvents->pop_front();
+                }
+                break;
             }
-            break;
         }
     }
-    m_lock.Unlock();
     const bool res = (pEvent != nullptr);
     if (pEvent)
     {
@@ -297,7 +315,7 @@ bool SRemoteServer::WriteBuffer(SRemoteClient* pClient,  char* buffer, int& size
 bool SRemoteServer::ReadBuffer(const char* buffer, int data)
 {
     bool result = true;
-    
+
     // Sometimes multiple events can come in a single buffer, so make sure we look
     // at the entire thing.
     int bytesRemaining = data;
@@ -306,15 +324,14 @@ bool SRemoteServer::ReadBuffer(const char* buffer, int data)
     {
         // Create the event from the current sub string in the buffer.
         IRemoteEvent* event = SRemoteEventFactory::GetInst()->CreateEventFromBuffer(curBuffer, bytesRemaining);
-        
+
         result &= (event != nullptr);
         if (event)
         {
             if (event->GetType() != eCET_Noop)
             {
-                m_lock.Lock();
+                AZStd::lock_guard lock(m_mutex);
                 m_eventBuffer.push_back(event);
-                m_lock.Unlock();
             }
             else
             {
@@ -337,7 +354,7 @@ bool SRemoteServer::ReadBuffer(const char* buffer, int data)
 void SRemoteClient::StartClient(AZSOCKET socket)
 {
     m_socket = socket;
-    Start(0, kClientThreadName);
+    Start(kClientThreadName);
 }
 
 /////////////////////////////////////////////////////////////////////////////////////////////
@@ -356,7 +373,6 @@ void SRemoteClient::Terminate()
 /////////////////////////////////////////////////////////////////////////////////////////////
 void SRemoteClient::Run()
 {
-    SetName(kClientThreadName);
     AZ_TRAIT_REMOTECONSOLE_SET_THREAD_AFFINITY
 
     char szBuff[kDefaultBufferSize];
diff --git a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.h b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.h
index 45c3bf62d9..7e22be5735 100644
--- a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.h
+++ b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.h
@@ -11,9 +11,11 @@
 #include 
 #include 
 #include 
+#include 
+#include 
+#include 
 #include 
 
-#include 
 
 extern const int defaultRemoteConsolePort;
 
@@ -146,6 +148,30 @@ private:
 
 typedef AZStd::list TEventBuffer;
 
+
+/////////////////////////////////////////////////////////////////////////////////////////////
+// SRemoteThreadedObject
+//
+// Simple runnable-like threaded object
+//
+/////////////////////////////////////////////////////////////////////////////////////////////
+struct SRemoteThreadedObject
+{
+    virtual ~SRemoteThreadedObject() = default;
+
+    void Start(const char* name);
+
+    void WaitForThread();
+
+    virtual void Run() = 0;
+    virtual void Terminate() = 0;
+
+private:
+    void ThreadFunction();
+
+    AZStd::thread m_thread;
+};
+
 /////////////////////////////////////////////////////////////////////////////////////////////
 // SRemoteServer
 //
@@ -154,10 +180,10 @@ typedef AZStd::list TEventBuffer;
 /////////////////////////////////////////////////////////////////////////////////////////////
 struct SRemoteClient;
 struct SRemoteServer
-    : public CrySimpleThread<>
+    : public SRemoteThreadedObject
 {
     SRemoteServer()
-        : m_socket(AZ_SOCKET_INVALID) { m_stopEvent.Set(); }
+        : m_socket(AZ_SOCKET_INVALID) {}
 
     void StartServer();
     void StopServer();
@@ -165,10 +191,8 @@ struct SRemoteServer
     void AddEvent(IRemoteEvent* pEvent);
     void GetEvents(TEventBuffer& buffer);
 
-    // CrySimpleThread
     void Terminate() override;
     void Run() override;
-    // ~CrySimpleThread
 
 private:
     bool WriteBuffer(SRemoteClient* pClient,  char* buffer, int& size);
@@ -189,9 +213,9 @@ private:
     typedef AZStd::vector TClients;
     TClients m_clients;
     AZSOCKET m_socket;
-    CryMutex m_lock;
+    AZStd::recursive_mutex m_mutex;
     TEventBuffer m_eventBuffer;
-    CryEvent m_stopEvent;
+    AZStd::condition_variable_any m_stopCondition;
     volatile bool m_bAcceptClients;
     friend struct SRemoteClient;
 };
@@ -204,7 +228,7 @@ private:
 //
 /////////////////////////////////////////////////////////////////////////////////////////////
 struct SRemoteClient
-    : public CrySimpleThread<>
+    : public SRemoteThreadedObject
 {
     SRemoteClient(SRemoteServer* pServer)
         : m_pServer(pServer)
@@ -213,10 +237,8 @@ struct SRemoteClient
     void StartClient(AZSOCKET socket);
     void StopClient();
 
-    // CrySimpleThread
     void Terminate() override;
     void Run() override;
-    // ~CrySimpleThread
 
 private:
     bool RecvPackage(char* buffer, int& size);

From 3e7d7d150e72015fb57b3c4f2ef15bf5b95a45aa Mon Sep 17 00:00:00 2001
From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
Date: Fri, 6 Aug 2021 18:22:28 -0700
Subject: [PATCH 075/205] [redcode/crythread-2nd-pass] removed
 CryThread_dummy.h

Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
---
 Code/Legacy/CryCommon/CryThread.h           |   1 -
 Code/Legacy/CryCommon/CryThread_dummy.h     | 152 --------------------
 Code/Legacy/CryCommon/crycommon_files.cmake |   1 -
 3 files changed, 154 deletions(-)
 delete mode 100644 Code/Legacy/CryCommon/CryThread_dummy.h

diff --git a/Code/Legacy/CryCommon/CryThread.h b/Code/Legacy/CryCommon/CryThread.h
index 5929bed352..b7b6a3adfd 100644
--- a/Code/Legacy/CryCommon/CryThread.h
+++ b/Code/Legacy/CryCommon/CryThread.h
@@ -175,7 +175,6 @@ class CrySimpleThread;
 #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
 #else
 // Put other platform specific includes here!
-#include 
 #endif
 
 #if !defined _CRYTHREAD_CONDLOCK_GLITCH
diff --git a/Code/Legacy/CryCommon/CryThread_dummy.h b/Code/Legacy/CryCommon/CryThread_dummy.h
deleted file mode 100644
index d97b6c5b55..0000000000
--- a/Code/Legacy/CryCommon/CryThread_dummy.h
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#ifndef CRYINCLUDE_CRYCOMMON_CRYTHREAD_DUMMY_H
-#define CRYINCLUDE_CRYCOMMON_CRYTHREAD_DUMMY_H
-#pragma once
-
-#include 
-
-//////////////////////////////////////////////////////////////////////////
-CryEvent::CryEvent() {}
-CryEvent::~CryEvent() {}
-void CryEvent::Reset() {}
-void CryEvent::Set() {}
-void CryEvent::Wait() const {}
-bool CryEvent::Wait(const uint32 timeoutMillis) const {}
-typedef CryEvent CryEventTimed;
-
-//////////////////////////////////////////////////////////////////////////
-class _DummyLock
-{
-public:
-    _DummyLock();
-
-    void Lock();
-    bool TryLock();
-    void Unlock();
-
-#if defined(AZ_DEBUG_BUILD)
-    bool IsLocked();
-#endif
-};
-
-template<>
-class CryLock
-    : public _DummyLock
-{
-    CryLock(const CryLock&);
-    void operator = (const CryLock&);
-
-public:
-    CryLock();
-};
-
-template<>
-class CryLock
-    : public _DummyLock
-{
-    CryLock(const CryLock&);
-    void operator = (const CryLock&);
-
-public:
-    CryLock();
-};
-
-template<>
-class CryCondLock
-    : public CryLock
-{
-};
-
-template<>
-class CryCondLock
-    : public CryLock
-{
-};
-
-template<>
-class CryCond< CryLock >
-{
-    typedef CryLock LockT;
-    CryCond(const CryCond&);
-    void operator = (const CryCond&);
-
-public:
-    CryCond();
-
-    void Notify();
-    void NotifySingle();
-    void Wait(LockT&);
-    bool TimedWait(LockT &, uint32);
-};
-
-template<>
-class CryCond< CryLock >
-{
-    typedef CryLock LockT;
-    CryCond(const CryCond&);
-    void operator = (const CryCond&);
-
-public:
-    CryCond();
-
-    void Notify();
-    void NotifySingle();
-    void Wait(LockT&);
-    bool TimedWait(LockT &, uint32);
-};
-
-class _DummyRWLock
-{
-public:
-    _DummyRWLock() { }
-
-    void RLock();
-    bool TryRLock();
-    void WLock();
-    bool TryWLock();
-    void Lock() { WLock(); }
-    bool TryLock() { return TryWLock(); }
-    void Unlock();
-};
-
-template
-class CrySimpleThread
-    : public CryRunnable
-{
-public:
-    typedef void (* ThreadFunction)(void*);
-
-    CrySimpleThread();
-    virtual ~CrySimpleThread();
-#if !defined(NO_THREADINFO)
-    CryThreadInfo& GetInfo();
-#endif
-    const char* GetName();
-    void SetName(const char*);
-
-    virtual void Run();
-    virtual void Cancel();
-    virtual void Start(Runnable&, unsigned = 0, const char* = NULL);
-    virtual void Start(unsigned = 0, const char* = NULL);
-    void StartFunction(ThreadFunction, void* = NULL, unsigned = 0);
-
-    void Exit();
-    void Join();
-    unsigned SetCpuMask(unsigned);
-    unsigned GetCpuMask();
-
-    void Stop();
-    bool IsStarted() const;
-    bool IsRunning() const;
-};
-
-#endif // CRYINCLUDE_CRYCOMMON_CRYTHREAD_DUMMY_H
-
diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake
index 0392f11c89..b4dac2ec08 100644
--- a/Code/Legacy/CryCommon/crycommon_files.cmake
+++ b/Code/Legacy/CryCommon/crycommon_files.cmake
@@ -160,7 +160,6 @@ set(FILES
     CryAssert_Mac.h
     CryLibrary.cpp
     CryLibrary.h
-    CryThread_dummy.h
     CryThread_pthreads.h
     CryThread_windows.h
     CryThreadImpl_pthreads.h

From 64cff38f8294338371555ef737008be3879f2a28 Mon Sep 17 00:00:00 2001
From: antonmic <56370189+antonmic@users.noreply.github.com>
Date: Sun, 8 Aug 2021 16:46:42 -0700
Subject: [PATCH 076/205] Addressing PR feedback and fixed a small issue with
 the draw item count display

Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com>
---
 .../Code/Include/Atom/RHI/ShaderResourceGroupDebug.h | 12 +++++++++++-
 .../RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp  |  6 +++---
 Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp      | 12 ++++++------
 .../RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp |  6 +++---
 .../RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp   |  4 +++-
 5 files changed, 26 insertions(+), 14 deletions(-)

diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h
index b81f9e0c0b..d9ea77d823 100644
--- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h
+++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ShaderResourceGroupDebug.h
@@ -14,8 +14,18 @@ namespace AZ
         struct DrawItem;
         class ShaderResourceGroup;
 
+        /// Given a ShaderResourceGroup and a reference ConstantsData input, this function will fetch the ConstantsData on the SRG and compare it
+        /// to the reference ConstantsData. It will print the names of any constants that are different between the two.
+        /// The parameter updateReferenceData can be used to set the reference data to the SRG's constant data after the comparison. This is
+        /// useful for keeping track of differences in between calls to the function, such as between frames.
         void PrintConstantDataDiff(const ShaderResourceGroup& shaderResourceGroup, ConstantsData& referenceData, bool updateReferenceData = false);
-        void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, u32 srgBindingSlot, bool updateReferenceData = false);
+
+        /// Given a DrawItem, an SRG binding slot on that draw item and a reference ConstantsData input, this function will fetch the ConstantsData
+        /// from the draw item's SRG at the binding slot and compare it to the reference ConstantsData. It will print the names of any constants
+        /// that are different between the two.
+        /// The parameter updateReferenceData can be used to set the reference data to the draw item's constant data after the comparison. This is
+        /// useful for keeping track of differences in between calls to the function, such as between frames.
+        void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, uint32_t srgBindingSlot, bool updateReferenceData = false);
 
     }
 }
diff --git a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp
index f14d1d4c4e..8be053e4ef 100644
--- a/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp
+++ b/Gems/Atom/RHI/Code/Source/RHI.Reflect/ConstantsLayout.cpp
@@ -151,11 +151,11 @@ namespace AZ
         void ConstantsLayout::DebugPrintNames(AZStd::array_view constantList) const
         {
             AZStd::string output;
-            for (const ShaderInputConstantIndex& constandIdx : constantList)
+            for (const ShaderInputConstantIndex& constantIdx : constantList)
             {
-                if (constandIdx.GetIndex() < m_inputs.size())
+                if (constantIdx.GetIndex() < m_inputs.size())
                 {
-                    output += m_inputs[constandIdx.GetIndex()].m_name.GetCStr();
+                    output += m_inputs[constantIdx.GetIndex()].m_name.GetCStr();
                     output += " - ";
                 }
             }
diff --git a/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp b/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp
index d4caa3dd66..1524883e54 100644
--- a/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp
+++ b/Gems/Atom/RHI/Code/Source/RHI/ConstantsData.cpp
@@ -408,26 +408,26 @@ namespace AZ
 
         bool ConstantsData::ConstantIsEqual(const ConstantsData& other, ShaderInputConstantIndex inputIndex) const
         {
-            AZStd::array_view myConstans = GetConstantRaw(inputIndex);
-            AZStd::array_view otherConstans = other.GetConstantRaw(inputIndex);
+            AZStd::array_view myConstant = GetConstantRaw(inputIndex);
+            AZStd::array_view otherConstant = other.GetConstantRaw(inputIndex);
 
             // If they point to the same data, they are equal
-            if (myConstans == otherConstans)
+            if (myConstant == otherConstant)
             {
                 return true;
             }
 
             // If they point to data of different size, they are not equal
-            if (myConstans.size() != otherConstans.size())
+            if (myConstant.size() != otherConstant.size())
             {
                 return false;
             }
 
             // If they point to differing data of same size, compare the data
             // Note: due to small size of data this loop will be faster than a mem compare
-            for(uint32_t i = 0; i < myConstans.size(); ++i)
+            for(uint32_t i = 0; i < myConstant.size(); ++i)
             {
-                if (myConstans[i] != otherConstans[i])
+                if (myConstant[i] != otherConstant[i])
                 {
                     return false;
                 }
diff --git a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp
index 4bd8d0aab8..54399eba88 100644
--- a/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp
+++ b/Gems/Atom/RHI/Code/Source/RHI/ShaderResourceGroupDebug.cpp
@@ -36,10 +36,10 @@ namespace AZ
             }
         }
 
-        void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, u32 srgBindingSlot, bool updateReferenceData)
+        void PrintConstantDataDiff(const DrawItem& drawItem, ConstantsData& referenceData, uint32_t srgBindingSlot, bool updateReferenceData)
         {
-            s32 srgIndex = -1;
-            for (u32 i = 0; i < drawItem.m_shaderResourceGroupCount; ++i)
+            int srgIndex = -1;
+            for (uint32_t i = 0; i < drawItem.m_shaderResourceGroupCount; ++i)
             {
                 if (drawItem.m_shaderResourceGroups[i]->GetBindingSlot() == srgBindingSlot)
                 {
diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp
index 13f2215c8b..2e61542c36 100644
--- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp
+++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp
@@ -166,11 +166,14 @@ namespace AZ
             // clean up data
             m_drawListView = {};
             m_combinedDrawList.clear();
+            m_drawItemCount = 0;
 
             // draw list from view was sorted and if it's the only draw list then we can use it directly
             if (viewDrawList.size() > 0 && drawLists.size() == 0)
             {
                 m_drawListView = viewDrawList;
+                m_drawItemCount += viewDrawList.size();
+                PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount);
                 return;
             }
 
@@ -178,7 +181,6 @@ namespace AZ
             drawLists.push_back(viewDrawList);
 
             // combine draw items from mutiple draw lists to one draw list and sort it.
-            m_drawItemCount = 0;
             for (auto drawList : drawLists)
             {
                 m_drawItemCount += drawList.size();

From 4beb66c9caee9e9f1c3bce290c3ccc851ebe75d4 Mon Sep 17 00:00:00 2001
From: antonmic <56370189+antonmic@users.noreply.github.com>
Date: Sun, 8 Aug 2021 23:37:54 -0700
Subject: [PATCH 077/205] Making pass files declare dependency on shader files
 (part 01)

Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com>
---
 .../Code/Source/Editor/ShaderAssetBuilder.cpp |   3 +-
 .../Editor/ShaderVariantAssetBuilder.cpp      |   2 +-
 .../Source/RPI.Builders/Pass/PassBuilder.cpp  | 197 ++++++++++++++----
 .../Source/RPI.Builders/Pass/PassBuilder.h    |   1 -
 4 files changed, 159 insertions(+), 44 deletions(-)

diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp
index b1a3de2794..606502fb22 100644
--- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp
+++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp
@@ -139,8 +139,7 @@ namespace AZ
 
                 AssetBuilderSDK::JobDescriptor jobDescriptor;
                 jobDescriptor.m_priority = 2;
-                // [GFX TODO][ATOM-2830] Set 'm_critical' back to 'false' once proper fix for Atom startup issues are in 
-                jobDescriptor.m_critical = true;
+                jobDescriptor.m_critical = false;
                 jobDescriptor.m_jobKey = ShaderAssetBuilderJobKey;
                 jobDescriptor.SetPlatformIdentifier(platformInfo.m_identifier.c_str());
                 jobDescriptor.m_jobParameters.emplace(ShaderAssetBuildTimestampParam, AZStd::to_string(shaderAssetBuildTimestamp));
diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp
index 1da4623774..ee02ae8452 100644
--- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp
+++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp
@@ -321,7 +321,7 @@ namespace AZ
                     AssetBuilderSDK::JobDescriptor jobDescriptor;
 
                     jobDescriptor.m_priority = -5000;
-                    jobDescriptor.m_critical = false;
+                    jobDescriptor.m_critical = true;
                     jobDescriptor.m_jobKey = ShaderVariantAssetBuilderJobKey;
                     jobDescriptor.SetPlatformIdentifier(info.m_identifier.data());
                     
diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp
index 652130dea2..f582f3ba04 100644
--- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp
+++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp
@@ -37,7 +37,7 @@ namespace AZ
         {
             AssetBuilderSDK::AssetBuilderDesc builder;
             builder.m_name = PassBuilderJobKey;
-            builder.m_version = 12; // ATOM-15472
+            builder.m_version = 13; // antonmic: making .pass files declare dependency on shaders they reference
             builder.m_busId = azrtti_typeid();
             builder.m_createJobFunction = AZStd::bind(&PassBuilder::CreateJobs, this, AZStd::placeholders::_1, AZStd::placeholders::_2);
             builder.m_processJobFunction = AZStd::bind(&PassBuilder::ProcessJob, this, AZStd::placeholders::_1, AZStd::placeholders::_2);
@@ -65,35 +65,66 @@ namespace AZ
             m_isShuttingDown = true;
         }
 
-        void PassBuilder::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) const
+        // --- Code related to dependency shader asset handling ---
+
+        struct FindPassReferenceAssetParams
         {
-            if (m_isShuttingDown)
+            void* passAssetObject;
+            Uuid passAssetUuid;
+            SerializeContext* serializeContext;
+            AZStd::string_view passAssetSourceFile;     // File path of the pass asset
+            AZStd::string_view dependencySourceFile;    // File pass of the asset the pass asset depends on
+            const char* jobKey;                         // Job key for adding job dependency
+        };
+
+        //! Adds all relevant dependencies for a referenced source file, considering that the path might be relative to the original file location or a full asset path.
+        //! This will usually include multiple source dependencies and a single job dependency, but will include only source dependencies if the file is not found.
+        //! Note the AssetBuilderSDK::JobDependency::m_platformIdentifier will not be set by this function. The calling code must set this value before passing back
+        //! to the AssetBuilderSDK::CreateJobsResponse.
+        void AddPossibleDependencies(
+            FindPassReferenceAssetParams& params,
+            AssetBuilderSDK::CreateJobsResponse& response,
+            AssetBuilderSDK::JobDescriptor& job)
+        {
+            bool dependencyFileFound = false;
+
+            AZStd::vector possibleDependencies = RPI::AssetUtils::GetPossibleDepenencyPaths(params.passAssetSourceFile, params.dependencySourceFile);
+            for (auto& file : possibleDependencies)
             {
-                response.m_result = AssetBuilderSDK::CreateJobsResultCode::ShuttingDown;
-                return;
+                AssetBuilderSDK::SourceFileDependency sourceFileDependency;
+                sourceFileDependency.m_sourceFileDependencyPath = file;
+                response.m_sourceFileDependencyList.push_back(sourceFileDependency);
+
+                // The first path found is the highest priority, and will have a job dependency, as this is the one
+                // the builder will actually use
+                if (!dependencyFileFound)
+                {
+                    AZ::Data::AssetInfo sourceInfo;
+                    AZStd::string watchFolder;
+                    AzToolsFramework::AssetSystemRequestBus::BroadcastResult(dependencyFileFound, &AzToolsFramework::AssetSystem::AssetSystemRequest::GetSourceInfoBySourcePath, file.c_str(), sourceInfo, watchFolder);
+
+                    if (dependencyFileFound)
+                    {
+                        AssetBuilderSDK::JobDependency jobDependency;
+                        jobDependency.m_jobKey = params.jobKey;
+                        jobDependency.m_type = AssetBuilderSDK::JobDependencyType::Order;
+                        jobDependency.m_sourceFile.m_sourceFileDependencyPath = file;
+                        job.m_jobDependencyList.push_back(jobDependency);
+                    }
+                }
             }
-
-            for (const AssetBuilderSDK::PlatformInfo& platformInfo : request.m_enabledPlatforms)
-            {
-                AssetBuilderSDK::JobDescriptor job;
-                job.m_jobKey = PassBuilderJobKey;
-                job.SetPlatformIdentifier(platformInfo.m_identifier.c_str());
-
-                // Passes are a critical part of the rendering system
-                job.m_critical = true;
-
-                response.m_createJobOutputs.push_back(job);
-            }
-
-            response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success;
         }
 
         // Helper function to find all assetId's and object references
-        bool PassBuilder::FindPassReferencedAssets(void* objectPtr, Uuid passAssetUuid, SerializeContext* context, AZStd::unordered_set &referencedAssetList) const
+        bool FindPassReferencedAssets(FindPassReferenceAssetParams& params,
+                                      AZStd::unordered_set& referencedAssetList,
+                                      AssetBuilderSDK::CreateJobsResponse& response,
+                                      AssetBuilderSDK::JobDescriptor& job,
+                                      bool jobCreationPhase)
         {
             SerializeContext::ErrorHandler errorLogger;
             errorLogger.Reset();
-            
+
             bool foundProblems = false;
 
             // This callback will check whether the given element is an asset reference. If so, it will add it to the list of asset references
@@ -103,26 +134,34 @@ namespace AZ
                 if (classData->m_typeId == azrtti_typeid())
                 {
                     AssetReference* assetReference = reinterpret_cast(ptr);
-                
+
                     // If the asset id isn't already provided, get it using the source file path
                     if (!assetReference->m_assetId.IsValid() && !assetReference->m_filePath.empty())
                     {
-                        AZStd::string path = assetReference->m_filePath;
+                        const AZStd::string& path = assetReference->m_filePath;
                         uint32_t subId = 0;
 
-                        auto assetIdOutcome = AssetUtils::MakeAssetId(path, subId);
-
-                        if (assetIdOutcome)
+                        if (jobCreationPhase)
                         {
-                            assetReference->m_assetId = assetIdOutcome.GetValue();
+                            params.dependencySourceFile = path;
+                            AddPossibleDependencies(params, response, job);
                         }
-                        else
+                        else // Process Job Phase
                         {
-                            AZ_Error(PassBuilderName, false, "Could not get AssetId for [%s]", assetReference->m_filePath.c_str());
-                            foundProblems = true;
+                            auto assetIdOutcome = AssetUtils::MakeAssetId(path, subId);
+
+                            if (assetIdOutcome)
+                            {
+                                assetReference->m_assetId = assetIdOutcome.GetValue();
+                            }
+                            else
+                            {
+                                AZ_Error(PassBuilderName, false, "Could not get AssetId for [%s]", assetReference->m_filePath.c_str());
+                                foundProblems = true;
+                            }
                         }
                     }
-                
+
                     // If the asset ID is valid, add it as a dependency
                     if (assetReference->m_assetId.IsValid())
                     {
@@ -136,16 +175,16 @@ namespace AZ
             SerializeContext::EnumerateInstanceCallContext callContext(
                 AZStd::move(beginCallback),
                 nullptr,
-                context,
+                params.serializeContext,
                 SerializeContext::ENUM_ACCESS_FOR_READ,
                 &errorLogger
             );
 
             // Recursively iterate over all elements in the object to find asset references with the above callback
-            context->EnumerateInstance(
+            params.serializeContext->EnumerateInstance(
                 &callContext
-                , objectPtr
-                , passAssetUuid
+                , params.passAssetObject
+                , params.passAssetUuid
                 , nullptr
                 , nullptr
             );
@@ -153,6 +192,73 @@ namespace AZ
             return !foundProblems;
         }
 
+        // --- Code related to dependency shader asset handling ---
+
+        void PassBuilder::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) const
+        {
+            if (m_isShuttingDown)
+            {
+                response.m_result = AssetBuilderSDK::CreateJobsResultCode::ShuttingDown;
+                return;
+            }
+
+            AssetBuilderSDK::JobDescriptor job;
+
+            // Get serialization context
+            SerializeContext* serializeContext = nullptr;
+            ComponentApplicationBus::BroadcastResult(serializeContext, &ComponentApplicationBus::Events::GetSerializeContext);
+            if (!serializeContext)
+            {
+                AZ_Assert(false, "No serialize context");
+                return;
+            }
+
+            // Load PassAsset
+            AZStd::string fullPath;
+            AzFramework::StringFunc::Path::ConstructFull(request.m_watchFolder.c_str(), request.m_sourceFile.c_str(), fullPath, true);
+
+            PassAsset passAsset;
+            AZ::Outcome loadResult = JsonSerializationUtils::LoadObjectFromFile(passAsset, fullPath);
+
+            if (!loadResult.IsSuccess())
+            {
+                AZ_Error(PassBuilderName, false, "Failed to load pass asset [%s]", request.m_sourceFile.c_str());
+                AZ_Error(PassBuilderName, false, "Loading issues: %s", loadResult.GetError().data());
+                return;
+            }
+
+            // Find all Asset IDs we depend on
+            AZStd::unordered_set dependentList;
+            Uuid passAssetUuid = AzTypeInfo::Uuid();
+
+            FindPassReferenceAssetParams params;
+            params.passAssetObject = &passAsset;
+            params.passAssetSourceFile = request.m_sourceFile;
+            params.passAssetUuid = passAssetUuid;
+            params.serializeContext = serializeContext;
+            params.jobKey = "Shader Asset";
+
+            if (!FindPassReferencedAssets(params, dependentList, response, job, true))
+            {
+                return;
+            }
+
+            for (const AssetBuilderSDK::PlatformInfo& platformInfo : request.m_enabledPlatforms)
+            {
+                job.m_jobKey = PassBuilderJobKey;
+                job.SetPlatformIdentifier(platformInfo.m_identifier.c_str());
+
+                // Passes are a critical part of the rendering system
+                job.m_critical = true;
+
+                response.m_createJobOutputs.push_back(job);
+            }
+
+            response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success;
+        }
+
+
+
         void PassBuilder::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response) const
         {
             // Handle job cancellation and shutdown cases
@@ -164,9 +270,9 @@ namespace AZ
             }
 
             // Get serialization context
-            SerializeContext* context = nullptr;
-            ComponentApplicationBus::BroadcastResult(context, &ComponentApplicationBus::Events::GetSerializeContext);
-            if (!context)
+            SerializeContext* serializeContext = nullptr;
+            ComponentApplicationBus::BroadcastResult(serializeContext, &ComponentApplicationBus::Events::GetSerializeContext);
+            if (!serializeContext)
             {
                 AZ_Assert(false, "No serialize context");
                 return;
@@ -186,7 +292,18 @@ namespace AZ
             // Find all Asset IDs we depend on
             AZStd::unordered_set dependentList;
             Uuid passAssetUuid = AzTypeInfo::Uuid();
-            if (!FindPassReferencedAssets(&passAsset, passAssetUuid, context, dependentList))
+
+            FindPassReferenceAssetParams params;
+            params.passAssetObject = &passAsset;
+            params.passAssetSourceFile = request.m_sourceFile;
+            params.passAssetUuid = passAssetUuid;
+            params.serializeContext = serializeContext;
+            params.jobKey = "Shader Asset";
+
+            AssetBuilderSDK::CreateJobsResponse dummyResponse;
+            AssetBuilderSDK::JobDescriptor dummyJob;
+
+            if (!FindPassReferencedAssets(params, dependentList, dummyResponse, dummyJob, false))
             {
                 return;
             }
@@ -198,7 +315,7 @@ namespace AZ
             AzFramework::StringFunc::Path::ConstructFull(request.m_tempDirPath.c_str(), destFileName.c_str(), destPath, true);
 
             // Save the asset to binary format for production
-            bool result = Utils::SaveObjectToFile(destPath, DataStream::ST_BINARY, &passAsset, passAssetUuid, context);
+            bool result = Utils::SaveObjectToFile(destPath, DataStream::ST_BINARY, &passAsset, passAssetUuid, serializeContext);
             if (result == false)
             {
                 AZ_Error(PassBuilderName, false, "Failed to save asset to %s", destPath.c_str());
diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.h b/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.h
index 6130ae8edc..8c159efc56 100644
--- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.h
+++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.h
@@ -37,7 +37,6 @@ namespace AZ
             void RegisterBuilder();
 
         private:
-            bool FindPassReferencedAssets(void* objectPtr, Uuid passAssetUuid, SerializeContext* context, AZStd::unordered_set &referencedAssetList) const;
             bool m_isShuttingDown = false;
         };
 

From fceb29fa5f4ee42af1eb98c1517de2acf850f151 Mon Sep 17 00:00:00 2001
From: Nemerle 
Date: Fri, 6 Aug 2021 14:06:59 +0200
Subject: [PATCH 078/205] Editor: code style fixups in 2 files

A few small fixes ( for range loops + one -> check)

Signed-off-by: Nemerle 
---
 Code/Editor/PluginManager.cpp        | 22 +++++++++-------------
 Code/Editor/ResourceSelectorHost.cpp |  8 ++------
 2 files changed, 11 insertions(+), 19 deletions(-)

diff --git a/Code/Editor/PluginManager.cpp b/Code/Editor/PluginManager.cpp
index 5efd52a97e..1530641fa7 100644
--- a/Code/Editor/PluginManager.cpp
+++ b/Code/Editor/PluginManager.cpp
@@ -17,9 +17,8 @@
 // Editor
 #include "Include/IPlugin.h"
 
-
-using TPfnCreatePluginInstance = IPlugin *(*)(PLUGIN_INIT_PARAM *pInitParam);
-using TPfnQueryPluginSettings = void (*)(SPluginSettings &);
+using TPfnCreatePluginInstance = IPlugin* (*)(PLUGIN_INIT_PARAM* pInitParam);
+using TPfnQueryPluginSettings = void (*)(SPluginSettings&);
 
 CPluginManager::CPluginManager()
 {
@@ -155,7 +154,7 @@ bool CPluginManager::LoadPlugins(const char* pPathWithMask)
         }
 #endif
     }
-    if (plugins.size() == 0)
+    if (plugins.empty())
     {
         CLogFile::FormatLine("[Plugin Manager] Cannot find any plugins in plugin directory '%s'", strPath.toUtf8().data());
         return false;
@@ -269,13 +268,13 @@ void CPluginManager::RegisterPlugin(QLibrary* dllHandle, IPlugin* pPlugin)
 
 IPlugin* CPluginManager::GetPluginByGUID(const char* pGUID)
 {
-    for (auto it = m_plugins.begin(); it != m_plugins.end(); ++it)
+    for (const SPluginEntry& pluginEntry : m_plugins)
     {
-        const char* pPluginGuid = it->pPlugin->GetPluginGUID();
+        const char* pPluginGuid = pluginEntry.pPlugin->GetPluginGUID();
 
         if (pPluginGuid && !strcmp(pPluginGuid, pGUID))
         {
-            return it->pPlugin;
+            return pluginEntry.pPlugin;
         }
     }
 
@@ -332,14 +331,11 @@ IUIEvent* CPluginManager::GetEventByIDAndPluginID(uint8 aPluginID, uint8 aEventI
 
 bool CPluginManager::CanAllPluginsExitNow()
 {
-    for (auto it = m_plugins.begin(); it != m_plugins.end(); ++it)
+    for (const SPluginEntry& pluginEntry : m_plugins)
     {
-        if (it->pPlugin)
+        if (pluginEntry.pPlugin && !pluginEntry.pPlugin->CanExitNow())
         {
-            if (!it->pPlugin->CanExitNow())
-            {
-                return false;
-            }
+            return false;
         }
     }
 
diff --git a/Code/Editor/ResourceSelectorHost.cpp b/Code/Editor/ResourceSelectorHost.cpp
index af6c398fe7..39d36346e7 100644
--- a/Code/Editor/ResourceSelectorHost.cpp
+++ b/Code/Editor/ResourceSelectorHost.cpp
@@ -75,11 +75,7 @@ public:
 
     void SetGlobalSelection(const char* resourceType, const char* value) override
     {
-        if (!resourceType)
-        {
-            return;
-        }
-        if (!value)
+        if (!resourceType || !value)
         {
             return;
         }
@@ -101,7 +97,7 @@ public:
     }
 
 private:
-    using TTypeMap = std::map>;
+    using TTypeMap = std::map>;
     TTypeMap m_typeMap;
 
     std::map m_globallySelectedResources;

From 635b9686c6915803d472a56740b1c1cf028c417d Mon Sep 17 00:00:00 2001
From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
Date: Mon, 9 Aug 2021 11:18:38 -0700
Subject: [PATCH 079/205] [redcode/crythread-2nd-pass] removed CrySimpleThread
 and related code

Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
---
 Code/Legacy/CryCommon/CryThread.h             |  75 ---
 .../Legacy/CryCommon/CryThreadImpl_pthreads.h |   7 -
 Code/Legacy/CryCommon/CryThreadImpl_windows.h |  51 --
 Code/Legacy/CryCommon/CryThread_pthreads.h    | 440 ------------------
 Code/Legacy/CryCommon/CryThread_windows.h     | 206 --------
 5 files changed, 779 deletions(-)

diff --git a/Code/Legacy/CryCommon/CryThread.h b/Code/Legacy/CryCommon/CryThread.h
index b7b6a3adfd..fcd7be16ba 100644
--- a/Code/Legacy/CryCommon/CryThread.h
+++ b/Code/Legacy/CryCommon/CryThread.h
@@ -85,81 +85,6 @@ public:
 //////////////////////////////////////////////////////////////////////////
 typedef CryAutoLock CryAutoCriticalSection;
 
-/////////////////////////////////////////////////////////////////////////////
-//
-// Threads.
-
-// Base class for runnable objects.
-//
-// A runnable is an object with a Run() and a Cancel() method.  The Run()
-// method should perform the runnable's job.  The Cancel() method may be
-// called by another thread requesting early termination of the Run() method.
-// The runnable may ignore the Cancel() call, the default implementation of
-// Cancel() does nothing.
-class CryRunnable
-{
-public:
-    virtual ~CryRunnable() { }
-    virtual void Run() = 0;
-    virtual void Cancel() { }
-};
-
-// Class holding information about a thread.
-//
-// A reference to the thread information can be obtained by calling GetInfo()
-// on the CrySimpleThread (or derived class) instance.
-//
-// NOTE:
-// If the code is compiled with NO_THREADINFO defined, then the GetInfo()
-// method will return a reference to a static dummy instance of this
-// structure.  It is currently undecided if NO_THREADINFO will be defined for
-// release builds!
-
-struct CryThreadInfo
-{
-    // The symbolic name of the thread.
-    //
-    // You may set this name directly or through the SetName() method of
-    // CrySimpleThread (or derived class).
-    AZStd::string m_Name;
-
-
-    // A thread identification number.
-    // The number is unique but architecture specific.  Do not assume anything
-    // about that number except for being unique.
-    //
-    // This field is filled when the thread is started (i.e. before the Run()
-    // method or thread routine is called).  It is advised that you do not
-    // change this number manually.
-    uint32 m_ID;
-};
-
-// Simple thread class.
-//
-// CrySimpleThread is a simple wrapper around a system thread providing
-// nothing but system-level functionality of a thread.  There are two typical
-// ways to use a simple thread:
-//
-// 1. Derive from the CrySimpleThread class and provide an implementation of
-//    the Run() (and optionally Cancel()) methods.
-// 2. Specify a runnable object when the thread is started.  The default
-//    runnable type is CryRunnable.
-//
-// The Runnable class specfied as the template argument must provide Run()
-// and Cancel() methods compatible with the following signatures:
-//
-//   void Runnable::Run();
-//   void Runnable::Cancel();
-//
-// If the Runnable does not support cancellation, then the Cancel() method
-// should do nothing.
-//
-// The same instance of CrySimpleThread may be used for multiple thread
-// executions /in sequence/, i.e. it is valid to re-start the thread by
-// calling Start() after the thread has been joined by calling WaitForThread().
-template
-class CrySimpleThread;
-
 ///////////////////////////////////////////////////////////////////////////////
 // Include architecture specific code.
 #if AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS
diff --git a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
index c94d4fca90..358d8f962f 100644
--- a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
+++ b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
@@ -14,13 +14,6 @@
 
 #include "CryThread_pthreads.h"
 
-#if PLATFORM_SUPPORTS_THREADLOCAL
-THREADLOCAL CrySimpleThreadSelf
-* CrySimpleThreadSelf::m_Self = NULL;
-#else
-TLS_DEFINE(CrySimpleThreadSelf*, g_CrySimpleThreadSelf)
-#endif
-
 
 //////////////////////////////////////////////////////////////////////////
 // CryEvent(Timed) implementation
diff --git a/Code/Legacy/CryCommon/CryThreadImpl_windows.h b/Code/Legacy/CryCommon/CryThreadImpl_windows.h
index 5cf970414d..9d636fd41a 100644
--- a/Code/Legacy/CryCommon/CryThreadImpl_windows.h
+++ b/Code/Legacy/CryCommon/CryThreadImpl_windows.h
@@ -12,16 +12,6 @@
 #include 
 #include  // for CreateSemaphore
 
-struct SThreadNameDesc
-{
-    DWORD dwType;
-    LPCSTR szName;
-    DWORD dwThreadID;
-    DWORD dwFlags;
-};
-
-THREADLOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL;
-
 //////////////////////////////////////////////////////////////////////////
 CryEvent::CryEvent()
 {
@@ -302,44 +292,3 @@ void CryFastSemaphore::Release()
         m_Semaphore.Release();
     }
 }
-
-//////////////////////////////////////////////////////////////////////////
-CrySimpleThreadSelf::CrySimpleThreadSelf()
-    : m_thread(NULL)
-    , m_threadId(0)
-{
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CrySimpleThreadSelf::WaitForThread()
-{
-    assert(m_thread);
-    PREFAST_ASSUME(m_thread);
-    if (GetCurrentThreadId() != m_threadId)
-    {
-        WaitForSingleObject((HANDLE)m_thread, INFINITE);
-    }
-}
-
-CrySimpleThreadSelf::~CrySimpleThreadSelf()
-{
-    if (m_thread)
-    {
-        CloseHandle(m_thread);
-    }
-}
-
-void CrySimpleThreadSelf::StartThread(unsigned (__stdcall * func)(void*), void* argList)
-{
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #include AZ_RESTRICTED_FILE(CryThreadImpl_windows_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-#undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-    m_thread = (void*)_beginthreadex(NULL, 0, func, argList, CREATE_SUSPENDED, &m_threadId);
-#endif
-    assert(m_thread);
-    PREFAST_ASSUME(m_thread);
-    ResumeThread((HANDLE)m_thread);
-}
diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h
index 72b29344ec..9102c12c38 100644
--- a/Code/Legacy/CryCommon/CryThread_pthreads.h
+++ b/Code/Legacy/CryCommon/CryThread_pthreads.h
@@ -653,444 +653,4 @@ private:
 
 typedef CryEventTimed CryEvent;
 
-#if !PLATFORM_SUPPORTS_THREADLOCAL
-TLS_DECLARE(class CrySimpleThreadSelf*, g_CrySimpleThreadSelf);
-#endif
-
-class CrySimpleThreadSelf
-{
-protected:
-#if PLATFORM_SUPPORTS_THREADLOCAL
-
-    static CrySimpleThreadSelf* GetSelf()
-    {
-        return m_Self;
-    }
-
-    static void SetSelf(CrySimpleThreadSelf* pSelf)
-    {
-        m_Self = pSelf;
-    }
-private:
-    static THREADLOCAL CrySimpleThreadSelf* m_Self;
-
-#else
-
-    static CrySimpleThreadSelf* GetSelf()
-    {
-        return TLS_GET(CrySimpleThreadSelf*, g_CrySimpleThreadSelf);
-    }
-
-    static void SetSelf(CrySimpleThreadSelf* pSelf)
-    {
-        TLS_SET(g_CrySimpleThreadSelf, pSelf);
-    }
-
-#endif
-};
-
-template
-class CrySimpleThread
-    : public CryRunnable
-    , protected CrySimpleThreadSelf
-{
-public:
-    typedef void (* ThreadFunction)(void*);
-    typedef CryRunnable RunnableT;
-    
-    const volatile bool& GetStartedState() const { return m_bIsStarted; }
-
-private:
-#if !defined(NO_THREADINFO)
-    CryThreadInfo m_Info;
-#endif
-    pthread_t m_ThreadID;
-    unsigned m_CpuMask;
-    Runnable* m_Runnable;
-    struct
-    {
-        ThreadFunction m_ThreadFunction;
-        void* m_ThreadParameter;
-    } m_ThreadFunction;
-    volatile bool m_bIsStarted;
-    volatile bool m_bIsRunning;
-
-protected:
-    virtual void Terminate()
-    {
-        // This method must be empty.
-        // Derived classes overriding Terminate() are not required to call this
-        // method.
-    }
-
-private:
-#if !defined(NO_THREADINFO)
-    static void SetThreadInfo(CrySimpleThread* self)
-    {
-        pthread_t thread = pthread_self();
-        self->m_Info.m_ID = (uint32)(TRUNCATE_PTR)thread;
-#if defined(APPLE)
-        pthread_setname_np(self->m_Info.m_Name.c_str());
-#endif
-    }
-#else
-    static void SetThreadInfo(CrySimpleThread* self) { }
-#endif
-
-    static void* PthreadRunRunnable(void* thisPtr)
-    {
-        CrySimpleThread* const self = (CrySimpleThread*)thisPtr;
-        SetSelf(self);
-        self->m_bIsStarted = true;
-        self->m_bIsRunning = true;
-        SetThreadInfo(self);
-        self->m_Runnable->Run();
-        self->m_bIsRunning = false;
-        self->Terminate();
-        SetSelf(NULL);
-        return NULL;
-    }
-
-    static void* PthreadRunThis(void* thisPtr)
-    {
-        CrySimpleThread* const self = (CrySimpleThread*)thisPtr;
-        SetSelf(self);
-        self->m_bIsStarted = true;
-        self->m_bIsRunning = true;
-        SetThreadInfo(self);
-        self->Run();
-        self->m_bIsRunning = false;
-        self->Terminate();
-        SetSelf(NULL);
-        return NULL;
-    }
-
-    CrySimpleThread(const CrySimpleThread&);
-    void operator = (const CrySimpleThread&);
-
-public:
-    CrySimpleThread()
-        : m_CpuMask(0)
-        , m_bIsStarted(false)
-        , m_bIsRunning(false)
-    {
-        m_ThreadFunction.m_ThreadFunction = NULL;
-        m_ThreadFunction.m_ThreadParameter = NULL;
-#if !defined(NO_THREADINFO)
-        m_Info.m_Name = "";
-        m_Info.m_ID = 0;
-#endif
-        memset(&m_ThreadID, 0, sizeof m_ThreadID);
-        m_Runnable = NULL;
-    }
-
-    virtual ~CrySimpleThread()
-    {
-        if (IsStarted())
-        {
-            // Note: We don't want to cache a pointer to ISystem and/or ILog to
-            // gain more freedom on when the threading classes are used (e.g.
-            // threads may be started very early in the initialization).
-            ISystem* pSystem = GetISystem();
-            ILog* pLog = NULL;
-            if (pSystem != NULL)
-            {
-                pLog = pSystem->GetILog();
-            }
-            if (pLog != NULL)
-            {
-                pLog->LogError("Runaway thread %s", GetName());
-            }
-            Cancel();
-            WaitForThread();
-        }
-    }
-
-#if !defined(NO_THREADINFO)
-    CryThreadInfo& GetInfo() { return m_Info; }
-    const char* GetName()
-    {
-        return m_Info.m_Name.c_str();
-    }
-
-    // Set the name of the called thread.
-    //
-    // WIN32:
-    // If the thread is started, then the VC debugger is informed about the new
-    // thread name.  If the thread is not started, then the VC debugger will be
-    // informed lated when the thread is started through one of the Start()
-    // methods.
-    //
-    // If the parameter Name is NULL, then the name of the thread is kept
-    // unchanged.  This may be used to sent the current thread name to the VC
-    // debugger.
-    void SetName(const char* Name)
-    {
-        if (Name != NULL)
-        {
-            if (m_ThreadID)
-            {
-                RegisterThreadName(m_ThreadID, Name);
-            }
-            m_Info.m_Name = Name;
-        }
-#if defined(WIN32)
-        if (IsStarted())
-        {
-            // The VC debugger gets the information about a thread's name through
-            // the exception 0x406D1388.
-            struct
-            {
-                DWORD Type;
-                const char* Name;
-                DWORD ID;
-                DWORD Flags;
-            } Info = { 0x1000, NULL, 0, 0 };
-            Info.ID = (DWORD)m_Info.m_ID;
-            __try
-            {
-                RaiseException(
-                    0x406D1388, 0, sizeof Info / sizeof(DWORD), (ULONG_PTR*)&Info);
-            }
-            __except (EXCEPTION_CONTINUE_EXECUTION)
-            {
-            }
-        }
-#endif
-    }
-#else
-#if !defined(NO_THREADINFO)
-    CryThreadInfo& GetInfo()
-    {
-        static CryThreadInfo dummyInfo = { "", 0 };
-        return dummyInfo;
-    }
-#endif
-    const char* GetName() { return ""; }
-    void SetName(const char* Name) { }
-#endif
-
-    virtual void Run()
-    {
-        // This Run() implementation supports the void StartFunction() method.
-        // However, code using this class (or derived classes) should eventually
-        // be refactored to use one of the other Start() methods.  This code will
-        // be removed some day and the default implementation of Run() will be
-        // empty.
-        if (m_ThreadFunction.m_ThreadFunction != NULL)
-        {
-            m_ThreadFunction.m_ThreadFunction(m_ThreadFunction.m_ThreadParameter);
-        }
-    }
-
-    // Cancel the running thread.
-    //
-    // If the thread class is implemented as a derived class of CrySimpleThread,
-    // then the derived class should provide an appropriate implementation for
-    // this method.  Calling the base class implementation is _not_ required.
-    //
-    // If the thread was started by specifying a Runnable (template argument),
-    // then the Cancel() call is passed on to the specified runnable.
-    //
-    // If the thread was started using the StartFunction() method, then the
-    // caller must find other means to inform the thread about the cancellation
-    // request.
-    virtual void Cancel()
-    {
-        if (IsStarted() && m_Runnable != NULL)
-        {
-            UnRegisterThreadName(m_ThreadID);
-            m_Runnable->Cancel();
-        }
-    }
-
-    virtual void Start(Runnable& runnable, unsigned cpuMask = 0, const char* name = NULL, int32 StackSize = (SIMPLE_THREAD_STACK_SIZE_KB * 1024))
-    {
-#if defined(LARGE_THREAD_STACK)
-        StackSize *= 4;//debug code needs a lot more than profile
-#endif
-        assert(m_ThreadID == 0);
-        pthread_attr_t threadAttr;
-        pthread_attr_init(&threadAttr);
-        pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE);
-        pthread_attr_setstacksize(&threadAttr, StackSize);
-        if (name)
-        {
-            this->m_Info.m_Name = name;
-        }
-#if CRYTHREAD_PTHREADS_H_TRAIT_SET_THREAD_NAME
-        threadAttr.name = (char*)name;
-#endif
-        m_CpuMask = cpuMask;
-#if defined(PTHREAD_NPTL)
-        if (cpuMask != ~0 && cpuMask != 0)
-        {
-            cpu_set_t cpuSet;
-            CPU_ZERO(&cpuSet);
-            for (int cpu = 0; cpu < sizeof(cpuMask) * 8; ++cpu)
-            {
-                if (cpuMask & (1 << cpu))
-                {
-                    CPU_SET(cpu, &cpuSet);
-                }
-            }
-            pthread_attr_setaffinity_np(&threadAttr, sizeof cpuSet, &cpuSet);
-        }
-#elif defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_START_RUNNABLE
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-        m_Runnable = &runnable;
-        int err = pthread_create(
-                &m_ThreadID,
-                &threadAttr,
-                PthreadRunRunnable,
-                this);
-        pthread_attr_destroy(&threadAttr);
-        RegisterThreadName(m_ThreadID, name);
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_START_RUNNABLE_CPUMASK_POSTCREATE
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-        assert(err == 0);
-    }
-
-    virtual void Start(unsigned cpuMask = 0, const char* name = NULL, int32 Priority = THREAD_PRIORITY_NORMAL, int32 StackSize = (SIMPLE_THREAD_STACK_SIZE_KB * 1024))
-    {
-#if defined(LARGE_THREAD_STACK)
-        StackSize *= 4;//debug code needs a lot more than profile
-#endif
-        assert(m_ThreadID == 0);
-        pthread_attr_t threadAttr;
-        sched_param schedParam;
-        pthread_attr_init(&threadAttr);
-        pthread_attr_getschedparam(&threadAttr, &schedParam);
-        schedParam.sched_priority   =   Priority;
-        pthread_attr_setschedparam(&threadAttr, &schedParam);
-        pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE);
-        pthread_attr_setstacksize(&threadAttr, StackSize);
-        if (name)
-        {
-            this->m_Info.m_Name = name;
-        }
-#if CRYTHREAD_PTHREADS_H_TRAIT_SET_THREAD_NAME
-        threadAttr.name = (char*)name;
-#endif
-        m_CpuMask = cpuMask;
-#if defined(PTHREAD_NPTL)
-        if (cpuMask != ~0 && cpuMask != 0)
-        {
-            cpu_set_t cpuSet;
-            CPU_ZERO(&cpuSet);
-            for (int cpu = 0; cpu < sizeof(cpuMask) * 8; ++cpu)
-            {
-                if (cpuMask & (1 << cpu))
-                {
-                    CPU_SET(cpu, &cpuSet);
-                }
-            }
-            pthread_attr_setaffinity_np(&threadAttr, sizeof cpuSet, &cpuSet);
-        }
-#elif defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_START_CPUMASK
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-        int err = pthread_create(
-                &m_ThreadID,
-                &threadAttr,
-                PthreadRunThis,
-                this);
-        pthread_attr_destroy(&threadAttr);
-        RegisterThreadName(m_ThreadID, name);
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_START_CPUMASK_POSTCREATE
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-        assert(err == 0);
-    }
-
-    void StartFunction(
-        ThreadFunction threadFunction,
-        void* threadParameter = NULL,
-        unsigned cpuMask = 0
-        )
-    {
-        m_ThreadFunction.m_ThreadFunction = threadFunction;
-        m_ThreadFunction.m_ThreadParameter = threadParameter;
-        Start(cpuMask);
-    }
-
-    static CrySimpleThread* Self()
-    {
-        return reinterpret_cast*>(GetSelf());
-    }
-
-    void Exit()
-    {
-        assert(m_ThreadID == pthread_self());
-        m_bIsRunning = false;
-        Terminate();
-        SetSelf(NULL);
-        pthread_exit(NULL);
-        UnRegisterThreadName(m_ThreadID);
-    }
-
-    void WaitForThread()
-    {
-        if (pthread_self() != m_ThreadID)
-        {
-            int err = pthread_join(m_ThreadID, NULL);
-            assert(err == 0);
-        }
-        m_bIsStarted = false;
-        memset(&m_ThreadID, 0, sizeof m_ThreadID);
-    }
-
-    unsigned SetCpuMask(unsigned cpuMask)
-    {
-        int oldCpuMask = m_CpuMask;
-        if (cpuMask == m_CpuMask)
-        {
-            return oldCpuMask;
-        }
-        m_CpuMask = cpuMask;
-#if defined(PTHREAD_NPTL)
-        cpu_set_t cpuSet;
-        CPU_ZERO(&cpuSet);
-        if (cpuMask != ~0 && cpuMask != 0)
-        {
-            for (int cpu = 0; cpu < sizeof(cpuMask) * 8; ++cpu)
-            {
-                if (cpuMask & (1 << cpu))
-                {
-                    CPU_SET(cpu, &cpuSet);
-                }
-            }
-            else
-            {
-                CPU_ZERO(&cpuSet);
-                for (int cpu = 0; i < sizeof(cpuSet) * 8; ++cpu)
-                {
-                    CPU_SET(cpu, &cpuSet);
-                }
-            }
-            pthread_attr_setaffinity_np(&threadAttr, sizeof cpuSet, &cpuSet);
-#elif defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SETCPUMASK
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-            return oldCpuMask;
-        }
-
-        unsigned GetCpuMask() { return m_CpuMask; }
-
-        void Stop()
-        {
-            m_bIsStarted = false;
-        }
-
-        bool IsStarted() const { return m_bIsStarted; }
-        bool IsRunning() const { return m_bIsRunning; }
-    };
-
 #include "MemoryAccess.h"
diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h
index cc09cc530b..87147549f7 100644
--- a/Code/Legacy/CryCommon/CryThread_windows.h
+++ b/Code/Legacy/CryCommon/CryThread_windows.h
@@ -179,209 +179,3 @@ private:
     CrySemaphore m_Semaphore;
     volatile int32 m_nCounter;
 };
-
-//////////////////////////////////////////////////////////////////////////
-class CrySimpleThreadSelf
-{
-public:
-    CrySimpleThreadSelf();
-    void WaitForThread();
-    virtual ~CrySimpleThreadSelf();
-protected:
-    void StartThread(unsigned (__stdcall * func)(void*), void* argList);
-    static THREADLOCAL CrySimpleThreadSelf* m_Self;
-private:
-    CrySimpleThreadSelf(const CrySimpleThreadSelf&);
-    CrySimpleThreadSelf& operator = (const CrySimpleThreadSelf&);
-protected:
-    void* m_thread;
-    uint32 m_threadId;
-};
-
-template
-class CrySimpleThread
-    : public CryRunnable
-    , public CrySimpleThreadSelf
-{
-public:
-    typedef void (* ThreadFunction)(void*);
-    typedef CryRunnable RunnableT;
-
-    void SetName(const char* Name)
-    {
-        m_name = Name;
-    }
-    const char* GetName() { return m_name; }
-
-    const volatile bool& GetStartedState() const { return m_bIsStarted; }
-
-private:
-    Runnable* m_Runnable;
-    struct
-    {
-        ThreadFunction m_ThreadFunction;
-        void* m_ThreadParameter;
-    } m_ThreadFunction;
-    volatile bool m_bIsStarted;
-    volatile bool m_bIsRunning;
-    volatile bool m_bCreatedThread;
-    string m_name;
-
-protected:
-    virtual void Terminate()
-    {
-        // This method must be empty.
-        // Derived classes overriding Terminate() are not required to call this
-        // method.
-    }
-
-private:
-    static unsigned __stdcall RunRunnable(void* thisPtr)
-    {
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_WINDOWS_H_SECTION_1
-    #include AZ_RESTRICTED_FILE(CryThread_windows_h)
-#endif
-        CrySimpleThread* const self = (CrySimpleThread*)thisPtr;
-        self->m_bIsStarted = true;
-        self->m_bIsRunning = true;
-
-        self->m_Runnable->Run();
-        self->m_bIsRunning = false;
-        self->m_bCreatedThread = false;
-        self->Terminate();
-        return 0;
-    }
-
-    static unsigned __stdcall RunThis(void* thisPtr)
-    {
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_WINDOWS_H_SECTION_2
-    #include AZ_RESTRICTED_FILE(CryThread_windows_h)
-#endif
-        CrySimpleThread* const self = (CrySimpleThread*)thisPtr;
-        self->m_bIsStarted = true;
-        self->m_bIsRunning = true;
-
-        self->Run();
-        self->m_bIsRunning = false;
-        self->m_bCreatedThread = false;
-        self->Terminate();
-        return 0;
-    }
-
-    CrySimpleThread(const CrySimpleThread&);
-    void operator = (const CrySimpleThread&);
-
-public:
-    CrySimpleThread()
-        : m_bIsStarted(false)
-        , m_bIsRunning(false)
-        , m_bCreatedThread(false)
-    {
-        m_thread = NULL;
-        m_Runnable = NULL;
-    }
-    void* GetHandle() { return m_thread; }
-
-    virtual ~CrySimpleThread()
-    {
-        if (IsStarted())
-        {
-            if (gEnv && gEnv->pLog)
-            {
-                gEnv->pLog->LogError("Runaway thread %p '%s'", m_thread, m_name.c_str());
-            }
-        }
-
-        if (m_bCreatedThread)
-        {
-            Cancel();
-            WaitForThread();
-        }
-    }
-
-    virtual void Run()
-    {
-        // This Run() implementation supports the void StartFunction() method.
-        // However, code using this class (or derived classes) should eventually
-        // be refactored to use one of the other Start() methods.  This code will
-        // be removed some day and the default implementation of Run() will be
-        // empty.
-        if (m_ThreadFunction.m_ThreadFunction != NULL)
-        {
-            m_ThreadFunction.m_ThreadFunction(m_ThreadFunction.m_ThreadParameter);
-        }
-    }
-
-    // Cancel the running thread.
-    //
-    // If the thread class is implemented as a derived class of CrySimpleThread,
-    // then the derived class should provide an appropriate implementation for
-    // this method.  Calling the base class implementation is _not_ required.
-    //
-    // If the thread was started by specifying a Runnable (template argument),
-    // then the Cancel() call is passed on to the specified runnable.
-    //
-    // If the thread was started using the StartFunction() method, then the
-    // caller must find other means to inform the thread about the cancellation
-    // request.
-    virtual void Cancel()
-    {
-        if (IsStarted() && m_Runnable != NULL)
-        {
-            m_Runnable->Cancel();
-        }
-    }
-
-    virtual void Start(Runnable& runnable, [[maybe_unused]] unsigned cpuMask = 0, const char* = NULL, int32 = 0)
-    {
-        if (m_bCreatedThread)
-        {
-            // Don't start thread more than once!
-            return;
-        }
-        m_Runnable = &runnable;
-        m_bCreatedThread = true;
-        StartThread(RunRunnable, this);
-    }
-
-    virtual void Start([[maybe_unused]] unsigned cpuMask = 0, const char* = NULL, int32 = 0, int32 = 0)
-    {
-        if (m_bCreatedThread)
-        {
-            // Don't start thread more than once!
-            return;
-        }
-        m_bCreatedThread = true;
-        StartThread(RunThis, this);
-    }
-
-    void StartFunction(
-        ThreadFunction threadFunction,
-        void* threadParameter = NULL
-        )
-    {
-        m_ThreadFunction.m_ThreadFunction = threadFunction;
-        m_ThreadFunction.m_ThreadParameter = threadParameter;
-        Start();
-    }
-
-    static CrySimpleThread* Self()
-    {
-        return reinterpret_cast*>(m_Self);
-    }
-
-    void Exit()
-    {
-        assert(!"implemented");
-    }
-
-    void Stop()
-    {
-        m_bIsStarted = false;
-    }
-
-    bool IsStarted() const { return m_bIsStarted; }
-    bool IsRunning() const { return m_bIsRunning; }
-};

From 6a2d5cd370ae0e35c47188531a3a7eb6d2197e1f Mon Sep 17 00:00:00 2001
From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
Date: Mon, 9 Aug 2021 12:22:03 -0700
Subject: [PATCH 080/205] [redcode/crythread-2nd-pass] removed Cry-TLS macros
 from platform.h

Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
---
 Code/Legacy/CryCommon/platform.h | 54 --------------------------------
 1 file changed, 54 deletions(-)

diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h
index 6aad8dd043..851da316e0 100644
--- a/Code/Legacy/CryCommon/platform.h
+++ b/Code/Legacy/CryCommon/platform.h
@@ -277,18 +277,6 @@
   #define PRINTF_EMPTY_FORMAT ""
 #endif
 
-#if defined(IOS)
-#define USE_PTHREAD_TLS
-#endif
-
-// Storage class modifier for thread local storage.
-// THEADLOCAL should NOT be defined to empty because that creates some
-// really hard to find issues.
-#if !defined(USE_PTHREAD_TLS)
-#   define THREADLOCAL AZ_TRAIT_COMPILER_THREAD_LOCAL
-#endif //!defined(USE_PTHREAD_TLS)
-
-
 
 //////////////////////////////////////////////////////////////////////////
 // define Read Write Barrier macro needed for lockless programming
@@ -735,48 +723,6 @@ enum ETriState
         #define _MS_ALIGN(num) AZ_PUSH_DISABLE_WARNING(4324, "-Wunknown-warning-option")
 #endif
 
-#if defined(WIN32) || defined(WIN64)
-extern "C" {
-__declspec(dllimport) unsigned long __stdcall TlsAlloc();
-__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long dwTlsIndex);
-__declspec(dllimport) int __stdcall TlsSetValue(unsigned long dwTlsIndex, void* lpTlsValue);
-}
-
-    #define TLS_DECLARE(type, var) extern int var##idx;
-    #define TLS_DEFINE(type, var)              \
-    int var##idx;                              \
-    struct Init##var {                         \
-        Init##var() { var##idx = TlsAlloc(); } \
-    };                                         \
-    Init##var g_init##var;
-    #define TLS_DEFINE_DEFAULT_VALUE(type, var, value)                                \
-    int var##idx;                                                                     \
-    struct Init##var {                                                                \
-        Init##var() { var##idx = TlsAlloc(); TlsSetValue(var##idx, reinterpret_cast(value)); } \
-    };                                                                                \
-    Init##var g_init##var;
-    #define TLS_GET(type, var) (type)TlsGetValue(var##idx)
-    #define TLS_SET(var, val) TlsSetValue(var##idx, reinterpret_cast(val))
-#elif defined(USE_PTHREAD_TLS)
-    #define TLS_DECLARE(_TYPE, _VAR) extern SCryPthreadTLS<_TYPE> _VAR##TLSKey;
-    #define TLS_DEFINE(_TYPE, _VAR) SCryPthreadTLS<_TYPE> _VAR##TLSKey;
-    #define TLS_DEFINE_DEFAULT_VALUE(_TYPE, _VAR, _DEFAULT) SCryPthreadTLS<_TYPE> _VAR##TLSKey = _DEFAULT;
-    #define TLS_GET(_TYPE, _VAR) _VAR##TLSKey.Get()
-    #define TLS_SET(_VAR, _VALUE) _VAR##TLSKey.Set(_VALUE)
-#elif defined(THREADLOCAL)
-    #define TLS_DECLARE(type, var) extern THREADLOCAL type var;
-#if defined(LINUX) || defined(MAC)
-    #define TLS_DEFINE(type, var) THREADLOCAL type var = 0;
-#else
-    #define TLS_DEFINE(type, var) THREADLOCAL type var;
-#endif // defined(LINUX) || defined(MAC)
-    #define TLS_DEFINE_DEFAULT_VALUE(type, var, value) THREADLOCAL type var = value;
-    #define TLS_GET(type, var) (var)
-    #define TLS_SET(var, val) (var = (val))
-#else // defined(THREADLOCAL)
-    #error "There's no support for thread local storage"
-#endif
-
 #if defined(AZ_RESTRICTED_PLATFORM)
     #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_13
     #include AZ_RESTRICTED_FILE(platform_h)

From 2e2bbe80b118e5481a8be0b275ec039cf4ee3a7e Mon Sep 17 00:00:00 2001
From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
Date: Mon, 9 Aug 2021 13:19:41 -0700
Subject: [PATCH 081/205] [redcode/crythread-2nd-pass] removed CryEvent types

Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
---
 .../Legacy/CryCommon/CryThreadImpl_pthreads.h | 47 -------------------
 Code/Legacy/CryCommon/CryThreadImpl_windows.h | 39 ---------------
 Code/Legacy/CryCommon/CryThread_pthreads.h    | 34 --------------
 Code/Legacy/CryCommon/CryThread_windows.h     | 30 ------------
 4 files changed, 150 deletions(-)

diff --git a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
index 358d8f962f..38838991a8 100644
--- a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
+++ b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
@@ -14,53 +14,6 @@
 
 #include "CryThread_pthreads.h"
 
-
-//////////////////////////////////////////////////////////////////////////
-// CryEvent(Timed) implementation
-//////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////
-void CryEventTimed::Reset()
-{
-    m_lockNotify.Lock();
-    m_flag = false;
-    m_lockNotify.Unlock();
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryEventTimed::Set()
-{
-    m_lockNotify.Lock();
-    m_flag = true;
-    m_cond.Notify();
-    m_lockNotify.Unlock();
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryEventTimed::Wait()
-{
-    m_lockNotify.Lock();
-    if (!m_flag)
-    {
-        m_cond.Wait(m_lockNotify);
-    }
-    m_flag  =   false;
-    m_lockNotify.Unlock();
-}
-
-//////////////////////////////////////////////////////////////////////////
-bool CryEventTimed::Wait(const uint32 timeoutMillis)
-{
-    bool bResult = true;
-    m_lockNotify.Lock();
-    if (!m_flag)
-    {
-        bResult = m_cond.TimedWait(m_lockNotify, timeoutMillis);
-    }
-    m_flag  =   false;
-    m_lockNotify.Unlock();
-    return bResult;
-}
-
 ///////////////////////////////////////////////////////////////////////////////
 // CryCriticalSection implementation
 ///////////////////////////////////////////////////////////////////////////////
diff --git a/Code/Legacy/CryCommon/CryThreadImpl_windows.h b/Code/Legacy/CryCommon/CryThreadImpl_windows.h
index 9d636fd41a..d81f3b0689 100644
--- a/Code/Legacy/CryCommon/CryThreadImpl_windows.h
+++ b/Code/Legacy/CryCommon/CryThreadImpl_windows.h
@@ -12,45 +12,6 @@
 #include 
 #include  // for CreateSemaphore
 
-//////////////////////////////////////////////////////////////////////////
-CryEvent::CryEvent()
-{
-    m_handle = (void*)CreateEvent(NULL, FALSE, FALSE, NULL);
-}
-
-//////////////////////////////////////////////////////////////////////////
-CryEvent::~CryEvent()
-{
-    CloseHandle(m_handle);
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryEvent::Reset()
-{
-    ResetEvent(m_handle);
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryEvent::Set()
-{
-    SetEvent(m_handle);
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryEvent::Wait() const
-{
-    WaitForSingleObject(m_handle, INFINITE);
-}
-
-//////////////////////////////////////////////////////////////////////////
-bool CryEvent::Wait(const uint32 timeoutMillis) const
-{
-    if (WaitForSingleObject(m_handle, timeoutMillis) == WAIT_TIMEOUT)
-    {
-        return false;
-    }
-    return true;
-}
 
 //////////////////////////////////////////////////////////////////////////
 // CryLock_WinMutex
diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h
index 9102c12c38..8dd4bfba6c 100644
--- a/Code/Legacy/CryCommon/CryThread_pthreads.h
+++ b/Code/Legacy/CryCommon/CryThread_pthreads.h
@@ -619,38 +619,4 @@ struct SCryPthreadTLS
 {
 };
 
-
-//////////////////////////////////////////////////////////////////////////
-// CryEvent(Timed) represent a synchronization event
-//////////////////////////////////////////////////////////////////////////
-class CryEventTimed
-{
-public:
-    ILINE CryEventTimed(){m_flag = false; }
-    ILINE ~CryEventTimed(){}
-
-    // Reset the event to the unsignalled state.
-    void Reset();
-    // Set the event to the signalled state.
-    void Set();
-    // Access a HANDLE to wait on.
-    void* GetHandle() const { return NULL; };
-    // Wait indefinitely for the object to become signalled.
-    void Wait();
-    // Wait, with a time limit, for the object to become signalled.
-    bool Wait(const uint32 timeoutMillis);
-
-private:
-    // Lock for synchronization of notifications.
-    CryCriticalSection m_lockNotify;
-#if defined(LINUX) || defined(APPLE)
-    CryConditionVariableT< CryLockT > m_cond;
-#else
-    CryConditionVariable m_cond;
-#endif
-    volatile bool m_flag;
-};
-
-typedef CryEventTimed CryEvent;
-
 #include "MemoryAccess.h"
diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h
index 87147549f7..68908ab34a 100644
--- a/Code/Legacy/CryCommon/CryThread_windows.h
+++ b/Code/Legacy/CryCommon/CryThread_windows.h
@@ -17,36 +17,6 @@
 #define CRYTHREAD_WINDOWS_H_SECTION_2 2
 #endif
 
-//////////////////////////////////////////////////////////////////////////
-// CryEvent represent a synchronization event
-//////////////////////////////////////////////////////////////////////////
-class CryEvent
-{
-public:
-    CryEvent();
-    ~CryEvent();
-
-    // Reset the event to the unsignalled state.
-    void Reset();
-    // Set the event to the signalled state.
-    void Set();
-    // Access a HANDLE to wait on.
-    void* GetHandle() const { return m_handle; };
-    // Wait indefinitely for the object to become signalled.
-    void Wait() const;
-    // Wait, with a time limit, for the object to become signalled.
-    bool Wait(const uint32 timeoutMillis) const;
-
-private:
-    CryEvent(const CryEvent&);
-    CryEvent& operator = (const CryEvent&);
-
-private:
-    void* m_handle;
-};
-
-typedef CryEvent CryEventTimed;
-
 //////////////////////////////////////////////////////////////////////////
 
 //////////////////////////////////////////////////////////////////////////

From f47b8b534ba7abb2b24cd6cf29bb0a025c8ce2c3 Mon Sep 17 00:00:00 2001
From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
Date: Mon, 9 Aug 2021 14:03:42 -0700
Subject: [PATCH 082/205] [redcode/crythread-2nd-pass] removed unused
 CryConditionVariable in CryEdit

Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
---
 Code/Editor/CryEdit.cpp | 2 --
 1 file changed, 2 deletions(-)

diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp
index cd1dd4fe47..5a5b17f799 100644
--- a/Code/Editor/CryEdit.cpp
+++ b/Code/Editor/CryEdit.cpp
@@ -892,7 +892,6 @@ CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(LPCTSTR lp
 namespace
 {
     CryMutex g_splashScreenStateLock;
-    CryConditionVariable g_splashScreenStateChange;
     enum ESplashScreenState
     {
         eSplashScreenState_Init, eSplashScreenState_Started, eSplashScreenState_Destroy
@@ -932,7 +931,6 @@ void CCryEditApp::ShowSplashScreen(CCryEditApp* app)
     g_splashScreenState = eSplashScreenState_Started;
 
     g_splashScreenStateLock.Unlock();
-    g_splashScreenStateChange.Notify();
 
     splashScreen->show();
     // Make sure the initial paint of the splash screen occurs so we dont get stuck with a blank window

From 2408f7dc37acdb302026743d08ce13238e5ec3a8 Mon Sep 17 00:00:00 2001
From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
Date: Mon, 9 Aug 2021 14:49:29 -0700
Subject: [PATCH 083/205] [redcode/crythread-2nd-pass] removed more unused code
 from CryThread

Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
---
 Code/Legacy/CryCommon/CryThreadImpl_windows.h | 177 --------
 Code/Legacy/CryCommon/CryThread_pthreads.h    | 423 ------------------
 Code/Legacy/CryCommon/CryThread_windows.h     |  56 ---
 3 files changed, 656 deletions(-)

diff --git a/Code/Legacy/CryCommon/CryThreadImpl_windows.h b/Code/Legacy/CryCommon/CryThreadImpl_windows.h
index d81f3b0689..9157bde9bc 100644
--- a/Code/Legacy/CryCommon/CryThreadImpl_windows.h
+++ b/Code/Legacy/CryCommon/CryThreadImpl_windows.h
@@ -76,180 +76,3 @@ bool CryLock_CritSection::TryLock()
 {
     return TryEnterCriticalSection((CRITICAL_SECTION*)&m_cs) != FALSE;
 }
-
-//////////////////////////////////////////////////////////////////////////
-// most of this is taken from http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
-//////////////////////////////////////////////////////////////////////////
-CryConditionVariable::CryConditionVariable()
-{
-    m_waitersCount = 0;
-    m_wasBroadcast = 0;
-    m_sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
-    InitializeCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    m_waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
-}
-
-//////////////////////////////////////////////////////////////////////////
-CryConditionVariable::~CryConditionVariable()
-{
-    CloseHandle(m_sema);
-    DeleteCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    CloseHandle(m_waitersDone);
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryConditionVariable::Wait(LockType& lock)
-{
-    EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    m_waitersCount++;
-    LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-
-    SignalObjectAndWait(lock._get_win32_handle(), m_sema, INFINITE, FALSE);
-
-    EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    m_waitersCount--;
-    bool lastWaiter = m_wasBroadcast && m_waitersCount == 0;
-    LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-
-    if (lastWaiter)
-    {
-        SignalObjectAndWait(m_waitersDone, lock._get_win32_handle(), INFINITE, FALSE);
-    }
-    else
-    {
-        WaitForSingleObject(lock._get_win32_handle(), INFINITE);
-    }
-}
-
-//////////////////////////////////////////////////////////////////////////
-bool CryConditionVariable::TimedWait(LockType& lock, uint32 millis)
-{
-    EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    m_waitersCount++;
-    LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-
-    bool ok = true;
-    if (WAIT_TIMEOUT == SignalObjectAndWait(lock._get_win32_handle(), m_sema, millis, FALSE))
-    {
-        ok = false;
-    }
-
-    EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    m_waitersCount--;
-    bool lastWaiter = m_wasBroadcast && m_waitersCount == 0;
-    LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-
-    if (lastWaiter)
-    {
-        SignalObjectAndWait(m_waitersDone, lock._get_win32_handle(), INFINITE, FALSE);
-    }
-    else
-    {
-        WaitForSingleObject(lock._get_win32_handle(), INFINITE);
-    }
-
-    return ok;
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryConditionVariable::NotifySingle()
-{
-    EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    bool haveWaiters = m_waitersCount > 0;
-    LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    if (haveWaiters)
-    {
-        ReleaseSemaphore(m_sema, 1, 0);
-    }
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryConditionVariable::Notify()
-{
-    EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    bool haveWaiters = false;
-    if (m_waitersCount > 0)
-    {
-        m_wasBroadcast = 1;
-        haveWaiters = true;
-    }
-    if (haveWaiters)
-    {
-        ReleaseSemaphore(m_sema, m_waitersCount, 0);
-        LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-        WaitForSingleObject(m_waitersDone, INFINITE);
-        m_wasBroadcast = 0;
-    }
-    else
-    {
-        LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock);
-    }
-}
-
-//////////////////////////////////////////////////////////////////////////
-CrySemaphore::CrySemaphore(int nMaximumCount, int nInitialCount)
-{
-    m_Semaphore = (void*)CreateSemaphore(NULL, nInitialCount, nMaximumCount, NULL);
-}
-
-//////////////////////////////////////////////////////////////////////////
-CrySemaphore::~CrySemaphore()
-{
-    CloseHandle((HANDLE)m_Semaphore);
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CrySemaphore::Acquire()
-{
-    WaitForSingleObject((HANDLE)m_Semaphore, INFINITE);
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CrySemaphore::Release()
-{
-    ReleaseSemaphore((HANDLE)m_Semaphore, 1, NULL);
-}
-
-//////////////////////////////////////////////////////////////////////////
-CryFastSemaphore::CryFastSemaphore(int nMaximumCount, int nInitialCount)
-    : m_Semaphore(nMaximumCount)
-    , m_nCounter(nInitialCount)
-{
-}
-
-//////////////////////////////////////////////////////////////////////////
-CryFastSemaphore::~CryFastSemaphore()
-{
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryFastSemaphore::Acquire()
-{
-    int nCount = ~0;
-    do
-    {
-        nCount = *const_cast(&m_nCounter);
-    } while (CryInterlockedCompareExchange(alias_cast(&m_nCounter), nCount - 1, nCount) != nCount);
-
-    // if the count would have been 0 or below, go to kernel semaphore
-    if ((nCount - 1)  < 0)
-    {
-        m_Semaphore.Acquire();
-    }
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CryFastSemaphore::Release()
-{
-    int nCount = ~0;
-    do
-    {
-        nCount = *const_cast(&m_nCounter);
-    } while (CryInterlockedCompareExchange(alias_cast(&m_nCounter), nCount + 1, nCount) != nCount);
-
-    // wake up kernel semaphore if we have waiter
-    if (nCount < 0)
-    {
-        m_Semaphore.Release();
-    }
-}
diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h
index 8dd4bfba6c..9e04784f3f 100644
--- a/Code/Legacy/CryCommon/CryThread_pthreads.h
+++ b/Code/Legacy/CryCommon/CryThread_pthreads.h
@@ -48,52 +48,12 @@
     #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
 #endif
 
-#if !defined(RegisterThreadName)
-    #define RegisterThreadName(id, name)
-    #define UnRegisterThreadName(id)
-#endif
-
 #if defined(APPLE) || defined(ANDROID)
 // PTHREAD_MUTEX_FAST_NP is only defined by Pthreads-w32, thus not on MAC
     #define PTHREAD_MUTEX_FAST_NP PTHREAD_MUTEX_NORMAL
 #endif
 
-// Define LARGE_THREAD_STACK to use larger than normal per-thread stack
-#if defined(_DEBUG) && (defined(MAC) || defined(LINUX) || defined(AZ_PLATFORM_IOS))
-#define LARGE_THREAD_STACK
-#endif
-
-#if defined(LINUX)
-#undef RegisterThreadName
-ILINE void RegisterThreadName(pthread_t id, const char* name)
-{
-    if ((!name) || (!id))
-    {
-        return;
-    }
-    int ret;
-    // pthread names on linux are limited to 16 char
-    if (strlen(name) >= 16)
-    {
-        char thread_name[16];
-        memcpy(thread_name, name, 15);
-        thread_name[15] = 0;
-        ret = pthread_setname_np(id, thread_name);
-    }
-    else
-    {
-        ret = pthread_setname_np(id, name);
-    }
-    if (ret != 0)
-    {
-        CryLog("Failed to set thread name for %" PRI_THREADID ", name: %s", id, name);
-    }
-}
-#endif
-
 #if !defined _CRYTHREAD_HAVE_LOCK
-template
-class _PthreadCond;
 template
 class _PthreadLockBase;
 
@@ -130,8 +90,6 @@ template
 class _PthreadLock
     : public _PthreadLockBase
 {
-    friend class _PthreadCond;
-
     //#if defined(_DEBUG)
 public:
     //#endif
@@ -218,9 +176,6 @@ public:
 #if !defined(LINUX) && !defined(APPLE)
 #define CRYTHREAD_PTHREADS_H_TRAIT_DEFINE_CRYMUTEX 1
 #endif
-#if !defined(LINUX) && !defined(APPLE)
-#define CRYTHREAD_PTHREADS_H_TRAIT_SET_THREAD_NAME 1
-#endif
 #endif
 
 #if CRYTHREAD_PTHREADS_H_TRAIT_DEFINE_CRYMUTEX
@@ -237,386 +192,8 @@ class CryMutex
 #endif
 #endif // CRYTHREAD_PTHREADS_TRAIT_DEFINE_CRYMUTEX
 
-template
-class _PthreadCond
-{
-    pthread_cond_t m_Cond;
-
-public:
-    _PthreadCond() { pthread_cond_init(&m_Cond, NULL); }
-    ~_PthreadCond() { pthread_cond_destroy(&m_Cond); }
-    void Notify() { pthread_cond_broadcast(&m_Cond); }
-    void NotifySingle() { pthread_cond_signal(&m_Cond); }
-    void Wait(LockClass& Lock) { pthread_cond_wait(&m_Cond, &Lock.m_Lock); }
-    bool TimedWait(LockClass& Lock, uint32 milliseconds)
-    {
-        struct timeval now;
-        struct timespec timeout;
-        int err;
-
-        gettimeofday(&now, NULL);
-        while (true)
-        {
-            timeout.tv_sec = now.tv_sec + milliseconds / 1000;
-            uint64 nsec = (uint64)now.tv_usec * 1000 + (uint64)milliseconds * 1000000;
-            if (nsec >= 1000000000)
-            {
-                timeout.tv_sec += (long)(nsec / 1000000000);
-                nsec %= 1000000000;
-            }
-            timeout.tv_nsec = (long)nsec;
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_PTHREADCOND
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-            #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-            err = pthread_cond_timedwait(&m_Cond, &Lock.m_Lock, &timeout);
-            if (err == EINTR)
-            {
-                // Interrupted by a signal.
-                continue;
-            }
-            else if (err == ETIMEDOUT)
-            {
-                return false;
-            }
-#endif
-            else
-            {
-                assert(err == 0);
-            }
-            break;
-        }
-        return true;
-    }
-
-    // Get the POSIX pthread_cont_t.
-    // Warning:
-    // This method will not be available in the Win32 port of CryThread.
-    pthread_cond_t& Get_pthread_cond_t() { return m_Cond; }
-};
-
-#if AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS
-template 
-class CryConditionVariableT
-    : public _PthreadCond
-{
-};
-
-#if defined CRYLOCK_HAVE_FASTTLOCK
-template<>
-class CryConditionVariableT< CryLockT >
-    : public _PthreadCond< CryLockT >
-{
-    typedef CryLockT LockClass;
-    CryConditionVariableT(const CryConditionVariableT&);
-    CryConditionVariableT& operator = (const CryConditionVariableT&);
-
-public:
-    CryConditionVariableT() { }
-};
-#endif // CRYLOCK_HAVE_FASTLOCK
-
-template<>
-class CryConditionVariableT< CryLockT >
-    : public _PthreadCond< CryLockT >
-{
-    typedef CryLockT LockClass;
-    CryConditionVariableT(const CryConditionVariableT&);
-    CryConditionVariableT& operator = (const CryConditionVariableT&);
-
-public:
-    CryConditionVariableT() { }
-};
-
-#if !defined(_CRYTHREAD_CONDLOCK_GLITCH)
-typedef CryConditionVariableT< CryLockT > CryConditionVariable;
-#else
-typedef CryConditionVariableT< CryLockT > CryConditionVariable;
-#endif
-
 #define _CRYTHREAD_HAVE_LOCK 1
 
-#else // LINUX MAC
-
-#if defined CRYLOCK_HAVE_FASTLOCK
-template<>
-class CryConditionVariable
-    : public _PthreadCond< CryLockT >
-{
-    typedef CryLockT LockClass;
-    CryConditionVariable(const CryConditionVariable&);
-    CryConditionVariable& operator = (const CryConditionVariable&);
-
-public:
-    CryConditionVariable() { }
-};
-#endif // CRYLOCK_HAVE_FASTLOCK
-
-template<>
-class CryConditionVariable
-    : public _PthreadCond< CryLockT >
-{
-    typedef CryLockT LockClass;
-    CryConditionVariable(const CryConditionVariable&);
-    CryConditionVariable& operator = (const CryConditionVariable&);
-
-public:
-    CryConditionVariable() { }
-};
-
-#define _CRYTHREAD_HAVE_LOCK 1
-
-#endif // LINUX MAC
 #endif // !defined _CRYTHREAD_HAVE_LOCK
 
-//////////////////////////////////////////////////////////////////////////
-// Platform independet wrapper for a counting semaphore
-class CrySemaphore
-{
-public:
-    CrySemaphore(int nMaximumCount, int nInitialCount = 0);
-    ~CrySemaphore();
-
-    void Acquire();
-    void Release();
-
-private:
-#if defined(APPLE)
-    // Apple only supports named semaphores so have to use sem_open/unlink/sem_close instead
-    // of sem_open/sem_destroy, passing in this array for the name.
-    char m_semaphoreName[L_tmpnam];
-#endif
-    sem_t* m_Semaphore;
-};
-
-//////////////////////////////////////////////////////////////////////////
-inline CrySemaphore::CrySemaphore(int nMaximumCount, int nInitialCount)
-{
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_CONSTRUCT
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-    #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#elif defined(APPLE)
-#   pragma clang diagnostic push
-#   pragma clang diagnostic ignored "-Wdeprecated-declarations"
-    tmpnam(m_semaphoreName);
-#   pragma clang diagnostic pop
-    m_Semaphore = sem_open(m_semaphoreName, O_CREAT | O_EXCL, 0644, nInitialCount);
-#else
-    m_Semaphore = new sem_t;
-    sem_init(m_Semaphore, 0, nInitialCount);
-#endif
-}
-
-//////////////////////////////////////////////////////////////////////////
-inline CrySemaphore::~CrySemaphore()
-{
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_DESTROY
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-    #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#elif defined(APPLE)
-    sem_close(m_Semaphore);
-    sem_unlink(m_semaphoreName);
-#else
-    sem_destroy(m_Semaphore);
-    delete m_Semaphore;
-#endif
-}
-
-//////////////////////////////////////////////////////////////////////////
-inline void CrySemaphore::Acquire()
-{
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_ACQUIRE
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-    #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-    while (sem_wait(m_Semaphore) != 0 && errno == EINTR)
-    {
-        ;
-    }
-#endif
-}
-
-//////////////////////////////////////////////////////////////////////////
-inline void CrySemaphore::Release()
-{
-#if defined(AZ_RESTRICTED_PLATFORM)
-    #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_RELEASE
-    #include AZ_RESTRICTED_FILE(CryThread_pthreads_h)
-#endif
-#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED)
-    #undef AZ_RESTRICTED_SECTION_IMPLEMENTED
-#else
-    sem_post(m_Semaphore);
-#endif
-}
-
-//////////////////////////////////////////////////////////////////////////
-// Platform independet wrapper for a counting semaphore
-// except that this version uses C-A-S only until a blocking call is needed
-// -> No kernel call if there are object in the semaphore
-
-class CryFastSemaphore
-{
-public:
-    CryFastSemaphore(int nMaximumCount, int nInitialCount = 0);
-    ~CryFastSemaphore();
-    void Acquire();
-    void Release();
-
-private:
-    CrySemaphore m_Semaphore;
-    volatile int32 m_nCounter;
-};
-
-//////////////////////////////////////////////////////////////////////////
-inline CryFastSemaphore::CryFastSemaphore(int nMaximumCount, int nInitialCount)
-    : m_Semaphore(nMaximumCount)
-    , m_nCounter(nInitialCount)
-{
-}
-
-//////////////////////////////////////////////////////////////////////////
-inline CryFastSemaphore::~CryFastSemaphore()
-{
-}
-
-/////////////////////////////////////////////////////////////////////////
-inline void CryFastSemaphore::Acquire()
-{
-    int nCount = ~0;
-    do
-    {
-        nCount = *const_cast(&m_nCounter);
-    } while (CryInterlockedCompareExchange(alias_cast(&m_nCounter), nCount - 1, nCount) != nCount);
-
-    // if the count would have been 0 or below, go to kernel semaphore
-    if ((nCount - 1)  < 0)
-    {
-        m_Semaphore.Acquire();
-    }
-}
-
-//////////////////////////////////////////////////////////////////////////
-inline void CryFastSemaphore::Release()
-{
-    int nCount = ~0;
-    do
-    {
-        nCount = *const_cast(&m_nCounter);
-    } while (CryInterlockedCompareExchange(alias_cast(&m_nCounter), nCount + 1, nCount) != nCount);
-
-    // wake up kernel semaphore if we have waiter
-    if (nCount < 0)
-    {
-        m_Semaphore.Release();
-    }
-}
-
-////////////////////////////////////////////////////////////////////////////////
-// Provide TLS implementation using pthreads for those platforms without __thread
-////////////////////////////////////////////////////////////////////////////////
-
-struct SCryPthreadTLSBase
-{
-    SCryPthreadTLSBase(void (*pDestructor)(void*))
-    {
-        pthread_key_create(&m_kKey, pDestructor);
-    }
-
-    ~SCryPthreadTLSBase()
-    {
-        pthread_key_delete(m_kKey);
-    }
-
-    void* GetSpecific()
-    {
-        return pthread_getspecific(m_kKey);
-    }
-
-    void SetSpecific(const void* pValue)
-    {
-        pthread_setspecific(m_kKey, pValue);
-    }
-
-    pthread_key_t m_kKey;
-};
-
-template 
-struct SCryPthreadTLSImpl{};
-
-template 
-struct SCryPthreadTLSImpl
-    : private SCryPthreadTLSBase
-{
-    SCryPthreadTLSImpl()
-        :   SCryPthreadTLSBase(NULL)
-    {
-    }
-
-    T Get()
-    {
-        void* pSpecific(GetSpecific());
-        return *reinterpret_cast(&pSpecific);
-    }
-
-    void Set(const T& kValue)
-    {
-        SetSpecific(*reinterpret_cast(&kValue));
-    }
-};
-
-template 
-struct SCryPthreadTLSImpl
-    : private SCryPthreadTLSBase
-{
-    SCryPthreadTLSImpl()
-        :   SCryPthreadTLSBase(&Destroy)
-    {
-    }
-
-    T* GetPtr()
-    {
-        T* pPtr(static_cast(GetSpecific()));
-        if (pPtr == NULL)
-        {
-            pPtr = new T();
-            SetSpecific(pPtr);
-        }
-        return pPtr;
-    }
-
-    static void Destroy(void* pPointer)
-    {
-        delete static_cast(pPointer);
-    }
-
-    const T& Get()
-    {
-        return *GetPtr();
-    }
-
-    void Set(const T& kValue)
-    {
-        *GetPtr() = kValue;
-    }
-};
-
-template 
-struct SCryPthreadTLS
-    : SCryPthreadTLSImpl
-{
-};
-
 #include "MemoryAccess.h"
diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h
index 68908ab34a..5f83aa48e0 100644
--- a/Code/Legacy/CryCommon/CryThread_windows.h
+++ b/Code/Legacy/CryCommon/CryThread_windows.h
@@ -93,59 +93,3 @@ class CryMutex
 {
 };
 #define _CRYTHREAD_CONDLOCK_GLITCH 1
-
-//////////////////////////////////////////////////////////////////////////
-class CryConditionVariable
-{
-public:
-    typedef CryMutex LockType;
-
-    CryConditionVariable();
-    ~CryConditionVariable();
-    void Wait(LockType& lock);
-    bool TimedWait(LockType& lock, uint32 millis);
-    void NotifySingle();
-    void Notify();
-
-private:
-    CryConditionVariable(const CryConditionVariable&);
-    CryConditionVariable& operator = (const CryConditionVariable&);
-
-private:
-    int m_waitersCount;
-    CRY_CRITICAL_SECTION m_waitersCountLock;
-    void* m_sema;
-    void* m_waitersDone;
-    size_t m_wasBroadcast;
-};
-
-//////////////////////////////////////////////////////////////////////////
-// Platform independet wrapper for a counting semaphore
-class CrySemaphore
-{
-public:
-    CrySemaphore(int nMaximumCount, int nInitialCount = 0);
-    ~CrySemaphore();
-    void Acquire();
-    void Release();
-
-private:
-    void* m_Semaphore;
-};
-
-//////////////////////////////////////////////////////////////////////////
-// Platform independet wrapper for a counting semaphore
-// except that this version uses C-A-S only until a blocking call is needed
-// -> No kernel call if there are object in the semaphore
-class CryFastSemaphore
-{
-public:
-    CryFastSemaphore(int nMaximumCount, int nInitialCount = 0);
-    ~CryFastSemaphore();
-    void Acquire();
-    void Release();
-
-private:
-    CrySemaphore m_Semaphore;
-    volatile int32 m_nCounter;
-};

From 3bf4caf7d234ed86524e454b2d6c1e4b8462ac70 Mon Sep 17 00:00:00 2001
From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
Date: Mon, 9 Aug 2021 20:07:04 -0700
Subject: [PATCH 084/205] [redcode/crythread-2nd-pass] removed
 Cry*CriticalSection functions

Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com>
---
 Code/Legacy/CryCommon/CryThreadImpl.h         |  2 +-
 .../Legacy/CryCommon/CryThreadImpl_pthreads.h | 56 -------------------
 Code/Legacy/CryCommon/MultiThread.h           |  8 ---
 Code/Legacy/CryCommon/crycommon_files.cmake   |  1 -
 Code/Legacy/CryCommon/platform_impl.cpp       | 53 ------------------
 5 files changed, 1 insertion(+), 119 deletions(-)
 delete mode 100644 Code/Legacy/CryCommon/CryThreadImpl_pthreads.h

diff --git a/Code/Legacy/CryCommon/CryThreadImpl.h b/Code/Legacy/CryCommon/CryThreadImpl.h
index 0226b73716..4ff2cc6438 100644
--- a/Code/Legacy/CryCommon/CryThreadImpl.h
+++ b/Code/Legacy/CryCommon/CryThreadImpl.h
@@ -14,7 +14,7 @@
 
 // Include architecture specific code.
 #if defined(LINUX) || defined(APPLE)
-#include 
+// noting to include
 #define AZ_RESTRICTED_SECTION_IMPLEMENTED
 #elif defined(WIN32) || defined(WIN64)
 #include 
diff --git a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
deleted file mode 100644
index 38838991a8..0000000000
--- a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-
-#ifndef CRYINCLUDE_CRYCOMMON_CRYTHREADIMPL_PTHREADS_H
-#define CRYINCLUDE_CRYCOMMON_CRYTHREADIMPL_PTHREADS_H
-#pragma once
-
-
-#include "CryThread_pthreads.h"
-
-///////////////////////////////////////////////////////////////////////////////
-// CryCriticalSection implementation
-///////////////////////////////////////////////////////////////////////////////
-typedef CryLockT TCritSecType;
-
-void  CryDeleteCriticalSection(void* cs)
-{
-    delete ((TCritSecType*)cs);
-}
-
-void  CryEnterCriticalSection(void* cs)
-{
-    ((TCritSecType*)cs)->Lock();
-}
-
-bool  CryTryCriticalSection(void* cs)
-{
-    return false;
-}
-
-void  CryLeaveCriticalSection(void* cs)
-{
-    ((TCritSecType*)cs)->Unlock();
-}
-
-void  CryCreateCriticalSectionInplace(void* pCS)
-{
-    new (pCS) TCritSecType;
-}
-
-void CryDeleteCriticalSectionInplace(void*)
-{
-}
-
-void* CryCreateCriticalSection()
-{
-    return (void*) new TCritSecType;
-}
-
-#endif // CRYINCLUDE_CRYCOMMON_CRYTHREADIMPL_PTHREADS_H
diff --git a/Code/Legacy/CryCommon/MultiThread.h b/Code/Legacy/CryCommon/MultiThread.h
index 2b224c4743..c3aa892d14 100644
--- a/Code/Legacy/CryCommon/MultiThread.h
+++ b/Code/Legacy/CryCommon/MultiThread.h
@@ -48,14 +48,6 @@ LONG     CryInterlockedCompareExchange(LONG volatile* dst, LONG exchange, LONG c
 void*    CryInterlockedCompareExchangePointer(void* volatile* dst, void* exchange, void* comperand);
 void*  CryInterlockedExchangePointer       (void* volatile* dst, void* exchange);
 
-void*  CryCreateCriticalSection();
-void   CryCreateCriticalSectionInplace(void*);
-void   CryDeleteCriticalSection(void* cs);
-void   CryDeleteCriticalSectionInplace(void* cs);
-void   CryEnterCriticalSection(void* cs);
-bool   CryTryCriticalSection(void* cs);
-void   CryLeaveCriticalSection(void* cs);
-
 #if defined(AZ_RESTRICTED_PLATFORM)
     #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_DEFINE_CRYINTERLOCKEXCHANGE
     #include AZ_RESTRICTED_FILE(MultiThread_h)
diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake
index b4dac2ec08..487d08b13c 100644
--- a/Code/Legacy/CryCommon/crycommon_files.cmake
+++ b/Code/Legacy/CryCommon/crycommon_files.cmake
@@ -162,7 +162,6 @@ set(FILES
     CryLibrary.h
     CryThread_pthreads.h
     CryThread_windows.h
-    CryThreadImpl_pthreads.h
     CryThreadImpl_windows.h
     CryWindows.h
     Linux32Specific.h
diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp
index a677ba30b6..09d7493ae7 100644
--- a/Code/Legacy/CryCommon/platform_impl.cpp
+++ b/Code/Legacy/CryCommon/platform_impl.cpp
@@ -364,59 +364,6 @@ void CryInterlockedAdd(volatile size_t* pVal, ptrdiff_t iAdd)
     assert((iAdd == 0) || (iAdd < 0 && v < v - (size_t)iAdd) || (iAdd > 0 && v > v - (size_t)iAdd));
 }
 
-//////////////////////////////////////////////////////////////////////////
-void* CryCreateCriticalSection()
-{
-    CRITICAL_SECTION* pCS = new CRITICAL_SECTION;
-    InitializeCriticalSection(pCS);
-    return pCS;
-}
-
-void  CryCreateCriticalSectionInplace(void* pCS)
-{
-    InitializeCriticalSection((CRITICAL_SECTION*)pCS);
-}
-//////////////////////////////////////////////////////////////////////////
-void  CryDeleteCriticalSection(void* cs)
-{
-    CRITICAL_SECTION* pCS = (CRITICAL_SECTION*)cs;
-    if (pCS->LockCount >= 0)
-    {
-        CryFatalError("Critical Section hanging lock");
-    }
-    DeleteCriticalSection(pCS);
-    delete pCS;
-}
-
-//////////////////////////////////////////////////////////////////////////
-void  CryDeleteCriticalSectionInplace(void* cs)
-{
-    CRITICAL_SECTION* pCS = (CRITICAL_SECTION*)cs;
-    if (pCS->LockCount >= 0)
-    {
-        CryFatalError("Critical Section hanging lock");
-    }
-    DeleteCriticalSection(pCS);
-}
-
-//////////////////////////////////////////////////////////////////////////
-void  CryEnterCriticalSection(void* cs)
-{
-    EnterCriticalSection((CRITICAL_SECTION*)cs);
-}
-
-//////////////////////////////////////////////////////////////////////////
-bool  CryTryCriticalSection(void* cs)
-{
-    return TryEnterCriticalSection((CRITICAL_SECTION*)cs) != 0;
-}
-
-//////////////////////////////////////////////////////////////////////////
-void  CryLeaveCriticalSection(void* cs)
-{
-    LeaveCriticalSection((CRITICAL_SECTION*)cs);
-}
-
 //////////////////////////////////////////////////////////////////////////
 uint32 CryGetFileAttributes(const char* lpFileName)
 {

From d1240444982b7f6877d4d1101c67dac01bcb21b2 Mon Sep 17 00:00:00 2001
From: aaguilea 
Date: Tue, 10 Aug 2021 09:19:16 +0100
Subject: [PATCH 085/205] First step removing legacy code from the camera

Signed-off-by: aaguilea 
---
 Code/Editor/EditorViewportWidget.cpp          |  16 +-
 .../Editor/LegacyViewportCameraController.cpp | 537 ------------------
 Code/Editor/LegacyViewportCameraController.h  |  91 ---
 Code/Editor/editor_lib_files.cmake            |   2 -
 4 files changed, 4 insertions(+), 642 deletions(-)
 delete mode 100644 Code/Editor/LegacyViewportCameraController.cpp
 delete mode 100644 Code/Editor/LegacyViewportCameraController.h

diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp
index 4c638e1f82..419e51914d 100644
--- a/Code/Editor/EditorViewportWidget.cpp
+++ b/Code/Editor/EditorViewportWidget.cpp
@@ -72,7 +72,6 @@
 #include "IPostEffectGroup.h"
 #include "EditorPreferencesPageGeneral.h"
 #include "ViewportManipulatorController.h"
-#include "LegacyViewportCameraController.h"
 
 #include "ViewPane.h"
 #include "CustomResolutionDlg.h"
@@ -102,14 +101,13 @@
 
 AZ_CVAR(
     bool, ed_visibility_logTiming, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Output the timing of the new IVisibilitySystem query");
-AZ_CVAR(bool, ed_useNewCameraSystem, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Use the new Editor camera system");
 AZ_CVAR(bool, ed_showCursorCameraLook, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Show the cursor when using free look with the new camera system");
 
 namespace SandboxEditor
 {
     bool UsingNewCameraSystem()
     {
-        return ed_useNewCameraSystem;
+        return true;
     }
 } // namespace SandboxEditor
 
@@ -1476,14 +1474,9 @@ void EditorViewportWidget::SetViewportId(int id)
 
     m_renderViewport->GetControllerList()->Add(AZStd::make_shared());
 
-    if (ed_useNewCameraSystem)
-    {
-        m_renderViewport->GetControllerList()->Add(CreateModularViewportCameraController(AzFramework::ViewportId(id)));
-    }
-    else
-    {
-        m_renderViewport->GetControllerList()->Add(AZStd::make_shared());
-    }
+    
+    m_renderViewport->GetControllerList()->Add(CreateModularViewportCameraController(AzFramework::ViewportId(id)));
+    
 
     m_renderViewport->SetViewportSettings(&g_EditorViewportSettings);
 
@@ -2519,7 +2512,6 @@ void EditorViewportWidget::CenterOnAABB(const AABB& aabb)
     m_orbitDistance = fabs(m_orbitDistance);
 
     SetViewTM(newTM);
-    SandboxEditor::OrbitCameraControlsBus::Event(GetViewportId(), &SandboxEditor::OrbitCameraControlsBus::Events::SetOrbitDistance, m_orbitDistance);
 }
 
 void EditorViewportWidget::CenterOnSliceInstance()
diff --git a/Code/Editor/LegacyViewportCameraController.cpp b/Code/Editor/LegacyViewportCameraController.cpp
deleted file mode 100644
index eb7323b423..0000000000
--- a/Code/Editor/LegacyViewportCameraController.cpp
+++ /dev/null
@@ -1,537 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-#include "LegacyViewportCameraController.h"
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include "CryCommon/MathConversion.h"
-#include "SandboxAPI.h"
-#include "Settings.h"
-
-namespace SandboxEditor
-{
-
-LegacyViewportCameraControllerInstance::LegacyViewportCameraControllerInstance(AzFramework::ViewportId viewportId, LegacyViewportCameraController* controller)
-    : AzFramework::MultiViewportControllerInstanceInterface(viewportId, controller)
-{
-    OrbitCameraControlsBus::Handler::BusConnect(viewportId);
-}
-
-LegacyViewportCameraControllerInstance::~LegacyViewportCameraControllerInstance()
-{
-    OrbitCameraControlsBus::Handler::BusDisconnect();
-}
-
-bool LegacyViewportCameraControllerInstance::JustAltHeld() const
-{
-    return (m_modifiers ^ Qt::AltModifier) == 0;
-}
-
-bool LegacyViewportCameraControllerInstance::NoModifierHeld() const
-{
-    return !m_modifiers;
-}
-
-bool LegacyViewportCameraControllerInstance::AllowDolly() const
-{
-    return JustAltHeld();
-}
-
-bool LegacyViewportCameraControllerInstance::AllowOrbit() const
-{
-    return JustAltHeld();
-}
-
-bool LegacyViewportCameraControllerInstance::AllowPan() const
-{
-    // begin pan with alt (inverted movement) or no modifiers
-    return JustAltHeld() || NoModifierHeld();
-}
-
-bool LegacyViewportCameraControllerInstance::InvertPan() const
-{
-    return JustAltHeld();
-}
-
-void LegacyViewportCameraControllerInstance::SetOrbitDistance(float orbitDistance)
-{
-    m_orbitDistance = orbitDistance;
-}
-
-
-AZ::RPI::ViewportContextPtr LegacyViewportCameraControllerInstance::GetViewportContext()
-{
-    // This could be cached, if needed
-    auto viewportContextManager = AZ::Interface::Get();
-    if (!viewportContextManager)
-    {
-        return {};
-    }
-    return viewportContextManager->GetViewportContextById(GetViewportId());
-}
-
-bool LegacyViewportCameraControllerInstance::HandleMouseMove(
-    int dx, int dy)
-{
-    if (dx == 0 && dy == 0)
-    {
-        return false;
-    }
-
-    auto viewportContext = GetViewportContext();
-    if (!viewportContext)
-    {
-        return false;
-    }
-
-    float speedScale = gSettings.cameraMoveSpeed;
-
-    if (m_modifiers & Qt::Key_Control)
-    {
-        speedScale *= gSettings.cameraFastMoveSpeed;
-    }
-
-    if (m_inMoveMode || m_inOrbitMode || m_inRotateMode || m_inZoomMode)
-    {
-        m_totalMouseMoveDelta += AZStd::abs(dx) + AZStd::abs(dy);
-    }
-
-    if ((m_inRotateMode && m_inMoveMode) || m_inZoomMode)
-    {
-        Matrix34 m = AZTransformToLYTransform(viewportContext->GetCameraTransform());
-
-        Vec3 ydir = m.GetColumn1().GetNormalized();
-        Vec3 pos = m.GetTranslation();
-
-        const float posDelta = 0.2f * dy * speedScale;
-        pos = pos - ydir * posDelta;
-        m_orbitDistance = m_orbitDistance + posDelta;
-        m_orbitDistance = fabs(m_orbitDistance);
-
-        m.SetTranslation(pos);
-        viewportContext->SetCameraTransform(LYTransformToAZTransform(m));
-        return true;
-    }
-    else if (m_inRotateMode)
-    {
-        Ang3 angles(dy, 0, dx);
-        angles = angles * 0.002f * gSettings.cameraRotateSpeed;
-        if (gSettings.invertYRotation)
-        {
-            angles.x = -angles.x;
-        }
-        Matrix34 camtm = AZTransformToLYTransform(viewportContext->GetCameraTransform());
-        Ang3 ypr = CCamera::CreateAnglesYPR(Matrix33(camtm));
-        ypr.x += angles.z;
-        ypr.y += angles.x;
-
-        ypr.y = AZStd::clamp(ypr.y, -1.5f, 1.5f); // to keep rotation in reasonable range
-        ypr.z = 0;      // to have camera always upward
-
-        camtm = Matrix34(CCamera::CreateOrientationYPR(ypr), camtm.GetTranslation());
-        viewportContext->SetCameraTransform(LYTransformToAZTransform(camtm));
-        return true;
-    }
-    else if (m_inMoveMode)
-    {
-        // Slide.
-        Matrix34 m = AZTransformToLYTransform(viewportContext->GetCameraTransform());
-        Vec3 xdir = m.GetColumn0().GetNormalized();
-        Vec3 zdir = m.GetColumn2().GetNormalized();
-
-        if (InvertPan())
-        {
-            xdir = -xdir;
-            zdir = -zdir;
-        }
-
-        Vec3 pos = m.GetTranslation();
-        pos += 0.1f * xdir * dx * speedScale + 0.1f * zdir * dy * speedScale;
-        m.SetTranslation(pos);
-
-        AZ::Transform transform = viewportContext->GetCameraTransform();
-        transform.SetTranslation(LYVec3ToAZVec3(pos));
-        viewportContext->SetCameraTransform(transform);
-        return true;
-    }
-    else if (m_inOrbitMode)
-    {
-        Ang3 angles(dy, 0, dx);
-        angles = angles * 0.002f * gSettings.cameraRotateSpeed;
-
-        if (gSettings.invertPan)
-        {
-            angles.z = -angles.z;
-        }
-
-        Matrix34 m = AZTransformToLYTransform(viewportContext->GetCameraTransform());
-        Ang3 ypr = CCamera::CreateAnglesYPR(Matrix33(m));
-        ypr.x += angles.z;
-        ypr.y = AZStd::clamp(ypr.y, -1.5f, 1.5f); // to keep rotation in reasonable range
-        ypr.y += angles.x;
-
-        Matrix33 rotateTM = CCamera::CreateOrientationYPR(ypr);
-
-        Vec3 src = m.GetTranslation();
-        Vec3 trg(m_orbitTarget.GetX(), m_orbitTarget.GetY(), m_orbitTarget.GetZ());
-        float fCameraRadius = (trg - src).GetLength();
-
-        // Calc new source.
-        src = trg - rotateTM * Vec3(0, 1, 0) * fCameraRadius;
-        Matrix34 camTM = rotateTM;
-        camTM.SetTranslation(src);
-
-        viewportContext->SetCameraTransform(LYTransformToAZTransform(camTM));
-        return true;
-    }
-    return false;
-}
-
-bool LegacyViewportCameraControllerInstance::HandleMouseWheel(float zDelta)
-{
-    auto viewportContext = GetViewportContext();
-    if (!viewportContext)
-    {
-        return false;
-    }
-
-    Matrix34 m = AZTransformToLYTransform(viewportContext->GetCameraTransform());
-    const Vec3 ydir = m.GetColumn1().GetNormalized();
-
-    Vec3 pos = m.GetTranslation();
-
-    const float posDelta = 0.01f * zDelta * gSettings.wheelZoomSpeed;
-    pos += ydir * posDelta;
-    m_orbitDistance = m_orbitDistance - posDelta;
-    m_orbitDistance = fabs(m_orbitDistance);
-
-    m.SetTranslation(pos);
-    viewportContext->SetCameraTransform(LYTransformToAZTransform(m));
-    return true;
-}
-
-bool LegacyViewportCameraControllerInstance::IsKeyDown(Qt::Key key) const
-{
-    return m_pressedKeys.contains(key);
-}
-
-Qt::Key LegacyViewportCameraControllerInstance::GetKeyboardKey(const AzFramework::InputChannel& inputChannel)
-{
-    using Key = AzFramework::InputDeviceKeyboard::Key;
-    const auto& id = inputChannel.GetInputChannelId();
-    if (id == Key::AlphanumericW)
-    {
-        return Qt::Key_W;
-    }
-    else if (id == Key::AlphanumericA)
-    {
-        return Qt::Key_A;
-    }
-    else if (id == Key::AlphanumericS)
-    {
-        return Qt::Key_S;
-    }
-    else if (id == Key::AlphanumericD)
-    {
-        return Qt::Key_D;
-    }
-    else if (id == Key::AlphanumericQ)
-    {
-        return Qt::Key_Q;
-    }
-    else if (id == Key::AlphanumericE)
-    {
-        return Qt::Key_E;
-    }
-    else if (id == Key::NavigationArrowUp)
-    {
-        return Qt::Key_Up;
-    }
-    else if (id == Key::NavigationArrowUp)
-    {
-        return Qt::Key_Down;
-    }
-    else if (id == Key::NavigationArrowUp)
-    {
-        return Qt::Key_Left;
-    }
-    else if (id == Key::NavigationArrowUp)
-    {
-        return Qt::Key_Right;
-    }
-    return Qt::Key_unknown;
-}
-
-Qt::KeyboardModifier LegacyViewportCameraControllerInstance::GetKeyboardModifier(const AzFramework::InputChannel& inputChannel)
-{
-    using Key = AzFramework::InputDeviceKeyboard::Key;
-    const auto& id = inputChannel.GetInputChannelId();
-    if (id == Key::ModifierAltL || id == Key::ModifierAltR)
-    {
-        return Qt::KeyboardModifier::AltModifier;
-    }
-    if (id == Key::ModifierCtrlL || id == Key::ModifierCtrlR)
-    {
-        return Qt::KeyboardModifier::ControlModifier;
-    }
-    if (id == Key::ModifierShiftL || id == Key::ModifierShiftR)
-    {
-        return Qt::KeyboardModifier::ShiftModifier;
-    }
-    return Qt::KeyboardModifier::NoModifier;
-}
-
-bool LegacyViewportCameraControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event)
-{
-    using AzFramework::InputChannel;
-    using MouseButton = AzFramework::InputDeviceMouse::Button;
-    const auto& id = event.m_inputChannel.GetInputChannelId();
-    const auto& state = event.m_inputChannel.GetState();
-    bool shouldCaptureCursor = m_capturingCursor;
-    bool shouldConsumeEvent = false;
-
-    if (id == AzFramework::InputDeviceMouse::Movement::X || id == AzFramework::InputDeviceMouse::Movement::Y)
-    {
-        int dx = 0;
-        int dy = 0;
-        if (id == AzFramework::InputDeviceMouse::Movement::X)
-        {
-            dx = -aznumeric_cast(event.m_inputChannel.GetValue());
-        }
-        else
-        {
-            dy = -aznumeric_cast(event.m_inputChannel.GetValue());
-        }
-        return HandleMouseMove(dx, dy);
-    }
-    else if (id == MouseButton::Left)
-    {
-        if (state == InputChannel::State::Began)
-        {
-            if (AllowOrbit())
-            {
-                AzFramework::CameraState cameraState;
-                AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::EventResult(
-                    cameraState, event.m_viewportId,
-                    &AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Events::GetCameraState);
-
-                m_inOrbitMode = true;
-                m_orbitTarget = cameraState.m_position + cameraState.m_forward * m_orbitDistance;
-
-                shouldConsumeEvent = true;
-                shouldCaptureCursor = true;
-            }
-        }
-        else if (state == InputChannel::State::Ended)
-        {
-            m_inOrbitMode = false;
-            shouldCaptureCursor = false;
-        }
-    }
-    else if (id == MouseButton::Right)
-    {
-        if (state == InputChannel::State::Began)
-        {
-            if (AllowDolly())
-            {
-                m_inZoomMode = true;
-            }
-            else
-            {
-                m_inRotateMode = true;
-            }
-
-            shouldCaptureCursor = true;
-            // Record how much the cursor has been moved to see if we should own the mouse up event.
-            m_totalMouseMoveDelta = 0;
-        }
-        else if (state == InputChannel::State::Ended)
-        {
-            m_inZoomMode = false;
-            m_inRotateMode = false;
-            // If we've moved the cursor more than a couple pixels, we should eat this mouse up event to prevent the context menu controller from seeing it.
-            shouldConsumeEvent = m_totalMouseMoveDelta > 2;
-            shouldCaptureCursor = false;
-        }
-    }
-    else if (id == MouseButton::Middle)
-    {
-        if (state == InputChannel::State::Began)
-        {
-            if (AllowPan())
-            {
-                m_inMoveMode = true;
-                shouldConsumeEvent = true;
-                shouldCaptureCursor = true;
-            }
-        }
-        else if (state == InputChannel::State::Ended)
-        {
-            m_inMoveMode = false;
-            shouldCaptureCursor = false;
-        }
-    }
-    else if (auto modifier = GetKeyboardModifier(event.m_inputChannel); modifier != Qt::KeyboardModifier::NoModifier)
-    {
-        if (state == InputChannel::State::Ended)
-        {
-            m_modifiers &= ~modifier;
-        }
-        else
-        {
-            m_modifiers |= modifier;
-        }
-    }
-    else if (id == AzFramework::InputDeviceMouse::Movement::Z)
-    {
-        if (state == InputChannel::State::Began || state == InputChannel::State::Updated)
-        {
-            shouldConsumeEvent = HandleMouseWheel(event.m_inputChannel.GetValue());
-        }
-    }
-    else if (auto key = GetKeyboardKey(event.m_inputChannel); key != Qt::Key_unknown)
-    {
-        if (!event.m_inputChannel.IsActive())
-        {
-            m_pressedKeys.erase(key);
-        }
-        else
-        {
-            m_pressedKeys.insert(key);
-            shouldConsumeEvent = true;
-        }
-    }
-
-    UpdateCursorCapture(shouldCaptureCursor);
-
-    return shouldConsumeEvent;
-}
-
-void LegacyViewportCameraControllerInstance::UpdateCursorCapture(bool shouldCaptureCursor)
-{
-    if (m_capturingCursor != shouldCaptureCursor)
-    {
-        if (shouldCaptureCursor)
-        {
-            AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Event(
-                GetViewportId(),
-                &AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Events::BeginCursorCapture
-            );
-        }
-        else
-        {
-            AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Event(
-                GetViewportId(),
-                &AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Events::EndCursorCapture
-            );
-        }
-
-        m_capturingCursor = shouldCaptureCursor;
-    }
-}
-
-void LegacyViewportCameraControllerInstance::ResetInputChannels()
-{
-    m_modifiers = 0;
-    m_pressedKeys.clear();
-    UpdateCursorCapture(false);
-    m_inRotateMode = m_inMoveMode = m_inOrbitMode = m_inZoomMode = false;
-}
-
-void LegacyViewportCameraControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event)
-{
-    auto viewportContext = GetViewportContext();
-    if (!viewportContext)
-    {
-        return;
-    }
-
-    AZ::Transform transform = viewportContext->GetCameraTransform();
-    AZ::Vector3 xdir = transform.GetBasisX();
-    AZ::Vector3 ydir = transform.GetBasisY();
-    AZ::Vector3 zdir = transform.GetBasisZ();
-
-    AZ::Vector3 pos = transform.GetTranslation();
-
-    float speedScale = AZStd::GetMin(30.0f * event.m_deltaTime.count(), 20.0f);
-
-    // Use the global modifier keys instead of our keymap. It's more reliable.
-    const bool shiftPressed = m_modifiers & Qt::ShiftModifier;
-    const bool controlPressed = m_modifiers & Qt::ControlModifier;
-
-    speedScale *= gSettings.cameraMoveSpeed;
-    if (controlPressed)
-    {
-        return;
-    }
-
-    if (shiftPressed)
-    {
-        speedScale *= gSettings.cameraFastMoveSpeed;
-    }
-
-    bool cameraMoved = false;
-
-    if (IsKeyDown(Qt::Key_Up) || IsKeyDown(Qt::Key_W))
-    {
-        // move forward
-        cameraMoved = true;
-        pos = pos + (speedScale * m_moveSpeed * ydir);
-    }
-
-    if (IsKeyDown(Qt::Key_Down) || IsKeyDown(Qt::Key_S))
-    {
-        // move backward
-        cameraMoved = true;
-        pos = pos - (speedScale * m_moveSpeed * ydir);
-    }
-
-    if (IsKeyDown(Qt::Key_Left) || IsKeyDown(Qt::Key_A))
-    {
-        // move left
-        cameraMoved = true;
-        pos = pos - (speedScale * m_moveSpeed * xdir);
-    }
-
-    if (IsKeyDown(Qt::Key_Right) || IsKeyDown(Qt::Key_D))
-    {
-        // move right
-        cameraMoved = true;
-        pos = pos + (speedScale * m_moveSpeed * xdir);
-    }
-
-    if (IsKeyDown(Qt::Key_E))
-    {
-        // move Up
-        cameraMoved = true;
-        pos = pos + (speedScale * m_moveSpeed * zdir);
-    }
-
-    if (IsKeyDown(Qt::Key_Q))
-    {
-        // move down
-        cameraMoved = true;
-        pos = pos - (speedScale * m_moveSpeed * zdir);
-    }
-
-    if (cameraMoved)
-    {
-        transform.SetTranslation(pos);
-        viewportContext->SetCameraTransform(transform);
-    }
-}
-
-} //namespace SandboxEditor
diff --git a/Code/Editor/LegacyViewportCameraController.h b/Code/Editor/LegacyViewportCameraController.h
deleted file mode 100644
index 6edd344f23..0000000000
--- a/Code/Editor/LegacyViewportCameraController.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-#pragma once
-
-#include 
-#include 
-#include 
-#include 
-
-#include 
-
-#include 
-#include 
-
-namespace AzFramework
-{
-    struct ScreenPoint;
-}
-
-namespace SandboxEditor
-{
-    class OrbitCameraControls
-    : public AZ::EBusTraits
-    {
-    public:
-        //////////////////////////////////////////////////////////////////////////
-        // EBusTraits overrides
-        static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple;
-        static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById;
-        using BusIdType = AzFramework::ViewportId;
-        //////////////////////////////////////////////////////////////////////////
-
-        virtual void SetOrbitDistance(float orbitDistance [[maybe_unused]]) {;}
-    };
-    using OrbitCameraControlsBus = AZ::EBus;
-
-    class LegacyViewportCameraControllerInstance;
-    using LegacyViewportCameraController = AzFramework::MultiViewportController;
-
-    class LegacyViewportCameraControllerInstance final
-        : public AzFramework::MultiViewportControllerInstanceInterface
-        , public OrbitCameraControlsBus::Handler
-    {
-    public:
-        LegacyViewportCameraControllerInstance(AzFramework::ViewportId viewport, LegacyViewportCameraController* controller);
-        ~LegacyViewportCameraControllerInstance();
-
-        bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override;
-        void ResetInputChannels() override;
-        void UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) override;
-
-        void SetOrbitDistance(float orbitDistance) override;
-
-    private:
-        bool JustAltHeld() const;
-        bool NoModifierHeld() const;
-        bool AllowDolly() const;
-        bool AllowOrbit() const;
-        bool AllowPan() const;
-        bool InvertPan() const;
-
-        static Qt::KeyboardModifier GetKeyboardModifier(const AzFramework::InputChannel& inputChannel);
-        static Qt::Key GetKeyboardKey(const AzFramework::InputChannel& inputChannel);
-
-        AZ::RPI::ViewportContextPtr GetViewportContext();
-
-        bool HandleMouseMove(int dx, int dy);
-        bool HandleMouseWheel(float zDelta);
-        bool IsKeyDown(Qt::Key key) const;
-        void UpdateCursorCapture(bool shouldCaptureCursor);
-
-        bool m_inRotateMode = false;
-        bool m_inMoveMode = false;
-        bool m_inOrbitMode = false;
-        bool m_inZoomMode = false;
-        int m_totalMouseMoveDelta = 0;
-        float m_orbitDistance = 10.f;
-        float m_moveSpeed = 1.f;
-        AZ::Vector3 m_orbitTarget = {};
-        unsigned int m_modifiers = {};
-        AZStd::unordered_set m_pressedKeys;
-        bool m_capturingCursor = false;
-    };
-
-} //namespace SandboxEditor
diff --git a/Code/Editor/editor_lib_files.cmake b/Code/Editor/editor_lib_files.cmake
index d59edfe6a8..b921d4a559 100644
--- a/Code/Editor/editor_lib_files.cmake
+++ b/Code/Editor/editor_lib_files.cmake
@@ -803,8 +803,6 @@ set(FILES
     EditorViewportCamera.h
     ViewportManipulatorController.cpp
     ViewportManipulatorController.h
-    LegacyViewportCameraController.cpp
-    LegacyViewportCameraController.h
     RenderViewport.cpp
     RenderViewport.h
     TopRendererWnd.cpp

From 97d0456e5fe3c7d829b9db9d0af083334b5388bf Mon Sep 17 00:00:00 2001
From: aaguilea 
Date: Tue, 10 Aug 2021 12:08:01 +0100
Subject: [PATCH 086/205] uber nit

Signed-off-by: aaguilea 
---
 Code/Editor/EditorViewportWidget.cpp | 2 --
 1 file changed, 2 deletions(-)

diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp
index 419e51914d..75ac349501 100644
--- a/Code/Editor/EditorViewportWidget.cpp
+++ b/Code/Editor/EditorViewportWidget.cpp
@@ -1474,10 +1474,8 @@ void EditorViewportWidget::SetViewportId(int id)
 
     m_renderViewport->GetControllerList()->Add(AZStd::make_shared());
 
-    
     m_renderViewport->GetControllerList()->Add(CreateModularViewportCameraController(AzFramework::ViewportId(id)));
     
-
     m_renderViewport->SetViewportSettings(&g_EditorViewportSettings);
 
     UpdateScene();

From 43ae25b49b40b888d2e99d8d570e4fd23c0fdb13 Mon Sep 17 00:00:00 2001
From: antonmic <56370189+antonmic@users.noreply.github.com>
Date: Tue, 10 Aug 2021 10:00:42 -0700
Subject: [PATCH 087/205] fixed compiler loss of precision warning

Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com>
---
 Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp
index 2e61542c36..4da5560908 100644
--- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp
+++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp
@@ -172,7 +172,7 @@ namespace AZ
             if (viewDrawList.size() > 0 && drawLists.size() == 0)
             {
                 m_drawListView = viewDrawList;
-                m_drawItemCount += viewDrawList.size();
+                m_drawItemCount += (u32)viewDrawList.size();
                 PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount);
                 return;
             }
@@ -183,7 +183,7 @@ namespace AZ
             // combine draw items from mutiple draw lists to one draw list and sort it.
             for (auto drawList : drawLists)
             {
-                m_drawItemCount += drawList.size();
+                m_drawItemCount += (u32)drawList.size();
             }
             PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount);
             m_combinedDrawList.resize(m_drawItemCount);

From e3b22f51b2f210ff67e8d21d9bbcffb567406745 Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 10 Aug 2021 10:50:24 -0700
Subject: [PATCH 088/205] @lumberyard-employee-dm suggestion to use
 (w)string_view as the src to simplify functions in conversions.h

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 Code/Editor/CryEdit.cpp                       |   2 +-
 .../AzCore/AzCore/std/string/conversions.h    | 154 +++++-------------
 .../Keyboard/InputDeviceKeyboard_WinAPI.h     |   4 +-
 .../Keyboard/InputDeviceKeyboard_Windows.cpp  |   2 +-
 Code/Legacy/CrySystem/SystemWin32.cpp         |   2 +-
 Code/Legacy/CrySystem/XConsole.cpp            |   2 +-
 .../Support/include/CrashSupport.h            |   2 +-
 Code/Tools/GridHub/GridHub/main.cpp           |   6 +-
 .../RHI/DX12/Code/Source/RHI/MemoryView.cpp   |   2 +-
 .../Source/RHI/RayTracingPipelineState.cpp    |   6 +-
 .../Code/Source/RHI/RayTracingShaderTable.cpp |   2 +-
 .../AtomFont/Code/Source/FFont.cpp            |   2 +-
 .../Code/Source/UiTextInputComponent.cpp      |   2 +-
 13 files changed, 56 insertions(+), 132 deletions(-)

diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp
index 408de7be2c..0fc283c5c3 100644
--- a/Code/Editor/CryEdit.cpp
+++ b/Code/Editor/CryEdit.cpp
@@ -3225,7 +3225,7 @@ bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
 
 #ifdef WIN32
         wchar_t windowsErrorMessageW[ERROR_LEN];
-        windowsErrorMessageW = L'\0';
+        windowsErrorMessageW[0] = L'\0';
         FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
             nullptr,
             dw,
diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index c5c9b29cdb..40378467db 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -32,79 +32,79 @@ namespace AZStd
         {
             static_assert(Size == size_t{ 2 } || Size == size_t{ 4 }, "only wchar_t types of size 2 or 4 can be converted to utf8");
 
-            template
-            static inline void to_string(AZStd::basic_string& dest, const wchar_t* first, const wchar_t* last)
+            template
+            static inline void to_string(AZStd::basic_string& dest, AZStd::wstring_view src)
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest), dest.max_size());
+                    Utf8::Unchecked::utf16to8(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size());
+                    Utf8::Unchecked::utf32to8(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size());
                 }
             }
 
             template
-            static inline void to_string(AZStd::basic_fixed_string& dest, const wchar_t* first, const wchar_t* last)
+            static inline void to_string(AZStd::basic_fixed_string& dest, AZStd::wstring_view src)
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf16to8(first, last, AZStd::back_inserter(dest), dest.max_size());
+                    Utf8::Unchecked::utf16to8(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf32to8(first, last, AZStd::back_inserter(dest), dest.max_size());
+                    Utf8::Unchecked::utf32to8(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size());
                 }
             }
 
-            static inline char* to_string(char* dest, size_t destSize, const wchar_t* first, const wchar_t* last)
+            static inline char* to_string(char* dest, size_t destSize, AZStd::wstring_view src)
             {
                 if constexpr (Size == 2)
                 {
-                    return Utf8::Unchecked::utf16to8(first, last, dest, destSize);
+                    return Utf8::Unchecked::utf16to8(src.begin(), src.end(), dest, destSize);
                 }
                 else if constexpr (Size == 4)
                 {
-                    return Utf8::Unchecked::utf32to8(first, last, dest, destSize);
+                    return Utf8::Unchecked::utf32to8(src.begin(), src.end(), dest, destSize);
                 }
             }
 
-            template
-            static inline void to_wstring(AZStd::basic_string& dest, const char* first, const char* last)
+            template
+            static inline void to_wstring(AZStd::basic_string& dest, AZStd::string_view src)
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest), dest.max_size());
+                    Utf8::Unchecked::utf8to16(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size());
+                    Utf8::Unchecked::utf8to32(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size());
                 }
             }
 
             template
-            static inline void to_wstring(AZStd::basic_fixed_string& dest, const char* first, const char* last)
+            static inline void to_wstring(AZStd::basic_fixed_string& dest, AZStd::string_view src)
             {
                 if constexpr (Size == 2)
                 {
-                    Utf8::Unchecked::utf8to16(first, last, AZStd::back_inserter(dest), dest.max_size());
+                    Utf8::Unchecked::utf8to16(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size());
                 }
                 else if constexpr (Size == 4)
                 {
-                    Utf8::Unchecked::utf8to32(first, last, AZStd::back_inserter(dest), dest.max_size());
+                    Utf8::Unchecked::utf8to32(src.begin(), src.end(), AZStd::back_inserter(dest), dest.max_size());
                 }
             }
 
-            static inline wchar_t* to_wstring(wchar_t* dest, size_t destSize, const char* first, const char* last)
+            static inline wchar_t* to_wstring(wchar_t* dest, size_t destSize, AZStd::string_view src)
             {
                 if constexpr (Size == 2)
                 {
-                    return Utf8::Unchecked::utf8to16(first, last, dest, destSize);
+                    return Utf8::Unchecked::utf8to16(src.begin(), src.end(), dest, destSize);
                 }
                 else if constexpr (Size == 4)
                 {
-                    return Utf8::Unchecked::utf8to32(first, last, dest, destSize);
+                    return Utf8::Unchecked::utf8to32(src.begin(), src.end(), dest, destSize);
                 }
             }
         };
@@ -284,64 +284,26 @@ namespace AZStd
     inline AZStd::string to_string(long double val)         { AZStd::string str; to_string(str, val); return str; }
 
     // In our engine we assume AZStd::string is Utf8 encoded!
-    template
-    void to_string(AZStd::basic_string& dest, const wchar_t* str, size_t srcLen = 0)
+    template
+    void to_string(AZStd::basic_string& dest, AZStd::wstring_view src)
     {
         dest.clear();
-
-        if (srcLen == 0)
-        {
-            srcLen = wcslen(str);
-        }
-
-        if (srcLen > 0)
-        {
-            Internal::WCharTPlatformConverter<>::to_string(dest, str, str + srcLen);
-        }
-    }
-
-    template
-    void to_string(AZStd::basic_string& dest, const AZStd::basic_string& src)
-    {
-        return to_string(dest, src.c_str(), src.length());
+        Internal::WCharTPlatformConverter<>::to_string(dest, src);
     }
 
     template
-    void to_string(AZStd::basic_fixed_string& dest, const wchar_t* str, size_t srcLen = 0)
+    void to_string(AZStd::basic_fixed_string& dest, AZStd::wstring_view src)
     {
         dest.clear();
-
-        if (srcLen == 0)
-        {
-            srcLen = wcslen(str);
-        }
-
-        if (srcLen > 0)
-        {
-            Internal::WCharTPlatformConverter<>::to_string(dest, str, str + srcLen);
-        }
+        Internal::WCharTPlatformConverter<>::to_string(dest, src);
     }
 
-    template
-    void to_string(AZStd::basic_fixed_string& dest, const AZStd::basic_fixed_string& src)
+    inline void to_string(char* dest, size_t destSize, AZStd::wstring_view src)
     {
-        return to_string(dest, src.c_str(), src.length());
-    }
-
-    inline void to_string(char* dest, size_t destSize, const wchar_t* str, size_t srcLen = 0)
-    {
-        if (srcLen == 0)
+        char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, src);
+        if (endStr < (dest + destSize))
         {
-            srcLen = wcslen(str);
-        }
-
-        if (srcLen > 0)
-        {
-            char* endStr = Internal::WCharTPlatformConverter<>::to_string(dest, destSize, str, str + srcLen);
-            if (endStr < (dest + destSize))
-            {
-                *endStr = '\0'; // null terminator
-            }
+            *endStr = '\0'; // null terminator
         }
     }
 
@@ -441,64 +403,26 @@ namespace AZStd
     inline AZStd::wstring to_wstring(unsigned long long val)    { AZStd::wstring wstr; to_wstring(wstr, val); return wstr; }
     inline AZStd::wstring to_wstring(long double val)           { AZStd::wstring wstr; to_wstring(wstr, val); return wstr; }
 
-    template
-    void to_wstring(AZStd::basic_string& dest, const char* str, size_t strLen = 0)
+    template
+    void to_wstring(AZStd::basic_string& dest, AZStd::string_view src)
     {
         dest.clear();
-
-        if (strLen == 0)
-        {
-            strLen = strlen(str);
-        }
-
-        if (strLen > 0)
-        {
-            Internal::WCharTPlatformConverter<>::to_wstring(dest, str, str + strLen);
-        }
+        Internal::WCharTPlatformConverter<>::to_wstring(dest, src);
     }
 
-    template
-    void to_wstring(AZStd::basic_string& dest, const AZStd::basic_string& src)
-    {
-        return to_wstring(dest, src.c_str(), src.length());
-    }
-
-    template
-    void to_wstring(AZStd::basic_fixed_string& dest, const char* str, size_t strLen = 0)
+    template
+    void to_wstring(AZStd::basic_fixed_string& dest, AZStd::string_view src)
     {
         dest.clear();
-
-        if (strLen == 0)
-        {
-            strLen = strlen(str);
-        }
-
-        if (strLen > 0)
-        {
-            Internal::WCharTPlatformConverter<>::to_wstring(dest, str, str + strLen);
-        }
+        Internal::WCharTPlatformConverter<>::to_wstring(dest, src);
     }
 
-    template
-    void to_wstring(AZStd::basic_fixed_string& dest, const AZStd::basic_fixed_string& src)
+    inline void to_wstring(wchar_t* dest, size_t destSize, AZStd::string_view src)
     {
-        return to_wstring(dest, src.c_str(), src.length());
-    }
-
-    inline void to_wstring(wchar_t* dest, size_t destSize, const char* str, size_t srcLen = 0)
-    {
-        if (srcLen == 0)
+        wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, src);
+        if (endWStr < (dest + destSize))
         {
-            srcLen = strlen(str);
-        }
-
-        if (srcLen > 0)
-        {
-            wchar_t* endWStr = Internal::WCharTPlatformConverter<>::to_wstring(dest, destSize, str, str + srcLen);
-            if (endWStr < (dest + destSize))
-            {
-                *endWStr = '\0'; // null terminator
-            }
+            *endWStr = '\0'; // null terminator
         }
     }
 
diff --git a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h
index 591f8421b9..4c90b83bc4 100644
--- a/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h
+++ b/Code/Framework/AzFramework/Platform/Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h
@@ -59,7 +59,7 @@ namespace AzFramework
             {
                 // Convert the valid UTF-16 surrogate pair to a UTF-8 code point
                 const wchar_t codePointUTF16[2] = { m_leadSurrogate, codeUnitUTF16 };
-                AZStd::to_string(codePointUTF8, codePointUTF16, 2);
+                AZStd::to_string(codePointUTF8, { codePointUTF16, 2 });
                 m_leadSurrogate = 0;
             }
             else
@@ -72,7 +72,7 @@ namespace AzFramework
         {
             // Convert the standalone UTF-16 code point to a UTF-8 code point
             const wchar_t codePointUTF16[1] = { codeUnitUTF16 };
-            AZStd::to_string(codePointUTF8, codePointUTF16, 1);
+            AZStd::to_string(codePointUTF8, { codePointUTF16, 1 });
             m_leadSurrogate = 0;
         }
 
diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp
index 78364fbd0d..f3112ab89c 100644
--- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp
+++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp
@@ -253,7 +253,7 @@ namespace AzFramework
         if (stringLength != 0)
         {
             // Convert UTF-16 to UTF-8
-            AZStd::to_string(o_keyOrButtonText, buffer, stringLength);
+            AZStd::to_string(o_keyOrButtonText, { buffer, aznumeric_cast(stringLength) });
         }
     }
 
diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp
index b114c9bf12..da8e966b0a 100644
--- a/Code/Legacy/CrySystem/SystemWin32.cpp
+++ b/Code/Legacy/CrySystem/SystemWin32.cpp
@@ -126,7 +126,7 @@ const char* CSystem::GetUserName()
     DWORD dwSize = iNameBufferSize;
     wchar_t nameW[iNameBufferSize];
     ::GetUserNameW(nameW, &dwSize);
-    AZStd::to_string(szNameBuffer, iNameBufferSize, nameW, dwSize);
+    AZStd::to_string(szNameBuffer, iNameBufferSize, { nameW, dwSize });
     return szNameBuffer;
 #else
 #if defined(LINUX)
diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp
index 8e598c481d..ae07f86312 100644
--- a/Code/Legacy/CrySystem/XConsole.cpp
+++ b/Code/Legacy/CrySystem/XConsole.cpp
@@ -2861,7 +2861,7 @@ void CXConsole::Paste()
             {
                 // Convert UCS code-point into UTF-8 string
                 AZStd::fixed_string<5> utf8_buf = {0};
-                AZStd::to_string(utf8_buf.data(), 5, &cp, 1);
+                AZStd::to_string(utf8_buf.data(), 5, { &cp, 1 });
                 AddInputUTF8(utf8_buf.c_str());
             }
         }
diff --git a/Code/Tools/CrashHandler/Support/include/CrashSupport.h b/Code/Tools/CrashHandler/Support/include/CrashSupport.h
index 1393930913..e0bec5818b 100644
--- a/Code/Tools/CrashHandler/Support/include/CrashSupport.h
+++ b/Code/Tools/CrashHandler/Support/include/CrashSupport.h
@@ -41,7 +41,7 @@ namespace CrashHandler
         std::string returnPath;
         GetExecutablePath(returnPath);
         wchar_t currentFileNameW[CRASH_HANDLER_MAX_PATH_LEN] = { 0 };
-        AZStd::to_wstring(currentFileNameW, CRASH_HANDLER_MAX_PATH_LEN, returnPath.c_str(), returnPath.size());
+        AZStd::to_wstring(currentFileNameW, CRASH_HANDLER_MAX_PATH_LEN, { returnPath.c_str(), returnPath.size() });
         returnPathW = currentFileNameW;
     }
 
diff --git a/Code/Tools/GridHub/GridHub/main.cpp b/Code/Tools/GridHub/GridHub/main.cpp
index 670367bf06..bfb82efd0d 100644
--- a/Code/Tools/GridHub/GridHub/main.cpp
+++ b/Code/Tools/GridHub/GridHub/main.cpp
@@ -408,7 +408,7 @@ GridHubApplication::Create(const Descriptor& descriptor, const StartupParameters
         if (AZ::Utils::GetExecutablePath(originalExeFileName, AZ_ARRAY_SIZE(originalExeFileName)).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
         {
             wchar_t originalExeFileNameW[MAX_PATH];
-            AZStd::to_wstring(originalExeFileNameW, MAX_PATH, originalExeFileName, MAX_PATH);
+            AZStd::to_wstring(originalExeFileNameW, MAX_PATH, originalExeFileName);
             PathRemoveFileSpec(originalExeFileNameW);
             PathAppend(originalExeFileNameW, GRIDHUB_IMAGE_NAME);
 
@@ -489,7 +489,7 @@ void CopyAndRun(bool failSilently)
     if (AZ::Utils::GetExecutablePath(myFileName, MAX_PATH).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
     {
         wchar_t myFileNameW[MAX_PATH] = { 0 };
-        AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName, MAX_PATH);
+        AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName);
         wchar_t sourceProcPath[MAX_PATH] = { 0 };
         wchar_t targetProcPath[MAX_PATH] = { 0 };
         wchar_t procDrive[MAX_PATH] = { 0 };
@@ -567,7 +567,7 @@ void RelaunchImage()
     if (AZ::Utils::GetExecutablePath(myFileName, MAX_PATH).m_pathStored == AZ::Utils::ExecutablePathResult::Success)
     {
         wchar_t myFileNameW[MAX_PATH] = { 0 };
-        AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName, MAX_PATH);
+        AZStd::to_wstring(myFileNameW, MAX_PATH, myFileName);
         wchar_t targetProcPath[MAX_PATH] = { 0 };
         wchar_t procDrive[MAX_PATH] = { 0 };
         wchar_t procDir[MAX_PATH] = { 0 };
diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/MemoryView.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/MemoryView.cpp
index 1246fb5b1a..c9d932afb1 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/RHI/MemoryView.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/MemoryView.cpp
@@ -94,7 +94,7 @@ namespace AZ
             if (m_memoryAllocation.m_memory)
             {
                 AZStd::wstring wname;
-                AZStd::to_wstring(wname, name.data(), name.size());
+                AZStd::to_wstring(wname, name);
                 m_memoryAllocation.m_memory->SetName(wname.data());
             }
         }
diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingPipelineState.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingPipelineState.cpp
index aebf705790..be0c084d95 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingPipelineState.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingPipelineState.cpp
@@ -84,15 +84,15 @@ namespace AZ
             for (const RHI::RayTracingHitGroup& hitGroup : descriptor->GetHitGroups())
             {
                 AZStd::wstring hitGroupNameWstring;
-                AZStd::to_wstring(hitGroupNameWstring, hitGroup.m_hitGroupName.GetStringView().data(), hitGroup.m_hitGroupName.GetStringView().size());
+                AZStd::to_wstring(hitGroupNameWstring, hitGroup.m_hitGroupName.GetStringView());
                 hitGroupNameWstrings.push_back(hitGroupNameWstring);
 
                 AZStd::wstring closestHitShaderNameWstring;
-                AZStd::to_wstring(closestHitShaderNameWstring, hitGroup.m_closestHitShaderName.GetStringView().data(), hitGroup.m_closestHitShaderName.GetStringView().size());
+                AZStd::to_wstring(closestHitShaderNameWstring, hitGroup.m_closestHitShaderName.GetStringView());
                 closestHitShaderNameWstrings.push_back(closestHitShaderNameWstring);
 
                 AZStd::wstring anyHitShaderNameWstring;
-                AZStd::to_wstring(anyHitShaderNameWstring, hitGroup.m_anyHitShaderName.GetStringView().data(), hitGroup.m_anyHitShaderName.GetStringView().size());
+                AZStd::to_wstring(anyHitShaderNameWstring, hitGroup.m_anyHitShaderName.GetStringView());
                 anyHitShaderNameWstrings.push_back(anyHitShaderNameWstring);
 
                 D3D12_HIT_GROUP_DESC hitGroupDesc = {};
diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingShaderTable.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingShaderTable.cpp
index eefb1a28aa..21e7dbc82e 100644
--- a/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingShaderTable.cpp
+++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/RayTracingShaderTable.cpp
@@ -85,7 +85,7 @@ namespace AZ
                 uint8_t* nextRecord = RHI::AlignUp(mappedData + shaderRecordSize, D3D12_RAYTRACING_SHADER_RECORD_BYTE_ALIGNMENT);
 
                 AZStd::wstring shaderExportNameWstring;
-                AZStd::to_wstring(shaderExportNameWstring, record.m_shaderExportName.GetStringView().data(), record.m_shaderExportName.GetStringView().size());
+                AZStd::to_wstring(shaderExportNameWstring, record.m_shaderExportName.GetStringView());
                 void* shaderIdentifier = stateObjectProperties->GetShaderIdentifier(shaderExportNameWstring.c_str());
                 memcpy(mappedData, shaderIdentifier, D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES);
                 mappedData += D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES;
diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
index fd59b7aed4..9317cae846 100644
--- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
+++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp
@@ -1236,7 +1236,7 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str,
         // get char width and sum it to the line width
         // Note: This is not unicode compatible, since char-width depends on surrounding context (ie, combining diacritics etc)
         char codepoint[5];
-        AZStd::to_string(codepoint, 5, (wchar_t*)&ch, 1);
+        AZStd::to_string(codepoint, 5, { (wchar_t*)&ch, 1 });
         curCharWidth = GetTextSize(codepoint, true, ctx).x;
 
         // keep track of spaces
diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
index 0c61116945..0d9fc09063 100644
--- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
+++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp
@@ -1186,7 +1186,7 @@ void UiTextInputComponent::UpdateDisplayedTextFunction()
                 // work for cases tested but may not in general.
                 wchar_t wcharString[2] = { static_cast(this->GetReplacementCharacter()), 0 };
                 AZStd::string replacementCharString;
-                AZStd::to_string(replacementCharString, wcharString, 1);
+                AZStd::to_string(replacementCharString, { wcharString, 1 });
 
                 int numReplacementChars = LyShine::GetUtf8StringLength(originalText);
 

From 3b9044ce5d583114b15aaa5049ffbbf5191411bd Mon Sep 17 00:00:00 2001
From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
Date: Tue, 10 Aug 2021 11:31:16 -0700
Subject: [PATCH 089/205] Addressing missing test identified by @hultonha

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
---
 .../AzCore/AzCore/std/string/conversions.h      | 17 +++++++++++++++++
 .../Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp |  2 +-
 Code/Framework/AzCore/Tests/AZStd/String.cpp    |  6 ++++++
 3 files changed, 24 insertions(+), 1 deletion(-)

diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h
index 40378467db..b7887339e2 100644
--- a/Code/Framework/AzCore/AzCore/std/string/conversions.h
+++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h
@@ -70,6 +70,18 @@ namespace AZStd
                 }
             }
 
+            static inline size_t to_string_length(AZStd::wstring_view src)
+            {
+                if constexpr (Size == 2)
+                {
+                    return Utf8::Unchecked::utf16ToUtf8BytesRequired(src.begin(), src.end());
+                }
+                else if constexpr (Size == 4)
+                {
+                    return Utf8::Unchecked::utf32ToUtf8BytesRequired(src.begin(), src.end());
+                }
+            }
+
             template
             static inline void to_wstring(AZStd::basic_string& dest, AZStd::string_view src)
             {
@@ -307,6 +319,11 @@ namespace AZStd
         }
     }
 
+    inline size_t to_string_length(AZStd::wstring_view src)
+    {
+        return Internal::WCharTPlatformConverter<>::to_string_length(src);
+    }
+
     template
     int stoi(const AZStd::basic_string& str, AZStd::size_t* idx = 0, int base = 10)
     {
diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
index 4d8c9c8cfc..bcba24b768 100644
--- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
+++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Utils/Utils_WinAPI.cpp
@@ -43,7 +43,7 @@ namespace AZ
             }
             else
             {
-                size_t utf8PathSize = Utf8::Unchecked::utf16ToUtf8BytesRequired(pathBufferW, pathBufferW + pathLen);
+                size_t utf8PathSize = AZStd::to_string_length({ pathBufferW, pathLen });
                 if (utf8PathSize >= exeStorageSize)
                 {
                     result.m_pathStored = ExecutablePathResult::BufferSizeNotLargeEnough;
diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp
index 309f561a75..9dae4a3d3f 100644
--- a/Code/Framework/AzCore/Tests/AZStd/String.cpp
+++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp
@@ -674,6 +674,7 @@ namespace UnitTest
         string str1;
         to_string(str1, wstr);
         AZ_TEST_ASSERT(str1 == "BlaBla 5");
+        EXPECT_EQ(8, to_string_length(wstr));
 
         str1 = string::format("%ls", wstr.c_str());
         AZ_TEST_ASSERT(str1 == "BlaBla 5");
@@ -690,6 +691,11 @@ namespace UnitTest
         char strBuffer[9];
         to_string(strBuffer, 9, wstr1.c_str());
         AZ_TEST_ASSERT(0 == azstricmp(strBuffer, "BLABLA 5"));
+        EXPECT_EQ(8, to_string_length(wstr1));
+
+        // wstring to char with unicode
+        wstring ws1InfinityEscaped = L"Infinity: \u221E"; // escaped
+        EXPECT_EQ(13, to_string_length(ws1InfinityEscaped));
 
         // wchar_t buffer to char buffer
         wchar_t wstrBuffer[9] = L"BLABLA 5";

From e6259882b87d1096523c4167862b05ecfa5788cb Mon Sep 17 00:00:00 2001
From: Chris Burel 
Date: Tue, 10 Aug 2021 09:58:11 -0700
Subject: [PATCH 090/205] Replace `MCore::AlignedArray` with `AZStd::vector`

Signed-off-by: Chris Burel 
---
 Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp | 159 ++--
 Gems/EMotionFX/Code/EMotionFX/Source/Pose.h   |  18 +-
 .../Code/MCore/Source/AlignedArray.h          | 783 ------------------
 Gems/EMotionFX/Code/MCore/mcore_files.cmake   |   1 -
 4 files changed, 87 insertions(+), 874 deletions(-)
 delete mode 100644 Gems/EMotionFX/Code/MCore/Source/AlignedArray.h

diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp
index 23390bf69b..99f1474c89 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp
+++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp
@@ -24,10 +24,6 @@ namespace EMotionFX
         m_actorInstance  = nullptr;
         m_actor          = nullptr;
         m_skeleton       = nullptr;
-        m_localSpaceTransforms.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE);
-        m_modelSpaceTransforms.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE);
-        m_flags.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE);
-        m_morphWeights.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE);
     }
 
 
@@ -55,10 +51,10 @@ namespace EMotionFX
 
         // resize the buffers
         const size_t numTransforms = m_actor->GetSkeleton()->GetNumNodes();
-        m_localSpaceTransforms.ResizeFast(numTransforms);
-        m_modelSpaceTransforms.ResizeFast(numTransforms);
-        m_flags.ResizeFast(numTransforms);
-        m_morphWeights.ResizeFast(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets());
+        m_localSpaceTransforms.resize_no_construct(numTransforms);
+        m_modelSpaceTransforms.resize_no_construct(numTransforms);
+        m_flags.resize_no_construct(numTransforms);
+        m_morphWeights.resize_no_construct(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets());
 
         for (const auto& poseDataItem : m_poseDatas)
         {
@@ -79,11 +75,11 @@ namespace EMotionFX
 
         // resize the buffers
         const size_t numTransforms = m_actor->GetSkeleton()->GetNumNodes();
-        m_localSpaceTransforms.ResizeFast(numTransforms);
-        m_modelSpaceTransforms.ResizeFast(numTransforms);
+        m_localSpaceTransforms.resize_no_construct(numTransforms);
+        m_modelSpaceTransforms.resize_no_construct(numTransforms);
 
-        const size_t oldSize = m_flags.GetLength();
-        m_flags.ResizeFast(numTransforms);
+        const size_t oldSize = m_flags.size();
+        m_flags.resize_no_construct(numTransforms);
         if (oldSize < numTransforms && clearAllFlags == false)
         {
             for (size_t i = oldSize; i < numTransforms; ++i)
@@ -93,7 +89,7 @@ namespace EMotionFX
         }
 
         MorphSetup* morphSetup = m_actor->GetMorphSetup(0);
-        m_morphWeights.ResizeFast((morphSetup) ? morphSetup->GetNumMorphTargets() : 0);
+        m_morphWeights.resize_no_construct((morphSetup) ? morphSetup->GetNumMorphTargets() : 0);
 
         for (const auto& poseDataItem : m_poseDatas)
         {
@@ -111,11 +107,11 @@ namespace EMotionFX
     void Pose::SetNumTransforms(size_t numTransforms)
     {
         // resize the buffers
-        m_localSpaceTransforms.ResizeFast(numTransforms);
-        m_modelSpaceTransforms.ResizeFast(numTransforms);
+        m_localSpaceTransforms.resize_no_construct(numTransforms);
+        m_modelSpaceTransforms.resize_no_construct(numTransforms);
 
-        const size_t oldSize = m_flags.GetLength();
-        m_flags.ResizeFast(numTransforms);
+        const size_t oldSize = m_flags.size();
+        m_flags.resize_no_construct(numTransforms);
 
         for (size_t i = oldSize; i < numTransforms; ++i)
         {
@@ -127,10 +123,18 @@ namespace EMotionFX
 
     void Pose::Clear(bool clearMem)
     {
-        m_localSpaceTransforms.Clear(clearMem);
-        m_modelSpaceTransforms.Clear(clearMem);
-        m_flags.Clear(clearMem);
-        m_morphWeights.Clear(clearMem);
+        const auto clear = [clearMem](auto& vector)
+        {
+            vector.clear();
+            if (clearMem)
+            {
+                vector.shrink_to_fit();
+            }
+        };
+        clear(m_localSpaceTransforms);
+        clear(m_modelSpaceTransforms);
+        clear(m_flags);
+        clear(m_morphWeights);
 
         ClearPoseDatas();
     }
@@ -139,7 +143,7 @@ namespace EMotionFX
     // clear the pose flags
     void Pose::ClearFlags(uint8 newFlags)
     {
-        MCore::MemSet((uint8*)m_flags.GetPtr(), newFlags, sizeof(uint8) * m_flags.GetLength());
+        MCore::MemSet((uint8*)m_flags.data(), newFlags, sizeof(uint8) * m_flags.size());
     }
 
 
@@ -398,30 +402,27 @@ namespace EMotionFX
     // invalidate all local transforms
     void Pose::InvalidateAllLocalSpaceTransforms()
     {
-        const size_t numFlags = m_flags.GetLength();
-        for (size_t i = 0; i < numFlags; ++i)
+        for (uint8& flag : m_flags)
         {
-            m_flags[i] &= ~FLAG_LOCALTRANSFORMREADY;
+            flag &= ~FLAG_LOCALTRANSFORMREADY;
         }
     }
 
 
     void Pose::InvalidateAllModelSpaceTransforms()
     {
-        const size_t numFlags = m_flags.GetLength();
-        for (size_t i = 0; i < numFlags; ++i)
+        for (uint8& flag : m_flags)
         {
-            m_flags[i] &= ~FLAG_MODELTRANSFORMREADY;
+            flag &= ~FLAG_MODELTRANSFORMREADY;
         }
     }
 
 
     void Pose::InvalidateAllLocalAndModelSpaceTransforms()
     {
-        const size_t numFlags = m_flags.GetLength();
-        for (size_t i = 0; i < numFlags; ++i)
+        for (uint8& flag : m_flags)
         {
-            m_flags[i] &= ~(FLAG_LOCALTRANSFORMREADY | FLAG_MODELTRANSFORMREADY);
+            flag &= ~(FLAG_LOCALTRANSFORMREADY | FLAG_MODELTRANSFORMREADY);
         }
     }
 
@@ -469,8 +470,8 @@ namespace EMotionFX
         // make sure the number of transforms are equal
         MCORE_ASSERT(destPose);
         MCORE_ASSERT(outPose);
-        MCORE_ASSERT(m_localSpaceTransforms.GetLength() == destPose->m_localSpaceTransforms.GetLength());
-        MCORE_ASSERT(m_localSpaceTransforms.GetLength() == outPose->m_localSpaceTransforms.GetLength());
+        MCORE_ASSERT(m_localSpaceTransforms.size() == destPose->m_localSpaceTransforms.size());
+        MCORE_ASSERT(m_localSpaceTransforms.size() == outPose->m_localSpaceTransforms.size());
         MCORE_ASSERT(instance->GetIsMixing() == false);
 
         // get some motion instance properties which we use to decide the optimized blending routine
@@ -509,7 +510,7 @@ namespace EMotionFX
             }
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -533,7 +534,7 @@ namespace EMotionFX
             outPose->InvalidateAllModelSpaceTransforms();
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -550,8 +551,8 @@ namespace EMotionFX
         // make sure the number of transforms are equal
         MCORE_ASSERT(destPose);
         MCORE_ASSERT(outPose);
-        MCORE_ASSERT(m_localSpaceTransforms.GetLength() == destPose->m_localSpaceTransforms.GetLength());
-        MCORE_ASSERT(m_localSpaceTransforms.GetLength() == outPose->m_localSpaceTransforms.GetLength());
+        MCORE_ASSERT(m_localSpaceTransforms.size() == destPose->m_localSpaceTransforms.size());
+        MCORE_ASSERT(m_localSpaceTransforms.size() == outPose->m_localSpaceTransforms.size());
         MCORE_ASSERT(instance->GetIsMixing());
 
         const bool additive = (instance->GetBlendMode() == BLENDMODE_ADDITIVE);
@@ -564,7 +565,7 @@ namespace EMotionFX
         Transform result;
 
         const MotionLinkData* motionLinkData = instance->GetMotion()->GetMotionData()->FindMotionLinkData(actorInstance->GetActor());
-        AZ_Assert(motionLinkData->GetJointDataLinks().size() == m_localSpaceTransforms.GetLength(), "Expecting there to be the same amount of motion links as pose transforms.");
+        AZ_Assert(motionLinkData->GetJointDataLinks().size() == m_localSpaceTransforms.size(), "Expecting there to be the same amount of motion links as pose transforms.");
 
         // blend all transforms
         if (!additive)
@@ -589,7 +590,7 @@ namespace EMotionFX
             outPose->InvalidateAllModelSpaceTransforms();
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -619,7 +620,7 @@ namespace EMotionFX
             outPose->InvalidateAllModelSpaceTransforms();
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -647,10 +648,10 @@ namespace EMotionFX
             return;
         }
 
-        m_modelSpaceTransforms.MemCopyContentsFrom(sourcePose->m_modelSpaceTransforms);
-        m_localSpaceTransforms.MemCopyContentsFrom(sourcePose->m_localSpaceTransforms);
-        m_flags.MemCopyContentsFrom(sourcePose->m_flags);
-        m_morphWeights.MemCopyContentsFrom(sourcePose->m_morphWeights);
+        m_modelSpaceTransforms = sourcePose->m_modelSpaceTransforms;
+        m_localSpaceTransforms = sourcePose->m_localSpaceTransforms;
+        m_flags = sourcePose->m_flags;
+        m_morphWeights = sourcePose->m_morphWeights;
 
         // Deactivate pose datas from the current pose that are not in the source that we copy from.
         // This is needed in order to prevent leftover pose datas and to avoid de-/allocations.
@@ -727,11 +728,11 @@ namespace EMotionFX
                 m_localSpaceTransforms[nodeNr].Zero();
             }
 
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs);
-            for (size_t i = 0; i < numMorphs; ++i)
+            for (float& morphWeight : m_morphWeights)
             {
-                m_morphWeights[i] = 0.0f;
+                morphWeight = 0.0f;
             }
         }
         else
@@ -742,11 +743,11 @@ namespace EMotionFX
                 m_localSpaceTransforms[i].Zero();
             }
 
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs);
-            for (size_t i = 0; i < numMorphs; ++i)
+            for (float& morphWeight : m_morphWeights)
             {
-                m_morphWeights[i] = 0.0f;
+                morphWeight = 0.0f;
             }
         }
 
@@ -795,7 +796,7 @@ namespace EMotionFX
             }
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == other->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -814,7 +815,7 @@ namespace EMotionFX
             }
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == other->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -841,7 +842,7 @@ namespace EMotionFX
             }
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -865,7 +866,7 @@ namespace EMotionFX
             }
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -886,7 +887,7 @@ namespace EMotionFX
 
     Pose& Pose::MakeRelativeTo(const Pose& other)
     {
-        AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size");
+        AZ_Assert(m_localSpaceTransforms.size() == other.m_localSpaceTransforms.size(), "Poses must be of the same size");
         if (m_actorInstance)
         {
             const size_t numNodes = m_actorInstance->GetNumEnabledNodes();
@@ -899,7 +900,7 @@ namespace EMotionFX
         }
         else
         {
-            const size_t numNodes = m_localSpaceTransforms.GetLength();
+            const size_t numNodes = m_localSpaceTransforms.size();
             for (size_t i = 0; i < numNodes; ++i)
             {
                 Transform& transform = const_cast(GetLocalSpaceTransform(i));
@@ -907,7 +908,7 @@ namespace EMotionFX
             }
         }
 
-        const size_t numMorphs = m_morphWeights.GetLength();
+        const size_t numMorphs = m_morphWeights.size();
         AZ_Assert(numMorphs == other.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose.");
         for (size_t i = 0; i < numMorphs; ++i)
         {
@@ -921,7 +922,7 @@ namespace EMotionFX
 
     Pose& Pose::ApplyAdditive(const Pose& additivePose, float weight)
     {
-        AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size");
+        AZ_Assert(m_localSpaceTransforms.size() == additivePose.m_localSpaceTransforms.size(), "Poses must be of the same size");
         if (m_actorInstance)
         {
             AZ_Assert(weight > -MCore::Math::epsilon && weight < (1 + MCore::Math::epsilon), "Expected weight to be between 0..1");
@@ -939,7 +940,7 @@ namespace EMotionFX
         }
         else
         {
-            AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size");
+            AZ_Assert(m_localSpaceTransforms.size() == additivePose.m_localSpaceTransforms.size(), "Poses must be of the same size");
             if (m_actorInstance)
             {
                 const size_t numNodes = m_actorInstance->GetNumEnabledNodes();
@@ -959,7 +960,7 @@ namespace EMotionFX
             }
             else
             {
-                const size_t numNodes = m_localSpaceTransforms.GetLength();
+                const size_t numNodes = m_localSpaceTransforms.size();
                 for (size_t i = 0; i < numNodes; ++i)
                 {
                     Transform& transform = const_cast(GetLocalSpaceTransform(i));
@@ -974,7 +975,7 @@ namespace EMotionFX
                 }
             }
 
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             AZ_Assert(numMorphs == additivePose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose.");
             for (size_t i = 0; i < numMorphs; ++i)
             {
@@ -989,7 +990,7 @@ namespace EMotionFX
 
     Pose& Pose::ApplyAdditive(const Pose& additivePose)
     {
-        AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size");
+        AZ_Assert(m_localSpaceTransforms.size() == additivePose.m_localSpaceTransforms.size(), "Poses must be of the same size");
         if (m_actorInstance)
         {
             const size_t numNodes = m_actorInstance->GetNumEnabledNodes();
@@ -1009,7 +1010,7 @@ namespace EMotionFX
         }
         else
         {
-            const size_t numNodes = m_localSpaceTransforms.GetLength();
+            const size_t numNodes = m_localSpaceTransforms.size();
             for (size_t i = 0; i < numNodes; ++i)
             {
                 Transform& transform = const_cast(GetLocalSpaceTransform(i));
@@ -1024,7 +1025,7 @@ namespace EMotionFX
             }
         }
 
-        const size_t numMorphs = m_morphWeights.GetLength();
+        const size_t numMorphs = m_morphWeights.size();
         AZ_Assert(numMorphs == additivePose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose.");
         for (size_t i = 0; i < numMorphs; ++i)
         {
@@ -1038,7 +1039,7 @@ namespace EMotionFX
 
     Pose& Pose::MakeAdditive(const Pose& refPose)
     {
-        AZ_Assert(m_localSpaceTransforms.GetLength() == refPose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size");
+        AZ_Assert(m_localSpaceTransforms.size() == refPose.m_localSpaceTransforms.size(), "Poses must be of the same size");
         if (m_actorInstance)
         {
             const size_t numNodes = m_actorInstance->GetNumEnabledNodes();
@@ -1057,7 +1058,7 @@ namespace EMotionFX
         }
         else
         {
-            const size_t numNodes = m_localSpaceTransforms.GetLength();
+            const size_t numNodes = m_localSpaceTransforms.size();
             for (size_t i = 0; i < numNodes; ++i)
             {
                 Transform& transform = const_cast(GetLocalSpaceTransform(i));
@@ -1071,7 +1072,7 @@ namespace EMotionFX
             }
         }
 
-        const size_t numMorphs = m_morphWeights.GetLength();
+        const size_t numMorphs = m_morphWeights.size();
         AZ_Assert(numMorphs == refPose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose.");
         for (size_t i = 0; i < numMorphs; ++i)
         {
@@ -1101,7 +1102,7 @@ namespace EMotionFX
             }
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -1123,7 +1124,7 @@ namespace EMotionFX
             }
 
             // blend the morph weights
-            const size_t numMorphs = m_morphWeights.GetLength();
+            const size_t numMorphs = m_morphWeights.size();
             MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs);
             MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights());
             for (size_t i = 0; i < numMorphs; ++i)
@@ -1274,23 +1275,19 @@ namespace EMotionFX
     // zero all morph weights
     void Pose::ZeroMorphWeights()
     {
-        const size_t numMorphs = m_morphWeights.GetLength();
-        for (size_t m = 0; m < numMorphs; ++m)
-        {
-            m_morphWeights[m] = 0.0f;
-        }
+        AZStd::fill(begin(m_morphWeights), end(m_morphWeights), 0.0f);
     }
 
 
     void Pose::ResizeNumMorphs(size_t numMorphTargets)
     {
-        m_morphWeights.Resize(numMorphTargets);
+        m_morphWeights.resize(numMorphTargets);
     }
 
 
     Pose& Pose::PreMultiply(const Pose& other)
     {
-        AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size");
+        AZ_Assert(m_localSpaceTransforms.size() == other.m_localSpaceTransforms.size(), "Poses must be of the same size");
         if (m_actorInstance)
         {
             const size_t numNodes = m_actorInstance->GetNumEnabledNodes();
@@ -1304,7 +1301,7 @@ namespace EMotionFX
         }
         else
         {
-            const size_t numNodes = m_localSpaceTransforms.GetLength();
+            const size_t numNodes = m_localSpaceTransforms.size();
             for (size_t i = 0; i < numNodes; ++i)
             {
                 Transform& transform = const_cast(GetLocalSpaceTransform(i));
@@ -1320,7 +1317,7 @@ namespace EMotionFX
 
     Pose& Pose::Multiply(const Pose& other)
     {
-        AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size");
+        AZ_Assert(m_localSpaceTransforms.size() == other.m_localSpaceTransforms.size(), "Poses must be of the same size");
         if (m_actorInstance)
         {
             const size_t numNodes = m_actorInstance->GetNumEnabledNodes();
@@ -1333,7 +1330,7 @@ namespace EMotionFX
         }
         else
         {
-            const size_t numNodes = m_localSpaceTransforms.GetLength();
+            const size_t numNodes = m_localSpaceTransforms.size();
             for (size_t i = 0; i < numNodes; ++i)
             {
                 Transform& transform = const_cast(GetLocalSpaceTransform(i));
@@ -1348,7 +1345,7 @@ namespace EMotionFX
 
     Pose& Pose::MultiplyInverse(const Pose& other)
     {
-        AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size");
+        AZ_Assert(m_localSpaceTransforms.size() == other.m_localSpaceTransforms.size(), "Poses must be of the same size");
         if (m_actorInstance)
         {
             const size_t numNodes = m_actorInstance->GetNumEnabledNodes();
@@ -1363,7 +1360,7 @@ namespace EMotionFX
         }
         else
         {
-            const size_t numNodes = m_localSpaceTransforms.GetLength();
+            const size_t numNodes = m_localSpaceTransforms.size();
             for (size_t i = 0; i < numNodes; ++i)
             {
                 Transform& transform = const_cast(GetLocalSpaceTransform(i));
diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h
index 32c7a33bd2..b7844276be 100644
--- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h
+++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h
@@ -9,7 +9,7 @@
 #pragma once
 
 #include 
-#include 
+#include 
 #include 
 #include 
 
@@ -98,9 +98,9 @@ namespace EMotionFX
 
         Transform CalcTrajectoryTransform() const;
 
-        MCORE_INLINE const Transform* GetLocalSpaceTransforms() const                               { return m_localSpaceTransforms.GetReadPtr(); }
-        MCORE_INLINE const Transform* GetModelSpaceTransforms() const                               { return m_modelSpaceTransforms.GetReadPtr(); }
-        MCORE_INLINE size_t GetNumTransforms() const                                                { return m_localSpaceTransforms.GetLength(); }
+        MCORE_INLINE const Transform* GetLocalSpaceTransforms() const                               { return m_localSpaceTransforms.data(); }
+        MCORE_INLINE const Transform* GetModelSpaceTransforms() const                               { return m_modelSpaceTransforms.data(); }
+        MCORE_INLINE size_t GetNumTransforms() const                                                { return m_localSpaceTransforms.size(); }
         MCORE_INLINE const ActorInstance* GetActorInstance() const                                  { return m_actorInstance; }
         MCORE_INLINE const Actor* GetActor() const                                                  { return m_actor; }
         MCORE_INLINE const Skeleton* GetSkeleton() const                                            { return m_skeleton; }
@@ -116,7 +116,7 @@ namespace EMotionFX
 
         MCORE_INLINE void SetMorphWeight(size_t index, float weight)                                { m_morphWeights[index] = weight; }
         MCORE_INLINE float GetMorphWeight(size_t index) const                                       { return m_morphWeights[index]; }
-        MCORE_INLINE size_t GetNumMorphWeights() const                                              { return m_morphWeights.GetLength(); }
+        MCORE_INLINE size_t GetNumMorphWeights() const                                              { return m_morphWeights.size(); }
         void ResizeNumMorphs(size_t numMorphTargets);
 
         /**
@@ -193,11 +193,11 @@ namespace EMotionFX
         T* GetAndPreparePoseData(ActorInstance* linkToActorInstance) { return azdynamic_cast(GetAndPreparePoseData(azrtti_typeid(), linkToActorInstance)); }
 
     private:
-        mutable MCore::AlignedArray  m_localSpaceTransforms;
-        mutable MCore::AlignedArray  m_modelSpaceTransforms;
-        mutable MCore::AlignedArray      m_flags;
+        mutable AZStd::vector  m_localSpaceTransforms;
+        mutable AZStd::vector  m_modelSpaceTransforms;
+        mutable AZStd::vector      m_flags;
         AZStd::unordered_map > m_poseDatas;
-        MCore::AlignedArray              m_morphWeights;      /**< The morph target weights. */
+        AZStd::vector              m_morphWeights;      /**< The morph target weights. */
         const ActorInstance*                        m_actorInstance;
         const Actor*                                m_actor;
         const Skeleton*                             m_skeleton;
diff --git a/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h b/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h
deleted file mode 100644
index 5ffaac2e40..0000000000
--- a/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h
+++ /dev/null
@@ -1,783 +0,0 @@
-/*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
-
-#pragma once
-
-#include "StandardHeaders.h"
-#include "MCoreSystem.h"
-#include "Algorithms.h"
-#include "MemoryManager.h"
-
-
-namespace MCore
-{
-    /**
-     * Dynamic array template, using aligned memory allocations.
-     * This array template allows dynamic sizing. It also stores the memory category of the data.
-     * It can theoretically store 18446744073709551614 items (maximum size_t value - 1 for the invalid index).
-     */
-    template 
-    class AlignedArray
-    {
-    public:
-        /**
-         * The memory block ID, used inside the memory manager.
-         * This will make all arrays remain in the same memory blocks, which is more efficient in a lot of cases.
-         * However, array data can still remain in other blocks.
-         */
-        enum
-        {
-            MEMORYBLOCK_ID = 3
-        };
-
-        /**
-         * Default constructor.
-         * Initializes the array so it's empty and has no memory allocated.
-         */
-        MCORE_INLINE AlignedArray()
-            : m_data(nullptr)
-            , m_length(0)
-            , m_maxLength(0)
-            , m_memCategory(MCORE_MEMCATEGORY_ARRAY)              {}
-
-        /**
-         * Constructor which creates a given number of elements.
-         * @param elems The element data.
-         * @param num The number of elements in 'elems'.
-         * @param memCategory The memory category the array is in.
-         */
-        MCORE_INLINE explicit AlignedArray(T* elems, size_t num, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY)
-            : m_length(num)
-            , m_maxLength(AllocSize(num))
-            , m_memCategory(memCategory)
-        {
-            m_data = (T*)AlignedAllocate(m_maxLength * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE);
-            for (size_t i = 0; i < m_length; ++i)
-            {
-                Construct(i, elems[i]);
-            }
-        }
-
-        /**
-         * Constructor which initializes the length of the array on a given number.
-         * @param initSize The number of ellements to allocate space for.
-         * @param memCategory The memory category the array is in.
-         */
-        MCORE_INLINE explicit AlignedArray(size_t initSize, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY)
-            : m_data(nullptr)
-            , m_length(initSize)
-            , m_maxLength(initSize)
-            , m_memCategory(memCategory)
-        {
-            if (m_maxLength > 0)
-            {
-                m_data = (T*)AlignedAllocate(m_maxLength * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE);
-                for (size_t i = 0; i < m_length; ++i)
-                {
-                    Construct(i);
-                }
-            }
-        }
-
-        /**
-         * Copy constructor.
-         * @param other The other array to copy the data from.
-         */
-        AlignedArray(const AlignedArray& other)
-            : m_data(nullptr)
-            , m_length(0)
-            , m_maxLength(0)
-            , m_memCategory(MCORE_MEMCATEGORY_ARRAY)              { *this = other; }
-
-        /**
-         * Move constructor.
-         * @param other The array to move the data from.
-         */
-        AlignedArray(AlignedArray&& other)                                                                { m_data = other.m_data; m_length = other.m_length; m_maxLength = other.m_maxLength; m_memCategory = other.m_memCategory; other.m_data = nullptr; other.m_length = 0; other.m_maxLength = 0; }
-
-        /**
-         * Destructor. Deletes all entry data.
-         * However, if you store pointers to objects, these objects won't be deleted.
- * Example:
- *
-         * AlignedArray< Object*, 16 > data;
-         * for (size_t i=0; i<10; i++)
-         *    data.Add( new Object() );
-         * 
- * Now when the array 'data' will be destructed, it will NOT free up the memory of the integers which you allocated by hand, using new. - * In order to free up this memory, you can do this: - *
-         * for (size_t i=0; i
-         */
-        ~AlignedArray()
-        {
-            for (size_t i = 0; i < m_length; ++i)
-            {
-                Destruct(i);
-            }
-            if (m_data)
-            {
-                AlignedFree(m_data);
-            }
-        }
-
-        /**
-         * Get the memory category ID where allocations made by this array belong to.
-         * On default the memory category is 0, which means unknown.
-         * @result The memory category ID.
-         */
-        MCORE_INLINE uint16 GetMemoryCategory() const                           { return m_memCategory; }
-
-        /**
-         * Set the memory category ID, where allocations made by this array will belong to.
-         * On default, after construction of the array, the category ID is 0, which means it is unknown.
-         * @param categoryID The memory category ID where this arrays allocations belong to.
-         */
-        MCORE_INLINE void SetMemoryCategory(uint16 categoryID)                  { m_memCategory = categoryID; }
-
-        /**
-         * Get a pointer to the first element.
-         * @result A pointer to the first element.
-         */
-        MCORE_INLINE T* GetPtr()                                                { return m_data; }
-
-        /**
-         * Get a pointer to the first element.
-         * @result A pointer to the first element.
-         */
-        MCORE_INLINE T* GetPtr() const                                          { return m_data; }
-
-        /**
-         * Get a given item/element.
-         * @param pos The item/element number.
-         * @result A reference to the element.
-         */
-        MCORE_INLINE T& GetItem(size_t pos)                                     { return m_data[pos]; }
-
-        /**
-         * Get the first element.
-         * @result A reference to the first element.
-         */
-        MCORE_INLINE T& GetFirst()                                              { return m_data[0]; }
-
-        /**
-         * Get the last element.
-         * @result A reference to the last element.
-         */
-        MCORE_INLINE T& GetLast()                                               { return m_data[m_length - 1]; }
-
-        /**
-         * Get a read-only pointer to the first element.
-         * @result A read-only pointer to the first element.
-         */
-        MCORE_INLINE const T* GetReadPtr() const                                { return m_data; }
-
-        /**
-         * Get a read-only reference to a given element number.
-         * @param pos The element number.
-         * @result A read-only reference to the given element.
-         */
-        MCORE_INLINE const T& GetItem(size_t pos) const                         { return m_data[pos]; }
-
-        /**
-         * Get a read-only reference to the first element.
-         * @result A read-only reference to the first element.
-         */
-        MCORE_INLINE const T& GetFirst() const                                  { return m_data[0]; }
-
-        /**
-         * Get a read-only reference to the last element.
-         * @result A read-only reference to the last element.
-         */
-        MCORE_INLINE const T& GetLast() const                                   { return m_data[m_length - 1]; }
-
-        /**
-         * Check if the array is empty or not.
-         * @result Returns true when there are no elements in the array, otherwise false is returned.
-         */
-        MCORE_INLINE bool GetIsEmpty() const                                    { return (m_length == 0); }
-
-        /**
-         * Checks if the passed index is in the array's range.
-         * @param index The index to check.
-         * @return True if the passed index is valid, false if not.
-         */
-        MCORE_INLINE bool GetIsValidIndex(size_t index) const                   { return (index < m_length); }
-
-        /**
-         * Get the number of elements in the array.
-         * @result The number of elements in the array.
-         */
-        MCORE_INLINE size_t GetLength() const                                   { return m_length; }
-
-        /**
-         * Get the maximum number of elements. This is the number of elements there currently is space for to store.
-         * However, never use this to make for-loops to iterate through all elements. Use GetLength() instead for that.
-         * This purely has to do with pre-allocating, to reduce the number of reallocs.
-         * @result The maximum array length.
-         */
-        MCORE_INLINE size_t GetMaxLength() const                                { return m_maxLength; }
-
-        /**
-         * Calculates the memory usage used by this array.
-         * @param includeMembers Include the class members in the calculation? (default=true).
-         * @result The number of bytes allocated by this array.
-         */
-        MCORE_INLINE size_t CalcMemoryUsage(bool includeMembers = true) const
-        {
-            size_t result = m_maxLength * sizeof(T);
-            if (includeMembers)
-            {
-                result += sizeof(AlignedArray);
-            }
-            return result;
-        }
-
-        /**
-         * Set a given element to a given value.
-         * @param pos The element number.
-         * @param value The value to store at that element number.
-         */
-        MCORE_INLINE void SetElem(size_t pos, const T& value)                   { m_data[pos] = value; }
-
-        /**
-         * Add a given element to the back of the array.
-         * @param x The element to add.
-         */
-        MCORE_INLINE void Add(const T& x)                                       { Grow(++m_length); Construct(m_length - 1, x); }
-
-        /**
-         * Add a given element to the back of the array, but without pre-allocation caching.
-         * @param x The element to add.
-         */
-        MCORE_INLINE void AddExact(const T& x)                                  { GrowExact(++m_length); Construct(m_length - 1, x); }
-
-        /**
-         * Add a given array to the back of this array.
-         * @param a The array to add.
-         */
-        MCORE_INLINE void Add(const AlignedArray& a)
-        {
-            size_t l = m_length;
-            Grow(m_length + a.m_length);
-            for (size_t i = 0; i < a.GetLength(); ++i)
-            {
-                Construct(l + i, a[i]);
-            }
-        }                                                                                                                                                                                   // TODO: a.GetLength() can be precaled before loop?
-
-        /**
-         * Add an empty (default constructed) element to the back of the array.
-         */
-        MCORE_INLINE void AddEmpty()                                            { Grow(++m_length); Construct(m_length - 1); }
-
-        /**
-         * Add an empty (default constructed) element to the back of the array, but without pre-allocation caching.
-         */
-        MCORE_INLINE void AddEmptyExact()                                       { GrowExact(++m_length); Construct(m_length - 1); }
-
-        /**
-         * Remove the first array element.
-         */
-        MCORE_INLINE void RemoveFirst()
-        {
-            if (m_length > 0)
-            {
-                Remove(0);
-            }
-        }
-
-        /**
-         * Remove the last array element.
-         */
-        MCORE_INLINE void RemoveLast()
-        {
-            if (m_length > 0)
-            {
-                Destruct(--m_length);
-            }
-        }
-
-        /**
-         * Insert an empty element (default constructed) at a given position in the array.
-         * @param pos The position to create the empty element.
-         */
-        MCORE_INLINE void Insert(size_t pos)                                    { Grow(m_length + 1); MoveElements(pos + 1, pos, m_length - pos - 1); Construct(pos); }
-
-        /**
-         * Insert a given element at a given position in the array.
-         * @param pos The position to insert the empty element.
-         * @param x The element to store at this position.
-         */
-        MCORE_INLINE void Insert(size_t pos, const T& x)                        { Grow(m_length + 1); MoveElements(pos + 1, pos, m_length - pos - 1); Construct(pos, x); }
-
-        /**
-         * Remove an element at a given position.
-         * @param pos The element number to remove.
-         */
-        MCORE_INLINE void Remove(size_t pos)
-        {
-            Destruct(pos);
-            if (m_length > 1)
-            {
-                MoveElements(pos, pos + 1, m_length - pos - 1);
-            }
-            m_length--;
-        }
-
-        /**
-         * Remove a given number of elements starting at a given position in the array.
-         * @param pos The start element, so to start removing from.
-         * @param num The number of elements to remove from this position.
-         */
-        MCORE_INLINE void Remove(size_t pos, size_t num)
-        {
-            for (size_t i = pos; i < pos + num; ++i)
-            {
-                Destruct(i);
-            }
-            MoveElements(pos, pos + num, m_length - pos - num);
-            m_length -= num;
-        }
-
-        /**
-         * Remove a given element with a given value.
-         * Only the first element with the given value will be removed.
-         * @param item The item/element to remove.
-         */
-        MCORE_INLINE bool RemoveByValue(const T& item)
-        {
-            size_t index = Find(item);
-            if (index == InvalidIndex)
-            {
-                return false;
-            }
-            Remove(index);
-            return true;
-        }
-
-        /**
-         * Remove a given element in the array and place the last element in the array at the created empty position.
-         * So if we have an array with the following characters : ABCDEFG
- * And we perform a SwapRemove(2), we will remove element C and place the last element (G) at the empty created position where C was located. - * So we will get this:
- * AB.DEFG [where . is empty, after we did the SwapRemove(2)]
- * ABGDEF [this is the result. G has been moved to the empty position]. - */ - MCORE_INLINE void SwapRemove(size_t pos) - { - Destruct(pos); - if (pos != m_length - 1) - { - Construct(pos, m_data[m_length - 1]); - Destruct(m_length - 1); - } - m_length--; - } // remove element at and place the last element of the array in that position - - /** - * Swap two elements. - * @param pos1 The first element number. - * @param pos2 The second element number. - */ - MCORE_INLINE void Swap(size_t pos1, size_t pos2) - { - if (pos1 != pos2) - { - Swap(GetItem(pos1), GetItem(pos2)); - } - } - - /** - * Clear the array contents. So GetLength() will return 0 after performing this method. - * @param clearMem If set to true (default) the allocated memory will also be released. If set to false, GetMaxLength() will still return the number of elements - * which the array contained before calling the Clear() method. - */ - MCORE_INLINE void Clear(bool clearMem = true) - { - for (size_t i = 0; i < m_length; ++i) - { - Destruct(i); - } - m_length = 0; - if (clearMem) - { - this->Free(); - } - } - - /** - * Make sure the array has enough space to store a given number of elements. - * @param newLength The number of elements we want to make sure that will fit in the array. - */ - MCORE_INLINE void AssureSize(size_t newLength) - { - if (m_length >= newLength) - { - return; - } - size_t oldLen = m_length; - Grow(newLength); - for (size_t i = oldLen; i < newLength; ++i) - { - Construct(i); - } - } - - /** - * Make sure this array has enough allocated storage to grow to a given number of elements elements without having to realloc. - * @param minLength The minimum length the array should have (actually the minimum maxLength, because this has no influence on what GetLength() will return). - */ - MCORE_INLINE void Reserve(size_t minLength) - { - if (m_maxLength < minLength) - { - Realloc(minLength); - } - } - - /** - * Make the array as small as possible. So remove all extra pre-allocated data, so that the array consumes the least possible amount of memory. - */ - MCORE_INLINE void Shrink() - { - if (m_length == m_maxLength) - { - return; - } - MCORE_ASSERT(m_maxLength >= m_length); - Realloc(m_length); - } - - /** - * Check if the array contains a given element. - * @param x The element to check. - * @result Returns true when the array contains the element, otherwise false is returned. - */ - MCORE_INLINE bool Contains(const T& x) const { return (Find(x) != InvalidIndex); } - - /** - * Find the position of a given element. - * @param x The element to find. - * @result Returns the index in the array, ranging from [0 to GetLength()-1] when found, otherwise InvalidIndex is returned. - */ - MCORE_INLINE size_t Find(const T& x) const - { - for (size_t i = 0; i < m_length; ++i) - { - if (m_data[i] == x) - { - return i; - } - } - return InvalidIndex; - } - - /** - * Copy the contents of another array into this one using a direct memory copy. - * This does not call copy constructors of the objects, but just copies the raw memory data. - * This resizes this array to be the exact length of the array we will copy the data from. - * @param other The array to copy the data from. - */ - MCORE_INLINE void MemCopyContentsFrom(const AlignedArray& other) { Resize(other.GetLength()); MemCopy((uint8*)m_data, (uint8*)other.m_data, sizeof(T) * other.m_length); } - - // sort function and standard sort function - typedef int32 (MCORE_CDECL * CmpFunc)(const T& itemA, const T& itemB); - static int32 MCORE_CDECL StdCmp(const T& itemA, const T& itemB) - { - if (itemA < itemB) - { - return -1; - } - else if (itemA == itemB) - { - return 0; - } - else - { - return 1; - } - } - static int32 MCORE_CDECL StdPtrObjCmp(const T& itemA, const T& itemB) - { - if (*itemA < *itemB) - { - return -1; - } - else if (*itemA == *itemB) - { - return 0; - } - else - { - return 1; - } - } - - /** - * Sort the complete array using a given sort function. - * @param cmp The sort function to use. - */ - MCORE_INLINE void Sort(CmpFunc cmp) { InnerSort(0, m_length - 1, cmp); } - - /** - * Sort a given part of the array using a given sort function. - * The default parameters are set so that it will sort the compelete array with a default compare function (which uses the < and > operators). - * The method will sort all elements between the given 'first' and 'last' element (first and last are also included in the sort). - * @param first The first element to start sorting. - * @param last The last element to sort (when set to InvalidIndex, GetLength()-1 will be used). - * @param cmp The compare function. - */ - MCORE_INLINE void Sort(size_t first = 0, size_t last = InvalidIndex, CmpFunc cmp = StdCmp) - { - if (last == InvalidIndex) - { - last = m_length - 1; - } - InnerSort(first, last, cmp); - } - - /** - * Performs a sort on a given part of the array. - * @param first The first element to start the sorting at. - * @param last The last element to end the sorting. - * @param cmp The compare function. - */ - MCORE_INLINE void InnerSort(int32 first, int32 last, CmpFunc cmp) - { - if (first >= last) - { - return; - } - int32 split = Partition(first, last, cmp); - InnerSort(first, split - 1, cmp); - InnerSort(split + 1, last, cmp); - } - - // resize in a fast way that doesn't call constructors or destructors - void ResizeFast(size_t newLength) - { - if (m_length == newLength) - { - return; - } - - if (newLength > m_length) - { - GrowExact(newLength); - } - - m_length = newLength; - } - - /** - * Resize the array to a given size. - * This does not mean an actual realloc will be made. This will only happen when the new length is bigger than the maxLength of the array. - * @param newLength The new length the array should be. - */ - void Resize(size_t newLength) - { - if (m_length == newLength) - { - return; - } - - // check for growing or shrinking array - if (newLength > m_length) - { - // growing array, construct empty elements at end of array - const size_t oldLen = m_length; - GrowExact(newLength); - for (size_t i = oldLen; i < newLength; ++i) - { - Construct(i); - } - } - else - { - // shrinking array, destruct elements at end of array - for (size_t i = newLength; i < m_length; ++i) - { - Destruct(i); - } - - m_length = newLength; - } - } - - /** - * Move "numElements" elements starting from the source index, to the dest index. - * Please note thate the array has to be large enough. You can't move data past the end of the array. - * @param destIndex The destination index. - * @param sourceIndex The source index, where the source elements start. - * @param numElements The number of elements to move. - */ - MCORE_INLINE void MoveElements(size_t destIndex, size_t sourceIndex, size_t numElements) - { - if (numElements > 0) - { - MemMove(m_data + destIndex, m_data + sourceIndex, numElements * sizeof(T)); - } - } - - // operators - bool operator==(const AlignedArray& other) const - { - if (m_length != other.m_length) - { - return false; - } - for (size_t i = 0; i < m_length; ++i) - { - if (m_data[i] != other.m_data[i]) - { - return false; - } - } - return true; - } - AlignedArray& operator= (const AlignedArray& other) - { - if (&other != this) - { - Clear(false); - m_memCategory = other.m_memCategory; - Grow(other.m_length); - for (size_t i = 0; i < m_length; ++i) - { - Construct(i, other.m_data[i]); - } - } - return *this; - } - AlignedArray& operator= (AlignedArray&& other) - { - MCORE_ASSERT(&other != this); - if (m_data) - { - AlignedFree(m_data); - } - m_data = other.m_data; - m_memCategory = other.m_memCategory; - m_length = other.m_length; - m_maxLength = other.m_maxLength; - other.m_data = nullptr; - other.m_length = 0; - other.m_maxLength = 0; - return *this; - } - AlignedArray& operator+=(const T& other) { Add(other); return *this; } - AlignedArray& operator+=(const AlignedArray& other) { Add(other); return *this; } - MCORE_INLINE T& operator[](size_t index) { MCORE_ASSERT(index < m_length); return m_data[index]; } - MCORE_INLINE const T& operator[](size_t index) const { MCORE_ASSERT(index < m_length); return m_data[index]; } - - private: - T* m_data; /**< The element data. */ - size_t m_length; /**< The number of used elements in the array. */ - size_t m_maxLength; /**< The number of elements that we have allocated memory for. */ - uint16 m_memCategory; /**< The memory category ID. */ - - // private functions - MCORE_INLINE void Grow(size_t newLength) - { - m_length = newLength; - if (m_maxLength >= newLength) - { - return; - } - Realloc(AllocSize(newLength)); - } - MCORE_INLINE void GrowExact(size_t newLength) - { - m_length = newLength; - if (m_maxLength < newLength) - { - Realloc(newLength); - } - } - MCORE_INLINE size_t AllocSize(size_t num) { return 1 + num /*+num/8*/; } - MCORE_INLINE void Alloc(size_t num) { m_data = (T*)AlignedAllocate(num * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } - MCORE_INLINE void Realloc(size_t newSize) - { - if (newSize == 0) - { - this->Free(); - return; - } - if (m_data) - { - m_data = (T*)AlignedRealloc(m_data, newSize * sizeof(T), m_maxLength * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - } - else - { - m_data = (T*)AlignedAllocate(newSize * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - } - - m_maxLength = newSize; - } - void Free() - { - m_length = 0; - m_maxLength = 0; - if (m_data) - { - AlignedFree(m_data); - m_data = nullptr; - } - } - MCORE_INLINE void Construct(size_t index, const T& original) { ::new(m_data + index)T(original); } // copy-construct an element at which is a copy of - MCORE_INLINE void Construct(size_t index) { ::new(m_data + index)T; } // construct an element at place - MCORE_INLINE void Destruct(size_t index) - { - #if (MCORE_COMPILER == MCORE_COMPILER_MSVC) - MCORE_UNUSED(index); // work around an MSVC compiler bug, where it triggers a warning that parameter 'index' is unused - #endif - (m_data + index)->~T(); - } - - // partition part of array (for sorting) - int32 Partition(int32 left, int32 right, CmpFunc cmp) - { - ::MCore::Swap(m_data[left], m_data[ (left + right) >> 1 ]); - - T& target = m_data[right]; - int32 i = left - 1; - int32 j = right; - - bool neverQuit = true; // workaround to disable a "warning C4127: conditional expression is constant" - while (neverQuit) - { - while (i < j) - { - if (cmp(m_data[++i], target) >= 0) - { - break; - } - } - while (j > i) - { - if (cmp(m_data[--j], target) <= 0) - { - break; - } - } - if (i >= j) - { - break; - } - ::MCore::Swap(m_data[i], m_data[j]); - } - - ::MCore::Swap(m_data[i], m_data[right]); - return i; - } - }; -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/mcore_files.cmake b/Gems/EMotionFX/Code/MCore/mcore_files.cmake index 47b35e004b..bb9c0f4447 100644 --- a/Gems/EMotionFX/Code/MCore/mcore_files.cmake +++ b/Gems/EMotionFX/Code/MCore/mcore_files.cmake @@ -11,7 +11,6 @@ set(FILES Source/Algorithms.cpp Source/Algorithms.h Source/Algorithms.inl - Source/AlignedArray.h Source/Array2D.h Source/Array2D.inl Source/Attribute.cpp From a9cd126026e2a27ed531b097717cdb8f3a0d10e3 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 12:30:04 -0700 Subject: [PATCH 091/205] Adding PLATFORM_H_SECTION_15 back since it is used in restricted Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/platform.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 9ff461543f..88d06c9b1e 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -24,6 +24,7 @@ #define PLATFORM_H_SECTION_12 12 #define PLATFORM_H_SECTION_13 13 #define PLATFORM_H_SECTION_14 14 +#define PLATFORM_H_SECTION_15 15 #endif #if (defined(LINUX) && !defined(ANDROID)) || defined(APPLE) @@ -414,4 +415,9 @@ threadID CryGetCurrentThreadId(); #endif #endif +#if defined(AZ_RESTRICTED_PLATFORM) + #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_15 + #include AZ_RESTRICTED_FILE(platform_h) +#endif + void InitRootDir(char szExeFileName[] = nullptr, uint nExeSize = 0, char szExeRootName[] = nullptr, uint nRootSize = 0); From 5472d6768e8a3ceb81f901251858bb58600439d0 Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Tue, 10 Aug 2021 12:48:26 -0700 Subject: [PATCH 092/205] Minor improvements Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- .../RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h | 6 +++--- .../RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h index cdbf983561..2c884ceedf 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h @@ -38,12 +38,12 @@ namespace AZ void SetDrawListTag(Name drawListName); - void SetPipelineStateDataIndex(u32 index); + void SetPipelineStateDataIndex(uint32_t index); //! Expose shader resource group. ShaderResourceGroup* GetShaderResourceGroup(); - u32 GetDrawItemCount(); + uint32_t GetDrawItemCount(); protected: explicit RasterPass(const PassDescriptor& descriptor); @@ -78,7 +78,7 @@ namespace AZ RHI::Viewport m_viewportState; bool m_overrideScissorSate = false; bool m_overrideViewportState = false; - u32 m_drawItemCount = 0; + uint32_t m_drawItemCount = 0; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp index 4da5560908..ce02e1c570 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp @@ -104,7 +104,7 @@ namespace AZ m_flags.m_hasDrawListTag = true; } - void RasterPass::SetPipelineStateDataIndex(u32 index) + void RasterPass::SetPipelineStateDataIndex(uint32_t index) { m_pipelineStateDataIndex.m_index = index; } @@ -114,7 +114,7 @@ namespace AZ return m_shaderResourceGroup.get(); } - u32 RasterPass::GetDrawItemCount() + uint32_t RasterPass::GetDrawItemCount() { return m_drawItemCount; } @@ -172,7 +172,7 @@ namespace AZ if (viewDrawList.size() > 0 && drawLists.size() == 0) { m_drawListView = viewDrawList; - m_drawItemCount += (u32)viewDrawList.size(); + m_drawItemCount += static_cast(viewDrawList.size()); PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); return; } @@ -183,7 +183,7 @@ namespace AZ // combine draw items from mutiple draw lists to one draw list and sort it. for (auto drawList : drawLists) { - m_drawItemCount += (u32)drawList.size(); + m_drawItemCount += static_cast(drawList.size()); } PassSystemInterface::Get()->IncrementFrameDrawItemCount(m_drawItemCount); m_combinedDrawList.resize(m_drawItemCount); @@ -211,7 +211,7 @@ namespace AZ void RasterPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) { RenderPass::SetupFrameGraphDependencies(frameGraph); - frameGraph.SetEstimatedItemCount(static_cast(m_drawListView.size())); + frameGraph.SetEstimatedItemCount(static_cast(m_drawListView.size())); } void RasterPass::CompileResources(const RHI::FrameGraphCompileContext& context) From c229191fad3a1595658502e9ee767764305891a9 Mon Sep 17 00:00:00 2001 From: evanchia Date: Tue, 10 Aug 2021 13:09:42 -0700 Subject: [PATCH 093/205] removing unused output for aztestrunner Signed-off-by: evanchia --- Code/Tools/AzTestRunner/src/main.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Code/Tools/AzTestRunner/src/main.cpp b/Code/Tools/AzTestRunner/src/main.cpp index d9ee727447..231e4e8059 100644 --- a/Code/Tools/AzTestRunner/src/main.cpp +++ b/Code/Tools/AzTestRunner/src/main.cpp @@ -120,12 +120,6 @@ namespace AzTestRunner { const char* cwd = AzTestRunner::get_current_working_directory(); std::cout << "cwd = " << cwd << std::endl; - - for (int i = 0; i < argc; i++) - { - std::cout << "arg[" << i << "] " << argv[i] << std::endl; - } - std::cout << "LIB: " << lib << std::endl; } From 4450eb4e224c1352addf25db767a61ef3a812e39 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 13:24:20 -0700 Subject: [PATCH 094/205] fix new warning hit Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp index 4f1aa5b42b..a0d0e62abd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp @@ -330,7 +330,7 @@ namespace EMStudio const size_t numMorphTargets = m_morphSetup->GetNumMorphTargets(); const uint32 numPhonemeSets = m_morphTarget->GetNumAvailablePhonemeSets(); int insertPosition = 0; - for (int i = 1; i < numPhonemeSets; ++i) + for (uint32 i = 1; i < numPhonemeSets; ++i) { // check if another morph target already has this phoneme set. bool phonemeSetFound = false; From 181998f8107f8776c3bc137732059f0a3b67639e Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 14:05:14 -0700 Subject: [PATCH 095/205] Fixes a nightly build and a CMake warning (#2941) * Addressing CMake warning and removing timeouts that are the same as the default Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * missed this one Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * Making it an error so developers stops putting timeouts longer than the allowed one since it causes AR issues Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * fixing warning from the nightly build Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * disabling test that is triggering a timeout Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Gem/PythonTests/Blast/CMakeLists.txt | 1 - .../Gem/PythonTests/NvCloth/CMakeLists.txt | 1 - .../PythonAssetBuilder/CMakeLists.txt | 1 - .../Gem/PythonTests/WhiteBox/CMakeLists.txt | 1 - .../asset_processor_tests/CMakeLists.txt | 24 +++++++++---------- .../Gem/PythonTests/editor/CMakeLists.txt | 4 ---- .../PythonTests/largeworlds/CMakeLists.txt | 11 --------- .../Gem/PythonTests/physics/CMakeLists.txt | 3 --- .../Gem/PythonTests/prefab/CMakeLists.txt | 1 - .../Gem/PythonTests/scripting/CMakeLists.txt | 2 -- .../Gem/PythonTests/smoke/CMakeLists.txt | 1 - Gems/PhysX/Code/CMakeLists.txt | 1 - cmake/LYTestWrappers.cmake | 2 +- 13 files changed, 12 insertions(+), 41 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt index 7048a6bd46..172eded09a 100644 --- a/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE main TEST_SERIAL TRUE PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Active.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt index a39cdf04cf..3913041f88 100644 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt @@ -13,7 +13,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_REQUIRES gpu TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Active.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt index 9b6542b3e3..905470e08f 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt index b5fcfcc44c..1c7a02862d 100644 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE main TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Active.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt index 0170d73af0..3d7a9204e2 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt @@ -92,17 +92,17 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AssetProcessor ) - ly_add_pytest( - NAME AssetPipelineTests.AssetBundler - PATH ${CMAKE_CURRENT_LIST_DIR}/asset_bundler_batch_tests.py - EXCLUDE_TEST_RUN_TARGET_FROM_IDE - TEST_SERIAL - TIMEOUT 2400 - TEST_SUITE periodic - RUNTIME_DEPENDENCIES - AZ::AssetProcessor - AZ::AssetBundlerBatch - ) + # Issue #3017 + #ly_add_pytest( + # NAME AssetPipelineTests.AssetBundler + # PATH ${CMAKE_CURRENT_LIST_DIR}/asset_bundler_batch_tests.py + # EXCLUDE_TEST_RUN_TARGET_FROM_IDE + # TEST_SERIAL + # TEST_SUITE periodic + # RUNTIME_DEPENDENCIES + # AZ::AssetProcessor + # AZ::AssetBundlerBatch + #) ly_add_pytest( NAME AssetPipelineTests.AssetBundler_SandBox @@ -111,7 +111,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) PYTEST_MARKS "SUITE_sandbox" # run only sandbox tests in this file EXCLUDE_TEST_RUN_TARGET_FROM_IDE TEST_SERIAL - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor AZ::AssetBundlerBatch @@ -133,7 +132,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) PATH ${CMAKE_CURRENT_LIST_DIR}/missing_dependency_tests.py EXCLUDE_TEST_RUN_TARGET_FROM_IDE TEST_SERIAL - TIMEOUT 1500 TEST_SUITE periodic RUNTIME_DEPENDENCIES AZ::AssetProcessorBatch diff --git a/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt index afde0a0d94..fa35bb25c6 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt @@ -13,7 +13,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_main and not REQUIRES_gpu" - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -28,7 +27,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_periodic and not REQUIRES_gpu" - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -44,7 +42,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_REQUIRES gpu PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_main and REQUIRES_gpu" - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -59,7 +56,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_sandbox" - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt index 351ca19031..043485d869 100644 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt @@ -16,7 +16,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE main PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "not SUITE_sandbox and not SUITE_periodic and not SUITE_benchmark" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -33,7 +32,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE sandbox PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_sandbox" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -49,7 +47,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_filter" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -64,7 +61,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_modifier" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -79,7 +75,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_regression" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -94,7 +89,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_area" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -109,7 +103,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_misc" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -124,7 +117,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/dyn_veg PYTEST_MARKS "SUITE_periodic and dynveg_surfacetagemitter" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -140,7 +132,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE main PATH ${CMAKE_CURRENT_LIST_DIR}/landscape_canvas PYTEST_MARKS "not SUITE_sandbox and not SUITE_periodic and not SUITE_benchmark" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -155,7 +146,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/landscape_canvas PYTEST_MARKS "SUITE_periodic" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -170,7 +160,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ TEST_SERIAL TEST_SUITE periodic PATH ${CMAKE_CURRENT_LIST_DIR}/gradient_signal - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor diff --git a/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt index 248bf3fdc5..eb37db1943 100644 --- a/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE main TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -25,7 +24,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Periodic.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -38,7 +36,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE sandbox TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Sandbox.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt index 1d9c54fa40..48c24d1ebf 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt @@ -13,7 +13,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE main TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt index 80b6e9a54e..25988216b2 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt @@ -12,7 +12,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Periodic.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor @@ -25,7 +24,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE sandbox TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Sandbox.py - TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 2c1d03b5a2..3fc4f3db0e 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -18,7 +18,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR} PYTEST_MARKS "SUITE_smoke" - TIMEOUT 1500 RUNTIME_DEPENDENCIES AZ::AssetProcessor AZ::PythonBindingsExample diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index a69019249f..80e8bee8e3 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -186,7 +186,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_googlebenchmark( NAME Gem::PhysX.Benchmarks TARGET Gem::PhysX.Tests - TIMEOUT 1500 #25mins ) list(APPEND testTargets PhysX.Tests) diff --git a/cmake/LYTestWrappers.cmake b/cmake/LYTestWrappers.cmake index efb19a20dd..8e71cb3db1 100644 --- a/cmake/LYTestWrappers.cmake +++ b/cmake/LYTestWrappers.cmake @@ -114,7 +114,7 @@ function(ly_add_test) if(NOT ly_add_test_TIMEOUT) set(ly_add_test_TIMEOUT ${LY_TEST_DEFAULT_TIMEOUT}) elseif(ly_add_test_TIMEOUT GREATER LY_TEST_DEFAULT_TIMEOUT) - message(WARNING "TIMEOUT for test ${ly_add_test_NAME} set at ${ly_add_test_TIMEOUT} seconds which is longer than the default of ${LY_TEST_DEFAULT_TIMEOUT}. Allowing a single module to run exceedingly long creates problems in a CI pipeline.") + message(FATAL_ERROR "TIMEOUT for test ${ly_add_test_NAME} set at ${ly_add_test_TIMEOUT} seconds which is longer than the default of ${LY_TEST_DEFAULT_TIMEOUT}. Allowing a single module to run exceedingly long creates problems in a CI pipeline.") endif() if(NOT ly_add_test_TEST_COMMAND) From a70a106fd2e2f5b7b83739ab37355b06689afe33 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 10 Aug 2021 14:48:33 -0700 Subject: [PATCH 096/205] Test code to add merge detection on Settings Registry keys Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../AzCore/Component/ComponentApplication.cpp | 1 + .../AzCore/AzCore/Settings/SettingsRegistry.h | 44 ++++++++ .../AzCore/Settings/SettingsRegistryImpl.cpp | 49 +++++++++ .../AzCore/Settings/SettingsRegistryImpl.h | 9 ++ .../Settings/EditorSettingsOriginTracker.cpp | 103 ++++++++++++++++++ .../Settings/EditorSettingsOriginTracker.h | 39 +++++++ .../aztoolsframework_files.cmake | 2 + 7 files changed, 247 insertions(+) create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index c68fce6f4d..7b1060a10f 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -728,6 +728,7 @@ namespace AZ DestroyReflectionManager(); static_cast(m_settingsRegistry.get())->ClearNotifiers(); + static_cast(m_settingsRegistry.get())->ClearMergeEvents(); // Uninit and unload any dynamic modules. m_moduleManager->UnloadModules(); diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h index 3bcf0ae89b..e27e4452ee 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h @@ -123,6 +123,36 @@ namespace AZ using NotifyEvent = AZ::Event; using NotifyEventHandler = typename NotifyEvent::Handler; + using PreMergeEventCallback = AZStd::function; + using PostMergeEventCallback = AZStd::function; + using PreMergeEvent = AZ::Event; + using PostMergeEvent = AZ::Event; + using PreMergeEventHandler = typename PreMergeEvent::Handler; + using PostMergeEventHandler = typename PostMergeEvent::Handler; + + struct ScopedMergeEvent + { + ScopedMergeEvent( + PreMergeEvent& preMergeEvent, PostMergeEvent& postMergeEvent, AZStd::string_view filePath, AZStd::string_view rootKey) + : m_preMergeEvent{ preMergeEvent } + , m_postMergeEvent{ postMergeEvent } + , m_filePath{ filePath } + , m_rootKey{ rootKey } + { + preMergeEvent.Signal(m_filePath, m_rootKey); + } + + ~ScopedMergeEvent() + { + m_postMergeEvent.Signal(m_filePath, m_rootKey); + } + + PreMergeEvent& m_preMergeEvent; + PostMergeEvent& m_postMergeEvent; + AZStd::string_view m_filePath; + AZStd::string_view m_rootKey; + }; + using VisitorCallback = AZStd::function; //! Base class for the visitor class during traversal over the Settings Registry. The type-agnostic function is always @@ -169,6 +199,20 @@ namespace AZ //! @callback The function to call when an entry gets a new/updated value. [[nodiscard]] virtual NotifyEventHandler RegisterNotifier(NotifyCallback&& callback) = 0; + //! Register a callback that will be called before an entry is merged. + //! @callback The function to call when an entry gets a new/updated value. + [[nodiscard]] virtual PreMergeEventHandler RegisterPreMergeEvent(const PreMergeEventCallback& callback) = 0; + //! Register a callback that will be called before an entry is merged. + //! @callback The function to call when an entry gets a new/updated value. + [[nodiscard]] virtual PreMergeEventHandler RegisterPreMergeEvent (PreMergeEventCallback&& callback) = 0; + + //! Register a callback that will be called after an entry is merged. + //! @callback The function to call when an entry gets a new/updated value. + [[nodiscard]] virtual PostMergeEventHandler RegisterPostMergeEvent(const PostMergeEventCallback& callback) = 0; + //! Register a callback that will be called after an entry is merged. + //! @callback The function to call when an entry gets a new/updated value. + [[nodiscard]] virtual PostMergeEventHandler RegisterPostMergeEvent (PostMergeEventCallback&& callback) = 0; + //! Gets the boolean value at the provided path. //! @param result The target to write the result to. //! @param path The path to the value. diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp index 0882e1b7f2..4a7b4183f3 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp @@ -229,6 +229,53 @@ namespace AZ m_notifiers.DisconnectAllHandlers(); } + auto SettingsRegistryImpl::RegisterPreMergeEvent(const PreMergeEventCallback& callback) -> PreMergeEventHandler + { + PreMergeEventHandler preMergeHandler{ callback }; + { + AZStd::scoped_lock lock(m_settingMutex); + preMergeHandler.Connect(m_preMergeEvent); + } + return preMergeHandler; + } + + auto SettingsRegistryImpl::RegisterPreMergeEvent(PreMergeEventCallback&& callback) -> PreMergeEventHandler + { + PreMergeEventHandler preMergeHandler{ AZStd::move(callback) }; + { + AZStd::scoped_lock lock(m_settingMutex); + preMergeHandler.Connect(m_preMergeEvent); + } + return preMergeHandler; + } + + auto SettingsRegistryImpl::RegisterPostMergeEvent(const PostMergeEventCallback& callback) -> PostMergeEventHandler + { + PostMergeEventHandler postMergeHandler{ callback }; + { + AZStd::scoped_lock lock(m_settingMutex); + postMergeHandler.Connect(m_postMergeEvent); + } + return postMergeHandler; + } + + auto SettingsRegistryImpl::RegisterPostMergeEvent(PostMergeEventCallback&& callback) -> PostMergeEventHandler + { + PostMergeEventHandler postMergeHandler{ AZStd::move(callback) }; + { + AZStd::scoped_lock lock(m_settingMutex); + postMergeHandler.Connect(m_postMergeEvent); + } + return postMergeHandler; + } + + void SettingsRegistryImpl::ClearMergeEvents() + { + AZStd::scoped_lock lock(m_settingMutex); + m_preMergeEvent.DisconnectAllHandlers(); + m_postMergeEvent.DisconnectAllHandlers(); + } + SettingsRegistryInterface::Type SettingsRegistryImpl::GetType(AZStd::string_view path) const { if (path.empty()) @@ -1115,6 +1162,8 @@ namespace AZ return false; } + ScopedMergeEvent(m_preMergeEvent, m_postMergeEvent, path, rootKey); + JsonSerializationResult::ResultCode mergeResult(JsonSerializationResult::Tasks::Merge); if (rootKey.empty()) { diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h index 41a628cf22..babcafe701 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h @@ -48,6 +48,12 @@ namespace AZ [[nodiscard]] NotifyEventHandler RegisterNotifier(NotifyCallback&& callback) override; void ClearNotifiers(); + [[nodiscard]] PreMergeEventHandler RegisterPreMergeEvent(const PreMergeEventCallback& callback) override; + [[nodiscard]] PreMergeEventHandler RegisterPreMergeEvent(PreMergeEventCallback&& callback) override; + [[nodiscard]] PostMergeEventHandler RegisterPostMergeEvent(const PostMergeEventCallback& callback) override; + [[nodiscard]] PostMergeEventHandler RegisterPostMergeEvent(PostMergeEventCallback&& callback) override; + void ClearMergeEvents(); + bool Get(bool& result, AZStd::string_view path) const override; bool Get(s64& result, AZStd::string_view path) const override; bool Get(u64& result, AZStd::string_view path) const override; @@ -103,6 +109,9 @@ namespace AZ mutable AZStd::recursive_mutex m_settingMutex; NotifyEvent m_notifiers; + PreMergeEvent m_preMergeEvent; + PostMergeEvent m_postMergeEvent; + rapidjson::Document m_settings; JsonSerializerSettings m_serializationSettings; JsonDeserializerSettings m_deserializationSettings; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp new file mode 100644 index 0000000000..13a0610f5c --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +#include +#include + +namespace AzToolsFramework +{ + EditorPreferencesSettingsOriginTracker::SettingsNotificationHandler::SettingsNotificationHandler( + AZ::SettingsRegistryInterface& registry) + : m_settingsRegistry(registry) + { + AZ::JsonApplyPatchSettings applyPatchSettings; + m_settingsRegistry.GetApplyPatchSettings(applyPatchSettings); + // Wrap any existing callbacks into the reporting callback, so that both this struct + // reporting callbacks and the existing callbacks can be invoked + m_prevReportingCallback = applyPatchSettings.m_reporting; + applyPatchSettings.m_reporting = [this]( + AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, + AZStd::string_view path) -> AZ::JsonSerializationResult::ResultCode + { + m_prevReportingCallback(message, result, path); + (*this)(message, result, path); + return result; + }; + m_settingsRegistry.SetApplyPatchSettings(applyPatchSettings); + } + + EditorPreferencesSettingsOriginTracker::SettingsNotificationHandler::~SettingsNotificationHandler() + { + // Restore previous reporting callback + AZ::JsonApplyPatchSettings applyPatchSettings; + m_settingsRegistry.GetApplyPatchSettings(applyPatchSettings); + applyPatchSettings.m_reporting = m_prevReportingCallback; + m_settingsRegistry.SetApplyPatchSettings(applyPatchSettings); + } + + // Use the Json Serialization Issue Callback system + // to determine when a merge option modifies a value + AZ::JsonSerializationResult::ResultCode EditorPreferencesSettingsOriginTracker::SettingsNotificationHandler::operator()( + AZStd::string_view /*message*/, AZ::JsonSerializationResult::ResultCode result, AZStd::string_view path) + { + using FixedValueString = AZ::SettingsRegistryInterface::FixedValueString; + + AZ::IO::PathView preferencesRootKey{ "/Amazon/Preferences", AZ::IO::PosixPathSeparator }; + AZ::IO::PathView inputKey{ path, AZ::IO::PosixPathSeparator }; + + // Delegate to the Notifier Handler callable below + if (result.GetTask() == AZ::JsonSerializationResult::Tasks::Merge && + result.GetProcessing() == AZ::JsonSerializationResult::Processing::Completed && inputKey.IsRelativeTo(preferencesRootKey)) + { + if (auto type = m_settingsRegistry.GetType(path); type != AZ::SettingsRegistryInterface::Type::NoType) + { + operator()(path, type); + } + } + + return result; + } + + void EditorPreferencesSettingsOriginTracker::SettingsNotificationHandler::operator()( + AZStd::string_view path, AZ::SettingsRegistryInterface::Type /*type*/) + { + constexpr AZ::IO::PathView preferencesRootKey{ "/Amazon/Preferences", AZ::IO::PosixPathSeparator }; + AZ::IO::PathView inputKey{ path, AZ::IO::PosixPathSeparator }; + if (inputKey.IsRelativeTo(preferencesRootKey)) + { + // Do stuff with key + } + } + + EditorPreferencesSettingsOriginTracker::EditorPreferencesSettingsOriginTracker(AZ::SettingsRegistryInterface& registry) + : m_settingsRegistry(registry) + { + auto PreMergeEvent = [this](AZStd::string_view filePath, AZStd::string_view /*rootKey*/) + { + AZ::IO::FixedMaxPath editorPreferencesPath = AZ::Utils::GetProjectPath(); + editorPreferencesPath = editorPreferencesPath / "user" / "Registry" / "editorpreferences.setreg"; + + if (AZ::IO::PathView(filePath) == editorPreferencesPath) + { + m_notifyHandler = m_settingsRegistry.RegisterNotifier(SettingsNotificationHandler(m_settingsRegistry)); + } + }; + + auto PostMergeEvent = [this](AZStd::string_view /*filePath*/, AZStd::string_view /*rootKey*/) + { + // Clear the notification handler so that it goes out of scope + // and this tracker instance no handles settings updates + m_notifyHandler = {}; + }; + + m_preMergeEventHandler = m_settingsRegistry.RegisterPreMergeEvent(PreMergeEvent); + m_postMergeEventHandler = m_settingsRegistry.RegisterPostMergeEvent(PostMergeEvent); + } +} diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h new file mode 100644 index 0000000000..63249a8ecd --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +namespace AzToolsFramework +{ + struct EditorPreferencesSettingsOriginTracker + { + explicit EditorPreferencesSettingsOriginTracker(AZ::SettingsRegistryInterface& registry); + + struct SettingsNotificationHandler + { + SettingsNotificationHandler(AZ::SettingsRegistryInterface& registry); + ~SettingsNotificationHandler(); + + AZ::JsonSerializationResult::ResultCode operator()( + AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, AZStd::string_view path); + void operator()(AZStd::string_view path, AZ::SettingsRegistryInterface::Type type); + + private: + AZ::SettingsRegistryInterface& m_settingsRegistry; + AZ::JsonSerializationResult::JsonIssueCallback m_prevReportingCallback; + }; + + private: + AZ::SettingsRegistryInterface& m_settingsRegistry; + AZ::SettingsRegistryInterface::PreMergeEventHandler m_preMergeEventHandler; + AZ::SettingsRegistryInterface::PostMergeEventHandler m_postMergeEventHandler; + AZ::SettingsRegistryInterface::NotifyEventHandler m_notifyHandler; + }; +} // namespace AZ diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 53173f83af..6e7446d74d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -113,6 +113,8 @@ set(FILES Component/EditorLevelComponentAPIComponent.h Editor/EditorContextMenuBus.h Editor/EditorSettingsAPIBus.h + Editor/Settings/EditorSettingsOriginTracker.cpp + Editor/Settings/EditorSettingsOriginTracker.h Entity/EditorEntityStartStatus.h Entity/EditorEntityAPIBus.h Entity/EditorEntityContextComponent.cpp From 6f6b88ec2f785ff3ef8c2e56b6c4134df54d345a Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 10 Aug 2021 15:27:01 -0700 Subject: [PATCH 097/205] Rename EditorSettingsOriginTracker Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../Editor/Settings/EditorSettingsOriginTracker.cpp | 10 +++++----- .../Editor/Settings/EditorSettingsOriginTracker.h | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp index 13a0610f5c..bdeb4e41b4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp @@ -13,7 +13,7 @@ namespace AzToolsFramework { - EditorPreferencesSettingsOriginTracker::SettingsNotificationHandler::SettingsNotificationHandler( + EditorSettingsOriginTracker::SettingsNotificationHandler::SettingsNotificationHandler( AZ::SettingsRegistryInterface& registry) : m_settingsRegistry(registry) { @@ -33,7 +33,7 @@ namespace AzToolsFramework m_settingsRegistry.SetApplyPatchSettings(applyPatchSettings); } - EditorPreferencesSettingsOriginTracker::SettingsNotificationHandler::~SettingsNotificationHandler() + EditorSettingsOriginTracker::SettingsNotificationHandler::~SettingsNotificationHandler() { // Restore previous reporting callback AZ::JsonApplyPatchSettings applyPatchSettings; @@ -44,7 +44,7 @@ namespace AzToolsFramework // Use the Json Serialization Issue Callback system // to determine when a merge option modifies a value - AZ::JsonSerializationResult::ResultCode EditorPreferencesSettingsOriginTracker::SettingsNotificationHandler::operator()( + AZ::JsonSerializationResult::ResultCode EditorSettingsOriginTracker::SettingsNotificationHandler::operator()( AZStd::string_view /*message*/, AZ::JsonSerializationResult::ResultCode result, AZStd::string_view path) { using FixedValueString = AZ::SettingsRegistryInterface::FixedValueString; @@ -65,7 +65,7 @@ namespace AzToolsFramework return result; } - void EditorPreferencesSettingsOriginTracker::SettingsNotificationHandler::operator()( + void EditorSettingsOriginTracker::SettingsNotificationHandler::operator()( AZStd::string_view path, AZ::SettingsRegistryInterface::Type /*type*/) { constexpr AZ::IO::PathView preferencesRootKey{ "/Amazon/Preferences", AZ::IO::PosixPathSeparator }; @@ -76,7 +76,7 @@ namespace AzToolsFramework } } - EditorPreferencesSettingsOriginTracker::EditorPreferencesSettingsOriginTracker(AZ::SettingsRegistryInterface& registry) + EditorSettingsOriginTracker::EditorSettingsOriginTracker(AZ::SettingsRegistryInterface& registry) : m_settingsRegistry(registry) { auto PreMergeEvent = [this](AZStd::string_view filePath, AZStd::string_view /*rootKey*/) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h index 63249a8ecd..3ef3f141a2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h @@ -12,9 +12,9 @@ namespace AzToolsFramework { - struct EditorPreferencesSettingsOriginTracker + struct EditorSettingsOriginTracker { - explicit EditorPreferencesSettingsOriginTracker(AZ::SettingsRegistryInterface& registry); + explicit EditorSettingsOriginTracker(AZ::SettingsRegistryInterface& registry); struct SettingsNotificationHandler { From 88762b2b69992b6d28e37e94a163cf7e4691040c Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 10 Aug 2021 15:33:24 -0700 Subject: [PATCH 098/205] Add #pragma once to EditorSettingsOriginTracker to make it build :) Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../Editor/Settings/EditorSettingsOriginTracker.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h index 3ef3f141a2..fbfdc1af25 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h @@ -6,6 +6,8 @@ * */ +#pragma once + #include #include #include From d71674579a372c17af98f522f5b96949f2495667 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 16:22:03 -0700 Subject: [PATCH 099/205] fixing startup on game launcher Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/platform_impl.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index 3d7b2180fc..3d23d8783e 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -290,14 +290,14 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], uint // Check if the engineroot exists azstrcat(szPath, AZ_ARRAY_SIZE(szPath), "\\engine.json"); WIN32_FILE_ATTRIBUTE_DATA data; - AZStd::wstring szPathW; - AZStd::to_wstring(szPathW, szPath); - BOOL res = GetFileAttributesExW(szPathW.c_str(), GetFileExInfoStandard, &data); + wchar_t szPathW[_MAX_PATH]; + AZStd::to_wstring(szPathW, _MAX_PATH, szPath); + BOOL res = GetFileAttributesExW(szPathW, GetFileExInfoStandard, &data); if (res != 0 && data.dwFileAttributes != INVALID_FILE_ATTRIBUTES) { // Found file szPath[n] = 0; - SetCurrentDirectoryW(szPathW.c_str()); + SetCurrentDirectoryW(szPathW); break; } } From cfa6e259f3bc5ddeb690afb6e74f6aa27b25062c Mon Sep 17 00:00:00 2001 From: Jeremy Ong Date: Tue, 10 Aug 2021 17:24:07 -0600 Subject: [PATCH 100/205] Hide RenderDoc integration behind LY_RENDERDOC_ENABLED option Signed-off-by: Jeremy Ong --- Gems/Atom/RHI/Code/CMakeLists.txt | 8 +++----- Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake | 7 ------- .../RHI/Code/Platform/Windows/renderdoc_windows.cmake | 9 +-------- 3 files changed, 4 insertions(+), 20 deletions(-) diff --git a/Gems/Atom/RHI/Code/CMakeLists.txt b/Gems/Atom/RHI/Code/CMakeLists.txt index eeb8f73bac..343736ff7c 100644 --- a/Gems/Atom/RHI/Code/CMakeLists.txt +++ b/Gems/Atom/RHI/Code/CMakeLists.txt @@ -11,20 +11,19 @@ ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Sourc include(${pal_dir}/AtomRHITests_traits_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) +set(LY_RENDERDOC_ENABLED OFF CACHE BOOL "Enable RenderDoc integration.") set(RENDERDOC_CMAKE ${CMAKE_CURRENT_SOURCE_DIR}/${pal_dir}/renderdoc_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) if(EXISTS ${RENDERDOC_CMAKE}) include(${RENDERDOC_CMAKE}) endif() -if(TARGET "3rdParty::renderdoc") +if(LY_RENDERDOC_ENABLED AND TARGET "3rdParty::renderdoc") message(STATUS "Renderdoc found, adding as runtime dependency") set(USE_RENDERDOC_DEFINE "USE_RENDERDOC") set(RENDERDOC_BUILD_DEPENDENCY "3rdParty::renderdoc") - set(RENDERDOC_API_DEPENDENCY "3rdParty::renderdoc_api") else() set(USE_RENDERDOC_DEFINE "") set(RENDERDOC_BUILD_DEPENDENCY "") - set(RENDERDOC_API_DEPENDENCY "") endif() ly_add_target( @@ -62,9 +61,8 @@ ly_add_target( AZ::AzCore AZ::AzFramework Gem::Atom_RHI.Reflect - ${RENDERDOC_BUILD_DEPENDENCY} PUBLIC - ${RENDERDOC_API_DEPENDENCY} + ${RENDERDOC_BUILD_DEPENDENCY} COMPILE_DEFINITIONS PUBLIC ${USE_RENDERDOC_DEFINE} diff --git a/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake b/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake index 0faccf80ec..222a3d5768 100644 --- a/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake +++ b/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake @@ -24,13 +24,6 @@ if(NOT LY_MONOLITHIC_GAME) INCLUDE_DIRECTORIES "." RUNTIME_DEPENDENCIES "${RENDERDOC_PATH}/librenderdoc.so" ) - - ly_add_external_target( - NAME renderdoc_api - VERSION - 3RDPARTY_ROOT_DIRECTORY ${RENDERDOC_PATH} - INCLUDE_DIRECTORIES "." - ) endif() endif() endif() \ No newline at end of file diff --git a/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake b/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake index 499321b2ab..90c44bcb7c 100644 --- a/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake +++ b/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake @@ -9,7 +9,7 @@ # Prevent bundling the renderdoc dll with a packaged title if(NOT LY_MONOLITHIC_GAME) # Common installation path for renderdoc path - set(RENDERDOC_PATH "C:/Program Files/RenderDoc") + set(RENDERDOC_PATH "$ENV{PROGRAMFILES}/RenderDoc") if(DEFINED ENV{"ATOM_RENDERDOC_PATH"}) set(RENDERDOC_PATH ENV{"ATOM_RENDERDOC_PATH"}) endif() @@ -26,13 +26,6 @@ if(NOT LY_MONOLITHIC_GAME) INCLUDE_DIRECTORIES "." RUNTIME_DEPENDENCIES "${RENDERDOC_PATH}/renderdoc.dll" ) - - ly_add_external_target( - NAME renderdoc_api - VERSION - 3RDPARTY_ROOT_DIRECTORY ${RENDERDOC_PATH} - INCLUDE_DIRECTORIES "." - ) endif() endif() endif() \ No newline at end of file From 25844a9ed6cff59d07e6cce1bdc63f01da6a8412 Mon Sep 17 00:00:00 2001 From: AMZN-mnaumov <82239319+AMZN-mnaumov@users.noreply.github.com> Date: Tue, 10 Aug 2021 16:40:51 -0700 Subject: [PATCH 101/205] Selecting entities when duplicating prefabs (#2995) * Selecting entitie when duplicating prefabs Signed-off-by: mnaumov * PR feedback Signed-off-by: mnaumov --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 69efe33d72..bb394720c9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -1727,6 +1727,7 @@ namespace AzToolsFramework AliasPath absoluteInstancePath = commonOwningInstance.GetAbsoluteInstanceAliasPath(); absoluteInstancePath.Append(newInstanceAlias); + absoluteInstancePath.Append(PrefabDomUtils::ContainerEntityName); AZ::EntityId newEntityId = InstanceEntityIdMapper::GenerateEntityIdForAliasPath(absoluteInstancePath); duplicatedEntityIds.push_back(newEntityId); From c0ed0a792520cd98bf6f2443eea8dbb1f24e1fff Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Tue, 10 Aug 2021 16:59:21 -0700 Subject: [PATCH 102/205] Added more tool tip data to repeater. Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- .../Core/RepeaterNodeable.ScriptCanvasNodeable.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Core/RepeaterNodeable.ScriptCanvasNodeable.xml b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Core/RepeaterNodeable.ScriptCanvasNodeable.xml index 14634ff959..951a30ceb1 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Core/RepeaterNodeable.ScriptCanvasNodeable.xml +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Core/RepeaterNodeable.ScriptCanvasNodeable.xml @@ -10,17 +10,17 @@ Category="Nodeables" GeneratePropertyFriend="True" Namespace="ScriptCanvas" - Description="Repeats the output signal the given number of times using the specified delay to space the signals out"> + Description="Repeats the output signal the given number of times using the specified delay to space the signals out."> - + - + From 4cee263033090c4464607eb53f198ab3db8c54e3 Mon Sep 17 00:00:00 2001 From: Artur K <96597+nemerle@users.noreply.github.com> Date: Wed, 11 Aug 2021 02:07:01 +0200 Subject: [PATCH 103/205] Minimal TypeInfo header/reduce std interdependencies. (#2688) * Minimal TypeInfo header/reduce std interdependencies. TypeInfoSimple.h is a small header that can replace the use of TypeInfo.h in some cases. Signed-off-by: Nemerle * Windows build fixed Removed algorithm.h from string_view.h smoke-test passed Signed-off-by: nemerle <96597+nemerle@users.noreply.github.com> * Resotore dynamic_pointer_cast in intrusive_ptr Requested by reviewer. Signed-off-by: nemerle <96597+nemerle@users.noreply.github.com> * Fix CI build string.h - missed alogorithm.h, since it was removed from string_view NodeWrapper.h - missing smart_ptr.h Signed-off-by: nemerle <96597+nemerle@users.noreply.github.com> Co-authored-by: Nemerle --- .../EditorCommon/DrawingPrimitives/Ruler.cpp | 1 + .../std/containers/fixed_vector_set.h | 1 + .../AzCore/AzCore/Component/ComponentExport.h | 2 +- .../AzCore/AzCore/Component/EntityId.h | 2 +- .../AzCore/AzCore/Debug/IEventLogger.h | 2 +- .../AzCore/AzCore/EBus/OrderedEvent.inl | 1 + Code/Framework/AzCore/AzCore/IO/Path/Path.h | 1 + .../AzCore/AzCore/Interface/Interface.h | 1 + Code/Framework/AzCore/AzCore/Math/Crc.h | 4 +- .../AzCore/AzCore/Math/PackedVector3.h | 1 + Code/Framework/AzCore/AzCore/Math/Random.h | 4 +- Code/Framework/AzCore/AzCore/Math/Vector2.h | 2 +- Code/Framework/AzCore/AzCore/Math/Vector3.h | 2 +- Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h | 36 +----------------- .../AzCore/AzCore/RTTI/TypeInfoSimple.h | 38 +++++++++++++++++++ .../AzCore/AzCore/Serialization/DataOverlay.h | 2 +- .../Serialization/Json/ArraySerializer.h | 2 +- .../Serialization/Json/DoubleSerializer.h | 2 +- .../AzCore/Serialization/Json/IntSerializer.h | 2 +- .../AzCore/AzCore/azcore_files.cmake | 1 + Code/Framework/AzCore/AzCore/std/allocator.h | 2 +- .../AzCore/AzCore/std/allocator_traits.h | 1 + .../AzCore/AzCore/std/chrono/types.h | 1 - .../AzCore/AzCore/std/containers/deque.h | 4 +- .../AzCore/AzCore/std/containers/list.h | 3 +- .../AzCore/std/containers/ring_buffer.h | 1 - .../AzCore/AzCore/std/containers/vector.h | 7 +--- .../AzCore/AzCore/std/createdestroy.h | 1 + .../AzCore/std/function/function_base.h | 1 + .../AzCore/std/function/function_template.h | 1 + Code/Framework/AzCore/AzCore/std/hash_table.h | 1 - Code/Framework/AzCore/AzCore/std/iterator.h | 3 +- .../AzCore/AzCore/std/parallel/atomic.h | 2 - .../AzCore/std/smart_ptr/intrusive_ptr.h | 24 +++++------- .../AzCore/AzCore/std/string/string.h | 1 + .../AzCore/AzCore/std/string/string_view.h | 15 +++++--- .../AzCore/std/typetraits/conjunction.h | 1 + .../AzCore/std/typetraits/static_storage.h | 3 +- Code/Framework/AzCore/AzCore/std/utils.h | 2 +- .../IO/Streamer/StreamerContext_Default.h | 1 + .../AzCore/Debug/StackTracer_Windows.cpp | 1 + .../Framework/AzCore/Tests/AZStd/SmartPtr.cpp | 5 ++- .../AzFramework/Archive/IArchive.h | 1 + .../AzFramework/Asset/CfgFileAsset.h | 2 +- .../Physics/Collision/CollisionGroups.h | 2 +- .../Physics/Collision/CollisionLayers.h | 2 +- .../Configuration/CollisionConfiguration.h | 2 +- .../Configuration/SceneConfiguration.h | 2 +- .../Slice/SliceInstantiationTicket.h | 2 +- .../AzFramework/Viewport/CameraState.h | 5 +++ .../AzFramework/Viewport/ScreenGeometry.h | 3 +- .../AzNetworking/PacketLayer/IPacket.h | 2 +- .../AzToolsFramework/API/ViewPaneOptions.h | 2 +- .../AzToolsFramework/Asset/AssetDebugInfo.h | 2 +- .../AzToolsFramework/Viewport/ViewportTypes.h | 1 + Code/Legacy/CryCommon/LyShine/UiAssetTypes.h | 2 +- .../native/ui/AssetTreeFilterModel.h | 1 + .../native/ui/SourceAssetDetailsPanel.h | 1 + Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h | 1 + .../SceneCore/Utilities/DebugOutput.h | 1 + .../Include/Private/ClientConfiguration.h | 1 + .../MaterialFunctorSourceDataRegistration.h | 1 + .../Code/Editor/Utilities/RecentFiles.cpp | 1 + 63 files changed, 129 insertions(+), 96 deletions(-) create mode 100644 Code/Framework/AzCore/AzCore/RTTI/TypeInfoSimple.h diff --git a/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp b/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp index 866a8206d6..1f0bd9ad88 100644 --- a/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp +++ b/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp @@ -12,6 +12,7 @@ #include #include #include +#include namespace DrawingPrimitives { diff --git a/Code/Framework/AtomCore/AtomCore/std/containers/fixed_vector_set.h b/Code/Framework/AtomCore/AtomCore/std/containers/fixed_vector_set.h index 1d5c9c2edd..c014f4b44e 100644 --- a/Code/Framework/AtomCore/AtomCore/std/containers/fixed_vector_set.h +++ b/Code/Framework/AtomCore/AtomCore/std/containers/fixed_vector_set.h @@ -8,6 +8,7 @@ #pragma once #include +#include namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentExport.h b/Code/Framework/AzCore/AzCore/Component/ComponentExport.h index c31c739160..0b3f9ea617 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentExport.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentExport.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include #include diff --git a/Code/Framework/AzCore/AzCore/Component/EntityId.h b/Code/Framework/AzCore/AzCore/Component/EntityId.h index 8e00cc70a9..e95813b388 100644 --- a/Code/Framework/AzCore/AzCore/Component/EntityId.h +++ b/Code/Framework/AzCore/AzCore/Component/EntityId.h @@ -9,7 +9,7 @@ #define AZCORE_ENTITY_ID_H #include -#include +#include #include /** @file diff --git a/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h b/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h index f04199e923..a11b411ded 100644 --- a/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h +++ b/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/EBus/OrderedEvent.inl b/Code/Framework/AzCore/AzCore/EBus/OrderedEvent.inl index 7c2e92d25b..aa3ac7d5ef 100644 --- a/Code/Framework/AzCore/AzCore/EBus/OrderedEvent.inl +++ b/Code/Framework/AzCore/AzCore/EBus/OrderedEvent.inl @@ -7,6 +7,7 @@ */ #pragma once +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.h b/Code/Framework/AzCore/AzCore/IO/Path/Path.h index 6f7e995a74..36640e821d 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.h +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/Interface/Interface.h b/Code/Framework/AzCore/AzCore/Interface/Interface.h index 8131f5b08f..8664e2905f 100644 --- a/Code/Framework/AzCore/AzCore/Interface/Interface.h +++ b/Code/Framework/AzCore/AzCore/Interface/Interface.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include #include diff --git a/Code/Framework/AzCore/AzCore/Math/Crc.h b/Code/Framework/AzCore/AzCore/Math/Crc.h index e8e8414f72..9ba2a83139 100644 --- a/Code/Framework/AzCore/AzCore/Math/Crc.h +++ b/Code/Framework/AzCore/AzCore/Math/Crc.h @@ -8,7 +8,7 @@ #pragma once #include - +#include #include ////////////////////////////////////////////////////////////////////////// @@ -108,7 +108,7 @@ namespace AZ namespace AZStd { - template<> + template<> struct hash { size_t operator()(const AZ::Crc32& id) const diff --git a/Code/Framework/AzCore/AzCore/Math/PackedVector3.h b/Code/Framework/AzCore/AzCore/Math/PackedVector3.h index 88108350c8..9a9acacdf3 100644 --- a/Code/Framework/AzCore/AzCore/Math/PackedVector3.h +++ b/Code/Framework/AzCore/AzCore/Math/PackedVector3.h @@ -8,6 +8,7 @@ #pragma once #include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Math/Random.h b/Code/Framework/AzCore/AzCore/Math/Random.h index 3c87824b1d..4912d9ad29 100644 --- a/Code/Framework/AzCore/AzCore/Math/Random.h +++ b/Code/Framework/AzCore/AzCore/Math/Random.h @@ -9,8 +9,10 @@ #pragma once #include -#include +#include #include +#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Math/Vector2.h b/Code/Framework/AzCore/AzCore/Math/Vector2.h index bd20618f06..c667f48010 100644 --- a/Code/Framework/AzCore/AzCore/Math/Vector2.h +++ b/Code/Framework/AzCore/AzCore/Math/Vector2.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Math/Vector3.h b/Code/Framework/AzCore/AzCore/Math/Vector3.h index 4be70aa02e..6b7ded5641 100644 --- a/Code/Framework/AzCore/AzCore/Math/Vector3.h +++ b/Code/Framework/AzCore/AzCore/Math/Vector3.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h b/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h index 8ec55274f5..022025a3df 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h +++ b/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h @@ -1006,12 +1006,6 @@ namespace AZ AZ_TYPE_INFO_INTERNAL_FUNCTION_VARIATION_SPECIALIZATION(AZStd::function, "{C9F9C644-CCC3-4F77-A792-F5B5DBCA746E}"); } // namespace AZ -#define AZ_TYPE_INFO_INTERNAL_1(_ClassName) static_assert(false, "You must provide a ClassName,ClassUUID") -#define AZ_TYPE_INFO_INTERNAL_2(_ClassName, _ClassUuid) \ - void TYPEINFO_Enable(){} \ - static const char* TYPEINFO_Name() { return #_ClassName; } \ - static const AZ::TypeId& TYPEINFO_Uuid() { static AZ::TypeId s_uuid(_ClassUuid); return s_uuid; } - // Template class type info #define AZ_TYPE_INFO_INTERNAL_TEMPLATE(_ClassName, _ClassUuid, ...)\ void TYPEINFO_Enable() {}\ @@ -1050,39 +1044,11 @@ namespace AZ #define AZ_TYPE_INFO_INTERNAL_17 AZ_TYPE_INFO_INTERNAL_TEMPLATE #define AZ_TYPE_INFO_INTERNAL(...) AZ_MACRO_SPECIALIZE(AZ_TYPE_INFO_INTERNAL_, AZ_VA_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__)) -#define AZ_TYPE_INFO_1 AZ_TYPE_INFO_INTERNAL_1 -#define AZ_TYPE_INFO_2 AZ_TYPE_INFO_INTERNAL_2 -#define AZ_TYPE_INFO_3 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_4 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_5 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_6 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_7 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_8 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_9 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_10 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_11 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_12 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_13 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_14 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_15 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_16 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED -#define AZ_TYPE_INFO_17 AZ_TYPE_INFO_INTERNAL_TEMPLATE_DEPRECATED - // Fall-back for the original version of AZ_TYPE_INFO that accepted template arguments. This should not be used, unless // to fix issues where AZ_TYPE_INFO was incorrectly used and the old UUID has to be maintained. #define AZ_TYPE_INFO_LEGACY AZ_TYPE_INFO_INTERNAL -/** -* Use this macro inside a class to allow it to be identified across modules and serialized (in different contexts). -* The expected input is the class and the assigned uuid as a string or an instance of a uuid. -* Example: -* class MyClass -* { -* public: -* AZ_TYPE_INFO(MyClass, "{BD5B1568-D232-4EBF-93BD-69DB66E3773F}"); -* ... -*/ -#define AZ_TYPE_INFO(...) AZ_MACRO_SPECIALIZE(AZ_TYPE_INFO_, AZ_VA_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__)) +#include /** * Use this macro outside a class to allow it to be identified across modules and serialized (in different contexts). diff --git a/Code/Framework/AzCore/AzCore/RTTI/TypeInfoSimple.h b/Code/Framework/AzCore/AzCore/RTTI/TypeInfoSimple.h new file mode 100644 index 0000000000..4da514f931 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/RTTI/TypeInfoSimple.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include + +namespace AZ +{ + using TypeId = AZ::Uuid; +} + +#define AZ_TYPE_INFO_INTERNAL_1(_ClassName) static_assert(false, "You must provide a ClassName,ClassUUID") +#define AZ_TYPE_INFO_INTERNAL_2(_ClassName, _ClassUuid) \ + void TYPEINFO_Enable(){} \ + static const char* TYPEINFO_Name() { return #_ClassName; } \ + static const AZ::TypeId& TYPEINFO_Uuid() { static AZ::TypeId s_uuid(_ClassUuid); return s_uuid; } + +#define AZ_TYPE_INFO_1 AZ_TYPE_INFO_INTERNAL_1 +#define AZ_TYPE_INFO_2 AZ_TYPE_INFO_INTERNAL_2 + +/** +* Use this macro inside a class to allow it to be identified across modules and serialized (in different contexts). +* The expected input is the class and the assigned uuid as a string or an instance of a uuid. +* Example: +* class MyClass +* { +* public: +* AZ_TYPE_INFO(MyClass, "{BD5B1568-D232-4EBF-93BD-69DB66E3773F}"); +* ... +*/ +#define AZ_TYPE_INFO(...) AZ_MACRO_SPECIALIZE(AZ_TYPE_INFO_, AZ_VA_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__)) + diff --git a/Code/Framework/AzCore/AzCore/Serialization/DataOverlay.h b/Code/Framework/AzCore/AzCore/Serialization/DataOverlay.h index 41f0b129e2..0fc4c5b362 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/DataOverlay.h +++ b/Code/Framework/AzCore/AzCore/Serialization/DataOverlay.h @@ -9,7 +9,7 @@ #define AZCORE_DATA_OVERLAY_H #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/ArraySerializer.h b/Code/Framework/AzCore/AzCore/Serialization/Json/ArraySerializer.h index eb7fd250d0..084e46194b 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/ArraySerializer.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/ArraySerializer.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/DoubleSerializer.h b/Code/Framework/AzCore/AzCore/Serialization/Json/DoubleSerializer.h index f3da5d6b1c..4ba5c2b011 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/DoubleSerializer.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/DoubleSerializer.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/IntSerializer.h b/Code/Framework/AzCore/AzCore/Serialization/Json/IntSerializer.h index b7a1989c83..4a22e84bad 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/IntSerializer.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/IntSerializer.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index c33d678730..0c95b9d592 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -434,6 +434,7 @@ set(FILES Preprocessor/Sequences.h RTTI/RTTI.h RTTI/TypeInfo.h + RTTI/TypeInfoSimple.h RTTI/ReflectContext.h RTTI/ReflectContext.cpp RTTI/ReflectionManager.h diff --git a/Code/Framework/AzCore/AzCore/std/allocator.h b/Code/Framework/AzCore/AzCore/std/allocator.h index 0e024bbb5f..0fee5481e2 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator.h +++ b/Code/Framework/AzCore/AzCore/std/allocator.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/allocator_traits.h b/Code/Framework/AzCore/AzCore/std/allocator_traits.h index 227727f694..95e64bbc49 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator_traits.h +++ b/Code/Framework/AzCore/AzCore/std/allocator_traits.h @@ -11,6 +11,7 @@ #include #include #include +#include namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/chrono/types.h b/Code/Framework/AzCore/AzCore/std/chrono/types.h index 19ef2c8469..ce42482132 100644 --- a/Code/Framework/AzCore/AzCore/std/chrono/types.h +++ b/Code/Framework/AzCore/AzCore/std/chrono/types.h @@ -10,7 +10,6 @@ #include #include -#include #include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/containers/deque.h b/Code/Framework/AzCore/AzCore/std/containers/deque.h index 170f3316f0..215845a8f4 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/deque.h +++ b/Code/Framework/AzCore/AzCore/std/containers/deque.h @@ -5,14 +5,17 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ +#pragma once #ifndef AZSTD_DEQUE_H #define AZSTD_DEQUE_H 1 + #include #include #include #include #include +#include namespace AZStd { @@ -1242,4 +1245,3 @@ namespace AZStd } #endif // AZSTD_DEQUE_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/containers/list.h b/Code/Framework/AzCore/AzCore/std/containers/list.h index 4d78c01364..124d8b7d7c 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/list.h +++ b/Code/Framework/AzCore/AzCore/std/containers/list.h @@ -7,12 +7,14 @@ */ #ifndef AZSTD_LIST_H #define AZSTD_LIST_H 1 +#pragma once #include #include #include #include #include +#include namespace AZStd { @@ -1346,4 +1348,3 @@ namespace AZStd } #endif // AZSTD_LIST_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h b/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h index 31fbdd85e9..7e84124958 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h +++ b/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h @@ -12,7 +12,6 @@ #include #include #include -//#include namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/containers/vector.h b/Code/Framework/AzCore/AzCore/std/containers/vector.h index 5c1c4da16c..bf02527d77 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/vector.h +++ b/Code/Framework/AzCore/AzCore/std/containers/vector.h @@ -5,13 +5,13 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZSTD_VECTOR_H -#define AZSTD_VECTOR_H 1 +#pragma once #include #include #include #include +#include namespace AZStd { @@ -1395,6 +1395,3 @@ namespace AZStd return removedCount; } } - -#endif // AZSTD_VECTOR_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/createdestroy.h b/Code/Framework/AzCore/AzCore/std/createdestroy.h index 94b86a58e4..0fa6e4ed40 100644 --- a/Code/Framework/AzCore/AzCore/std/createdestroy.h +++ b/Code/Framework/AzCore/AzCore/std/createdestroy.h @@ -16,6 +16,7 @@ #include #include #include +#include // AZStd::addressof namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/function/function_base.h b/Code/Framework/AzCore/AzCore/std/function/function_base.h index 409c3824a4..c1dd669f51 100644 --- a/Code/Framework/AzCore/AzCore/std/function/function_base.h +++ b/Code/Framework/AzCore/AzCore/std/function/function_base.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/function/function_template.h b/Code/Framework/AzCore/AzCore/std/function/function_template.h index 4f7d41dbd9..586b02e671 100644 --- a/Code/Framework/AzCore/AzCore/std/function/function_template.h +++ b/Code/Framework/AzCore/AzCore/std/function/function_template.h @@ -9,6 +9,7 @@ #include #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/hash_table.h b/Code/Framework/AzCore/AzCore/std/hash_table.h index c364720b3b..9a31020c49 100644 --- a/Code/Framework/AzCore/AzCore/std/hash_table.h +++ b/Code/Framework/AzCore/AzCore/std/hash_table.h @@ -7,7 +7,6 @@ */ #pragma once -#include #include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/iterator.h b/Code/Framework/AzCore/AzCore/std/iterator.h index 6135b6f450..8d0d49b649 100644 --- a/Code/Framework/AzCore/AzCore/std/iterator.h +++ b/Code/Framework/AzCore/AzCore/std/iterator.h @@ -8,8 +8,9 @@ #pragma once #include -#include #include +#include +#include #include // use by ConstIteratorCast #include diff --git a/Code/Framework/AzCore/AzCore/std/parallel/atomic.h b/Code/Framework/AzCore/AzCore/std/parallel/atomic.h index 09b6f68166..8516dd976a 100644 --- a/Code/Framework/AzCore/AzCore/std/parallel/atomic.h +++ b/Code/Framework/AzCore/AzCore/std/parallel/atomic.h @@ -8,8 +8,6 @@ #pragma once #include -#include -#include #include namespace AZStd diff --git a/Code/Framework/AzCore/AzCore/std/smart_ptr/intrusive_ptr.h b/Code/Framework/AzCore/AzCore/std/smart_ptr/intrusive_ptr.h index 20bc51a18b..9ee9b94fd0 100644 --- a/Code/Framework/AzCore/AzCore/std/smart_ptr/intrusive_ptr.h +++ b/Code/Framework/AzCore/AzCore/std/smart_ptr/intrusive_ptr.h @@ -5,8 +5,7 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZSTD_SMART_PTR_INTRUSIVE_PTR_H -#define AZSTD_SMART_PTR_INTRUSIVE_PTR_H +#pragma once // // intrusive_ptr.hpp @@ -19,10 +18,10 @@ // // See http://www.boost.org/libs/smart_ptr/intrusive_ptr.html for documentation. // - -#include #include +#include #include +#include namespace AZStd { @@ -112,7 +111,7 @@ namespace AZStd CountPolicy::add_ref(px); } } - + ~intrusive_ptr() { if (px != 0) @@ -120,7 +119,7 @@ namespace AZStd CountPolicy::release(px); } } - + template enable_if_t::value, intrusive_ptr&> operator=(intrusive_ptr const& rhs) { @@ -157,28 +156,28 @@ namespace AZStd this_type(rhs).swap(*this); return *this; } - + intrusive_ptr& operator=(T* rhs) { this_type(rhs).swap(*this); return *this; } - + void reset() { this_type().swap(*this); } - + void reset(T* rhs) { this_type(rhs).swap(*this); } - + T* get() const { return px; } - + T& operator*() const { AZ_Assert(px != 0, "You can't dereference a null pointer"); @@ -298,6 +297,3 @@ namespace AZStd // operator<< - not supported } // namespace AZStd - -#endif // #ifndef AZSTD_SMART_PTR_INTRUSIVE_PTR_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/string/string.h b/Code/Framework/AzCore/AzCore/std/string/string.h index 4d8fb0c5b5..ad3546ab09 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string.h +++ b/Code/Framework/AzCore/AzCore/std/string/string.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/std/string/string_view.h b/Code/Framework/AzCore/AzCore/std/string/string_view.h index a3d243dae7..9a98795554 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string_view.h +++ b/Code/Framework/AzCore/AzCore/std/string/string_view.h @@ -8,15 +8,16 @@ #pragma once #include -#include #include #include -#include + namespace AZStd { namespace StringInternal { + constexpr size_t min_size(size_t left, size_t right) { return (left < right) ? left : right; } + template constexpr SizeT char_find(const CharT* s, size_t count, CharT ch, SizeT npos = static_cast(-1)) noexcept { @@ -83,7 +84,7 @@ namespace AZStd } // Add one to offset so that for loop condition can check against 0 as the breakout condition - size_t lastIndex = (AZStd::min)(offset, size - count) + 1; + size_t lastIndex = StringInternal::min_size(offset, size - count) + 1; for (; lastIndex; --lastIndex) { @@ -576,7 +577,7 @@ namespace AZStd { return 0; } - size_type rlen = AZStd::min(count, size() - pos); + size_type rlen = StringInternal::min_size(count, size() - pos); Traits::copy(dest, data() + pos, rlen); return rlen; } @@ -584,12 +585,12 @@ namespace AZStd constexpr basic_string_view substr(size_type pos = 0, size_type count = npos) const { AZ_Assert(pos <= size(), "Cannot create substring where position is larger than size"); - return pos > size() ? basic_string_view() : basic_string_view(data() + pos, AZStd::min(count, size() - pos)); + return pos > size() ? basic_string_view() : basic_string_view(data() + pos, StringInternal::min_size(count, size() - pos)); } constexpr int compare(basic_string_view other) const { - size_t cmpSize = AZStd::min(size(), other.size()); + size_t cmpSize = StringInternal::min_size(size(), other.size()); int cmpval = cmpSize == 0 ? 0 : Traits::compare(data(), other.data(), cmpSize); if (cmpval == 0) { @@ -891,6 +892,8 @@ namespace AZStd return hash; } + template + struct hash; template struct hash> { diff --git a/Code/Framework/AzCore/AzCore/std/typetraits/conjunction.h b/Code/Framework/AzCore/AzCore/std/typetraits/conjunction.h index c6084e020e..64f923a40e 100644 --- a/Code/Framework/AzCore/AzCore/std/typetraits/conjunction.h +++ b/Code/Framework/AzCore/AzCore/std/typetraits/conjunction.h @@ -8,6 +8,7 @@ #pragma once #include +#include // for true_type namespace AZStd { diff --git a/Code/Framework/AzCore/AzCore/std/typetraits/static_storage.h b/Code/Framework/AzCore/AzCore/std/typetraits/static_storage.h index 449c9d85c0..00a683b0a8 100644 --- a/Code/Framework/AzCore/AzCore/std/typetraits/static_storage.h +++ b/Code/Framework/AzCore/AzCore/std/typetraits/static_storage.h @@ -9,11 +9,12 @@ #include #include -#include +#include #include namespace AZStd { + using std::forward; // Extension: static_storage: Used to initialize statics in a thread-safe manner // These are similar to default_delete/no_delete, except they just invoke the destructor (or not) template diff --git a/Code/Framework/AzCore/AzCore/std/utils.h b/Code/Framework/AzCore/AzCore/std/utils.h index 0de56cedcb..4c918250de 100644 --- a/Code/Framework/AzCore/AzCore/std/utils.h +++ b/Code/Framework/AzCore/AzCore/std/utils.h @@ -23,7 +23,7 @@ #include #include -#include +#include namespace AZStd { diff --git a/Code/Framework/AzCore/Platform/Common/Default/AzCore/IO/Streamer/StreamerContext_Default.h b/Code/Framework/AzCore/Platform/Common/Default/AzCore/IO/Streamer/StreamerContext_Default.h index 1478f663fa..3052c3f874 100644 --- a/Code/Framework/AzCore/Platform/Common/Default/AzCore/IO/Streamer/StreamerContext_Default.h +++ b/Code/Framework/AzCore/Platform/Common/Default/AzCore/IO/Streamer/StreamerContext_Default.h @@ -11,6 +11,7 @@ #include #include #include +#include namespace AZ::Platform { diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index d2cdac84c7..e6be83bde1 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -7,6 +7,7 @@ */ #include #include +#include #include #include diff --git a/Code/Framework/AzCore/Tests/AZStd/SmartPtr.cpp b/Code/Framework/AzCore/Tests/AZStd/SmartPtr.cpp index 6fe55b5672..c852fd35bb 100644 --- a/Code/Framework/AzCore/Tests/AZStd/SmartPtr.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/SmartPtr.cpp @@ -2051,10 +2051,11 @@ namespace UnitTest TEST_F(SmartPtr, IntrusivePtr_DynamicCast) { + AZStd::intrusive_ptr basePointer = new RefCountedSubclass; - AZStd::intrusive_ptr correctCast = dynamic_pointer_cast(basePointer); - AZStd::intrusive_ptr wrongCast = dynamic_pointer_cast(basePointer); + AZStd::intrusive_ptr correctCast = azdynamic_cast(basePointer); + AZStd::intrusive_ptr wrongCast = azdynamic_cast(basePointer); EXPECT_TRUE(correctCast.get() == basePointer.get()); EXPECT_TRUE(wrongCast.get() == nullptr); diff --git a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h index 3de63169b2..8866c1b74d 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Asset/CfgFileAsset.h b/Code/Framework/AzFramework/AzFramework/Asset/CfgFileAsset.h index aacf4303a7..2aadf9ae6c 100644 --- a/Code/Framework/AzFramework/AzFramework/Asset/CfgFileAsset.h +++ b/Code/Framework/AzFramework/AzFramework/Asset/CfgFileAsset.h @@ -7,7 +7,7 @@ */ #pragma once -#include +#include #include namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.h b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.h index f83a042577..5340a1a344 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.h b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.h index 25675e311a..6b5a4cd2a9 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/CollisionConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/CollisionConfiguration.h index e784c2339b..b6308e19e0 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/CollisionConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/CollisionConfiguration.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SceneConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SceneConfiguration.h index 246059bde9..a6590d3702 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SceneConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/SceneConfiguration.h @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Slice/SliceInstantiationTicket.h b/Code/Framework/AzFramework/AzFramework/Slice/SliceInstantiationTicket.h index 092fcd7822..3097c18d60 100644 --- a/Code/Framework/AzFramework/AzFramework/Slice/SliceInstantiationTicket.h +++ b/Code/Framework/AzFramework/AzFramework/Slice/SliceInstantiationTicket.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h index 0887754bdf..e174771c3b 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraState.h @@ -11,6 +11,11 @@ #include #include +namespace AZ +{ + class SerializeContext; +} // namespace AZ + namespace AzFramework { //! Represents the camera state populated by the viewport camera. diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h index 1063709343..c0fa1ad631 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ScreenGeometry.h @@ -11,7 +11,8 @@ #include #include #include -#include +#include +#include namespace AZ { diff --git a/Code/Framework/AzNetworking/AzNetworking/PacketLayer/IPacket.h b/Code/Framework/AzNetworking/AzNetworking/PacketLayer/IPacket.h index 021ca54cca..9962382f9f 100644 --- a/Code/Framework/AzNetworking/AzNetworking/PacketLayer/IPacket.h +++ b/Code/Framework/AzNetworking/AzNetworking/PacketLayer/IPacket.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h index a05a57e138..be93e1af1a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewPaneOptions.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetDebugInfo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetDebugInfo.h index 38bee8a1e5..56eaeb0f75 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetDebugInfo.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetDebugInfo.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h index 0ce80261ce..1cfb0dbe74 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h @@ -19,6 +19,7 @@ namespace AZ { class ReflectContext; + class SerializeContext; } namespace AzToolsFramework diff --git a/Code/Legacy/CryCommon/LyShine/UiAssetTypes.h b/Code/Legacy/CryCommon/LyShine/UiAssetTypes.h index a9c810c025..fef5f4d348 100644 --- a/Code/Legacy/CryCommon/LyShine/UiAssetTypes.h +++ b/Code/Legacy/CryCommon/LyShine/UiAssetTypes.h @@ -7,7 +7,7 @@ */ #pragma once -#include +#include #include //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Code/Tools/AssetProcessor/native/ui/AssetTreeFilterModel.h b/Code/Tools/AssetProcessor/native/ui/AssetTreeFilterModel.h index 05fd3d73d7..70b10e915f 100644 --- a/Code/Tools/AssetProcessor/native/ui/AssetTreeFilterModel.h +++ b/Code/Tools/AssetProcessor/native/ui/AssetTreeFilterModel.h @@ -10,6 +10,7 @@ #if !defined(Q_MOC_RUN) #include +#include #include #endif diff --git a/Code/Tools/AssetProcessor/native/ui/SourceAssetDetailsPanel.h b/Code/Tools/AssetProcessor/native/ui/SourceAssetDetailsPanel.h index 99610467a6..dec4749e03 100644 --- a/Code/Tools/AssetProcessor/native/ui/SourceAssetDetailsPanel.h +++ b/Code/Tools/AssetProcessor/native/ui/SourceAssetDetailsPanel.h @@ -10,6 +10,7 @@ #if !defined(Q_MOC_RUN) #include "AssetDetailsPanel.h" +#include #include #endif diff --git a/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h b/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h index e011bf213f..bef3cf0db4 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h +++ b/Code/Tools/SceneAPI/SDKWrapper/NodeWrapper.h @@ -7,6 +7,7 @@ */ #pragma once #include +#include struct aiNode; diff --git a/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h b/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h index 5bb57a6167..5fe5b98243 100644 --- a/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h +++ b/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace AZ::SceneAPI::Utilities diff --git a/Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h b/Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h index 7bcb60d325..ddda2299d4 100644 --- a/Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h +++ b/Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h @@ -8,6 +8,7 @@ #pragma once #include +#include namespace AWSMetrics { diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h index 8d8700f284..6ec4641fd8 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceDataRegistration.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include #include diff --git a/Gems/ScriptCanvas/Code/Editor/Utilities/RecentFiles.cpp b/Gems/ScriptCanvas/Code/Editor/Utilities/RecentFiles.cpp index fa665bb48f..84ee2a8ff8 100644 --- a/Gems/ScriptCanvas/Code/Editor/Utilities/RecentFiles.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Utilities/RecentFiles.cpp @@ -8,6 +8,7 @@ #include "RecentFiles.h" #include "CommonSettingsConfigurations.h" +#include #include #include From f3fe8439a71a15fdfab6af58b384315efe8b9698 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 10 Aug 2021 17:29:27 -0700 Subject: [PATCH 104/205] Fix local variable declaration. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp index 4a7b4183f3..8b10013408 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp @@ -1162,7 +1162,7 @@ namespace AZ return false; } - ScopedMergeEvent(m_preMergeEvent, m_postMergeEvent, path, rootKey); + ScopedMergeEvent scopedMergeEvent(m_preMergeEvent, m_postMergeEvent, path, rootKey); JsonSerializationResult::ResultCode mergeResult(JsonSerializationResult::Tasks::Merge); if (rootKey.empty()) From 6db547302ea047479af2649db8f80da535412a8e Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 10 Aug 2021 17:32:39 -0700 Subject: [PATCH 105/205] Remove EditorSettingsOriginTracker (moved to prototype branch) Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../Settings/EditorSettingsOriginTracker.cpp | 103 ------------------ .../Settings/EditorSettingsOriginTracker.h | 41 ------- .../aztoolsframework_files.cmake | 2 - 3 files changed, 146 deletions(-) delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp deleted file mode 100644 index bdeb4e41b4..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include - -#include -#include - -namespace AzToolsFramework -{ - EditorSettingsOriginTracker::SettingsNotificationHandler::SettingsNotificationHandler( - AZ::SettingsRegistryInterface& registry) - : m_settingsRegistry(registry) - { - AZ::JsonApplyPatchSettings applyPatchSettings; - m_settingsRegistry.GetApplyPatchSettings(applyPatchSettings); - // Wrap any existing callbacks into the reporting callback, so that both this struct - // reporting callbacks and the existing callbacks can be invoked - m_prevReportingCallback = applyPatchSettings.m_reporting; - applyPatchSettings.m_reporting = [this]( - AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, - AZStd::string_view path) -> AZ::JsonSerializationResult::ResultCode - { - m_prevReportingCallback(message, result, path); - (*this)(message, result, path); - return result; - }; - m_settingsRegistry.SetApplyPatchSettings(applyPatchSettings); - } - - EditorSettingsOriginTracker::SettingsNotificationHandler::~SettingsNotificationHandler() - { - // Restore previous reporting callback - AZ::JsonApplyPatchSettings applyPatchSettings; - m_settingsRegistry.GetApplyPatchSettings(applyPatchSettings); - applyPatchSettings.m_reporting = m_prevReportingCallback; - m_settingsRegistry.SetApplyPatchSettings(applyPatchSettings); - } - - // Use the Json Serialization Issue Callback system - // to determine when a merge option modifies a value - AZ::JsonSerializationResult::ResultCode EditorSettingsOriginTracker::SettingsNotificationHandler::operator()( - AZStd::string_view /*message*/, AZ::JsonSerializationResult::ResultCode result, AZStd::string_view path) - { - using FixedValueString = AZ::SettingsRegistryInterface::FixedValueString; - - AZ::IO::PathView preferencesRootKey{ "/Amazon/Preferences", AZ::IO::PosixPathSeparator }; - AZ::IO::PathView inputKey{ path, AZ::IO::PosixPathSeparator }; - - // Delegate to the Notifier Handler callable below - if (result.GetTask() == AZ::JsonSerializationResult::Tasks::Merge && - result.GetProcessing() == AZ::JsonSerializationResult::Processing::Completed && inputKey.IsRelativeTo(preferencesRootKey)) - { - if (auto type = m_settingsRegistry.GetType(path); type != AZ::SettingsRegistryInterface::Type::NoType) - { - operator()(path, type); - } - } - - return result; - } - - void EditorSettingsOriginTracker::SettingsNotificationHandler::operator()( - AZStd::string_view path, AZ::SettingsRegistryInterface::Type /*type*/) - { - constexpr AZ::IO::PathView preferencesRootKey{ "/Amazon/Preferences", AZ::IO::PosixPathSeparator }; - AZ::IO::PathView inputKey{ path, AZ::IO::PosixPathSeparator }; - if (inputKey.IsRelativeTo(preferencesRootKey)) - { - // Do stuff with key - } - } - - EditorSettingsOriginTracker::EditorSettingsOriginTracker(AZ::SettingsRegistryInterface& registry) - : m_settingsRegistry(registry) - { - auto PreMergeEvent = [this](AZStd::string_view filePath, AZStd::string_view /*rootKey*/) - { - AZ::IO::FixedMaxPath editorPreferencesPath = AZ::Utils::GetProjectPath(); - editorPreferencesPath = editorPreferencesPath / "user" / "Registry" / "editorpreferences.setreg"; - - if (AZ::IO::PathView(filePath) == editorPreferencesPath) - { - m_notifyHandler = m_settingsRegistry.RegisterNotifier(SettingsNotificationHandler(m_settingsRegistry)); - } - }; - - auto PostMergeEvent = [this](AZStd::string_view /*filePath*/, AZStd::string_view /*rootKey*/) - { - // Clear the notification handler so that it goes out of scope - // and this tracker instance no handles settings updates - m_notifyHandler = {}; - }; - - m_preMergeEventHandler = m_settingsRegistry.RegisterPreMergeEvent(PreMergeEvent); - m_postMergeEventHandler = m_settingsRegistry.RegisterPostMergeEvent(PostMergeEvent); - } -} diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h deleted file mode 100644 index fbfdc1af25..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/Settings/EditorSettingsOriginTracker.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include -#include - -namespace AzToolsFramework -{ - struct EditorSettingsOriginTracker - { - explicit EditorSettingsOriginTracker(AZ::SettingsRegistryInterface& registry); - - struct SettingsNotificationHandler - { - SettingsNotificationHandler(AZ::SettingsRegistryInterface& registry); - ~SettingsNotificationHandler(); - - AZ::JsonSerializationResult::ResultCode operator()( - AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, AZStd::string_view path); - void operator()(AZStd::string_view path, AZ::SettingsRegistryInterface::Type type); - - private: - AZ::SettingsRegistryInterface& m_settingsRegistry; - AZ::JsonSerializationResult::JsonIssueCallback m_prevReportingCallback; - }; - - private: - AZ::SettingsRegistryInterface& m_settingsRegistry; - AZ::SettingsRegistryInterface::PreMergeEventHandler m_preMergeEventHandler; - AZ::SettingsRegistryInterface::PostMergeEventHandler m_postMergeEventHandler; - AZ::SettingsRegistryInterface::NotifyEventHandler m_notifyHandler; - }; -} // namespace AZ diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 6e7446d74d..53173f83af 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -113,8 +113,6 @@ set(FILES Component/EditorLevelComponentAPIComponent.h Editor/EditorContextMenuBus.h Editor/EditorSettingsAPIBus.h - Editor/Settings/EditorSettingsOriginTracker.cpp - Editor/Settings/EditorSettingsOriginTracker.h Entity/EditorEntityStartStatus.h Entity/EditorEntityAPIBus.h Entity/EditorEntityContextComponent.cpp From 737cf3093791efb073ad226cbe7703e840c958d5 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 10 Aug 2021 17:36:43 -0700 Subject: [PATCH 106/205] Fix documentation comments to be more accurate. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../AzCore/AzCore/Settings/SettingsRegistry.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h index e27e4452ee..106e232904 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h @@ -199,18 +199,18 @@ namespace AZ //! @callback The function to call when an entry gets a new/updated value. [[nodiscard]] virtual NotifyEventHandler RegisterNotifier(NotifyCallback&& callback) = 0; - //! Register a callback that will be called before an entry is merged. - //! @callback The function to call when an entry gets a new/updated value. + //! Register a function that will be called before a file is merged. + //! @callback The function to call before a file is merged. [[nodiscard]] virtual PreMergeEventHandler RegisterPreMergeEvent(const PreMergeEventCallback& callback) = 0; - //! Register a callback that will be called before an entry is merged. - //! @callback The function to call when an entry gets a new/updated value. + //! Register a function that will be called before a file is merged. + //! @callback The function to call before a file is merged. [[nodiscard]] virtual PreMergeEventHandler RegisterPreMergeEvent (PreMergeEventCallback&& callback) = 0; - //! Register a callback that will be called after an entry is merged. - //! @callback The function to call when an entry gets a new/updated value. + //! Register a function that will be called after a file is merged. + //! @callback The function to call after a file is merged. [[nodiscard]] virtual PostMergeEventHandler RegisterPostMergeEvent(const PostMergeEventCallback& callback) = 0; - //! Register a callback that will be called after an entry is merged. - //! @callback The function to call when an entry gets a new/updated value. + //! Register a function that will be called after a file is merged. + //! @callback The function to call after a file is merged. [[nodiscard]] virtual PostMergeEventHandler RegisterPostMergeEvent (PostMergeEventCallback&& callback) = 0; //! Gets the boolean value at the provided path. From a7a0e8d2ef6778153deb28fedfc495832f162842 Mon Sep 17 00:00:00 2001 From: jonawals Date: Wed, 11 Aug 2021 02:43:44 +0100 Subject: [PATCH 107/205] Fix for PathLib unlink wrong version parameter. (#3020) * Fix for PathLib unlink wrong version parameter. * Fix dst target for TIAF. * Remove TIAF historic data arhciving on s3 buckets * Change permissions for TIAF bucket upload Signed-off-by: John --- scripts/build/Platform/Windows/build_config.json | 2 +- scripts/build/TestImpactAnalysis/git_utils.py | 4 +++- .../TestImpactAnalysis/tiaf_persistent_storage_s3.py | 9 +++------ 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index 8ac0b5241c..4c275a49cf 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -89,7 +89,7 @@ "CONFIGURATION": "profile", "SCRIPT_PATH": "scripts/build/TestImpactAnalysis/tiaf_driver.py", "SCRIPT_PARAMETERS": - "--config=\"!OUTPUT_DIRECTORY!/bin/TestImpactFramework/profile/Persistent/tiaf.json\" --src-branch=!BRANCH_NAME! --dst-branch=!BRANCH_NAME! --commit=!CHANGE_ID! --s3-bucket=!TEST_IMPACT_S3_BUCKET! --mars-index-prefix=jonawals --suite=main --test-failure-policy=continue" + "--config=\"!OUTPUT_DIRECTORY!/bin/TestImpactFramework/profile/Persistent/tiaf.json\" --src-branch=!BRANCH_NAME! --dst-branch=!CHANGE_TARGET! --commit=!CHANGE_ID! --s3-bucket=!TEST_IMPACT_S3_BUCKET! --mars-index-prefix=jonawals --suite=main --test-failure-policy=continue" } }, "debug_vs2019": { diff --git a/scripts/build/TestImpactAnalysis/git_utils.py b/scripts/build/TestImpactAnalysis/git_utils.py index 04d994ba4a..3561b337f3 100644 --- a/scripts/build/TestImpactAnalysis/git_utils.py +++ b/scripts/build/TestImpactAnalysis/git_utils.py @@ -32,7 +32,9 @@ class Repo: try: # Remove the existing file (if any) and create the parent directory - output_path.unlink(missing_ok=True) + # output_path.unlink(missing_ok=True) # missing_ok is only available in Python 3.8+ + if output_path.is_file(): + output_path.unlink() output_path.parent.mkdir(exist_ok=True) except EnvironmentError as e: raise RuntimeError(f"Could not create path for output file '{output_path}'") diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py index 75c4bc93d5..09b4df0564 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py @@ -48,14 +48,11 @@ class PersistentStorageS3(PersistentStorage): for object in self._bucket.objects.filter(Prefix=self._historic_data_key): logger.info(f"Historic data found for branch '{branch}'.") - # Archive the existing object with the name of the existing last commit hash - archive_key = f"{self._dir}/archive/{self._last_commit_hash}.{object_extension}" - logger.info(f"Archiving existing historic data to {archive_key}...") - self._bucket.copy({"Bucket": self._bucket.name, "Key": self._historic_data_key}, archive_key) - # Decode the historic data object into raw bytes + logger.info(f"Attempting to decode historic data object...") response = object.get() file_stream = response['Body'] + logger.info(f"Decoding complete.") # Decompress and unpack the zipped historic data JSON historic_data_json = zlib.decompress(file_stream.read()).decode('UTF-8') @@ -79,7 +76,7 @@ class PersistentStorageS3(PersistentStorage): try: data = BytesIO(zlib.compress(bytes(historic_data_json, "UTF-8"))) logger.info(f"Uploading historic data to location '{self._historic_data_key}'...") - self._bucket.upload_fileobj(data, self._historic_data_key) + self._bucket.upload_fileobj(data, self._historic_data_key, ExtraArgs={'ACL': 'bucket-owner-full-control'}) logger.info("Upload complete.") except botocore.exceptions.BotoCoreError as e: logger.error(f"There was a problem with the s3 bucket: {e}") From fa2032d21d406b959f4c94025cb94f412807cde3 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 19:02:38 -0700 Subject: [PATCH 108/205] Linux fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/GameEngine.h | 1 + Code/Editor/Include/IObjectManager.h | 1 + Code/Editor/QtUtil.h | 1 + .../Platform/Linux/Launcher_Linux.cpp | 1 + Code/Legacy/CryCommon/AppleSpecific.h | 4 ---- Code/Legacy/CryCommon/CryThread_pthreads.h | 20 ------------------- Code/Legacy/CryCommon/LinuxSpecific.h | 16 +++++++++++++-- Code/Legacy/CryCommon/Linux_Win32Wrapper.h | 2 -- Code/Legacy/CryCommon/VectorMap.h | 1 + 9 files changed, 19 insertions(+), 28 deletions(-) diff --git a/Code/Editor/GameEngine.h b/Code/Editor/GameEngine.h index 84df8bf002..829baec55a 100644 --- a/Code/Editor/GameEngine.h +++ b/Code/Editor/GameEngine.h @@ -20,6 +20,7 @@ #include "LogFile.h" #include "CryListenerSet.h" #include "Util/ModalWindowDismisser.h" +#include #endif class CStartupLogoDialog; diff --git a/Code/Editor/Include/IObjectManager.h b/Code/Editor/Include/IObjectManager.h index efc1955a56..360cc8fe34 100644 --- a/Code/Editor/Include/IObjectManager.h +++ b/Code/Editor/Include/IObjectManager.h @@ -12,6 +12,7 @@ #pragma once #include +#include #include #include #include diff --git a/Code/Editor/QtUtil.h b/Code/Editor/QtUtil.h index bb1f8ba427..a16eb1e692 100644 --- a/Code/Editor/QtUtil.h +++ b/Code/Editor/QtUtil.h @@ -12,6 +12,7 @@ #include #include #include "UnicodeFunctions.h" +#include #include #include diff --git a/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp b/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp index 1e87b902a6..3030dcc740 100644 --- a/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp +++ b/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp @@ -10,6 +10,7 @@ #include #include // for AZ_MAX_PATH_LEN +#include #include diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index 87aea0fbb5..df3b7578eb 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -355,13 +355,9 @@ enum #define wcsnicmp wcsncasecmp //#define memcpy_s(dest,bytes,src,n) memcpy(dest,src,n) #define _isnan ISNAN -#define _wtof(str) wcstod(str, 0) - #define TARGET_DEFAULT_ALIGN (0x8U) - - #define _msize malloc_size diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h index 2c6b389dbb..17f7e5d2a0 100644 --- a/Code/Legacy/CryCommon/CryThread_pthreads.h +++ b/Code/Legacy/CryCommon/CryThread_pthreads.h @@ -653,15 +653,9 @@ private: typedef CryEventTimed CryEvent; -#if !PLATFORM_SUPPORTS_THREADLOCAL -TLS_DECLARE(class CrySimpleThreadSelf*, g_CrySimpleThreadSelf); -#endif - class CrySimpleThreadSelf { protected: -#if PLATFORM_SUPPORTS_THREADLOCAL - static CrySimpleThreadSelf* GetSelf() { return m_Self; @@ -673,20 +667,6 @@ protected: } private: static AZ_THREAD_LOCAL CrySimpleThreadSelf* m_Self; - -#else - - static CrySimpleThreadSelf* GetSelf() - { - return TLS_GET(CrySimpleThreadSelf*, g_CrySimpleThreadSelf); - } - - static void SetSelf(CrySimpleThreadSelf* pSelf) - { - TLS_SET(g_CrySimpleThreadSelf, pSelf); - } - -#endif }; template diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h index a587350cb2..112e965555 100644 --- a/Code/Legacy/CryCommon/LinuxSpecific.h +++ b/Code/Legacy/CryCommon/LinuxSpecific.h @@ -209,8 +209,20 @@ typedef unsigned long int threadID; #define wcsicmp wcscasecmp #define wcsnicmp wcsncasecmp - -#define _wtof(str) wcstod(str, 0) +typedef union _LARGE_INTEGER +{ + struct + { + DWORD LowPart; + LONG HighPart; + }; + struct + { + DWORD LowPart; + LONG HighPart; + } u; + long long QuadPart; +} LARGE_INTEGER; // stdlib.h stuff #define _MAX_DRIVE 3 // max. length of drive component diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 2de17e6b28..625add59ad 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -324,8 +324,6 @@ inline uint32 GetTickCount() #define _strlwr_s(BUF, SIZE) strlwr(BUF) #define _strups strupr -#define _wtof(str) wcstod(str, 0) - // Need to include this before using it's used in finddata, but after the strnicmp definition #include "CryString.h" diff --git a/Code/Legacy/CryCommon/VectorMap.h b/Code/Legacy/CryCommon/VectorMap.h index 1a42f0e48f..75b1562c4d 100644 --- a/Code/Legacy/CryCommon/VectorMap.h +++ b/Code/Legacy/CryCommon/VectorMap.h @@ -14,6 +14,7 @@ #define CRYINCLUDE_CRYCOMMON_VECTORMAP_H #pragma once +#include //-------------------------------------------------------------------------- // VectorMap From 2361490c8bf0f89d4e32b84e60aa7dcc10e85a64 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 10 Aug 2021 20:18:59 -0700 Subject: [PATCH 109/205] Fixes for Android Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CryCommon/platform.h | 2 +- .../AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 88d06c9b1e..030fd4186e 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -192,7 +192,7 @@ #else #if defined(WIN64) #include "Win64specific.h" - #elif defined(LINUX64) + #elif defined(LINUX64) && !defined(ANDROID) #include "Linux64Specific.h" #elif defined(MAC) #include "MacSpecific.h" diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h index 7dd2629bd0..44de9656d2 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h @@ -20,6 +20,7 @@ #include #include #include +#include #include #include From f99f1f00f4de5696275db77cbbca5ee168891dab Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Tue, 10 Aug 2021 20:35:55 -0700 Subject: [PATCH 110/205] [redcode/crythread-2nd-pass] removed or replaced remaining CryMutex/CryLock usage with equivalent AZStd version Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Editor/CryEdit.cpp | 18 +++++++++--------- Code/Editor/GameEngine.h | 4 ++-- Code/Editor/GameExporter.cpp | 2 +- Code/Editor/IEditorImpl.cpp | 6 +++--- Code/Editor/IEditorImpl.h | 2 +- .../PerforcePlugin/PerforceSourceControl.cpp | 8 ++++---- Code/Legacy/CryCommon/CryAssert_Linux.h | 4 ++-- Code/Legacy/CryCommon/CryAssert_Mac.h | 2 -- Code/Legacy/CryCommon/IMaterial.h | 2 -- .../Legacy/CryCommon/MultiThread_Containers.h | 6 +++--- .../Legacy/CrySystem/LocalizedStringManager.h | 4 ++-- Code/Legacy/CrySystem/Log.cpp | 19 ++++--------------- Code/Legacy/CrySystem/Log.h | 4 +--- .../CrySystem/SystemEventDispatcher.cpp | 12 ++++++------ Code/Legacy/CrySystem/SystemEventDispatcher.h | 2 +- 15 files changed, 39 insertions(+), 56 deletions(-) diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index 5a5b17f799..fdde069e6f 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -891,7 +891,7 @@ CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(LPCTSTR lp ///////////////////////////////////////////////////////////////////////////// namespace { - CryMutex g_splashScreenStateLock; + AZStd::mutex g_splashScreenStateLock; enum ESplashScreenState { eSplashScreenState_Init, eSplashScreenState_Started, eSplashScreenState_Destroy @@ -922,7 +922,7 @@ QString FormatRichTextCopyrightNotice() ///////////////////////////////////////////////////////////////////////////// void CCryEditApp::ShowSplashScreen(CCryEditApp* app) { - g_splashScreenStateLock.Lock(); + g_splashScreenStateLock.lock(); CStartupLogoDialog* splashScreen = new CStartupLogoDialog(FormatVersion(app->m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice()); @@ -930,7 +930,7 @@ void CCryEditApp::ShowSplashScreen(CCryEditApp* app) g_splashScreen = splashScreen; g_splashScreenState = eSplashScreenState_Started; - g_splashScreenStateLock.Unlock(); + g_splashScreenStateLock.unlock(); splashScreen->show(); // Make sure the initial paint of the splash screen occurs so we dont get stuck with a blank window @@ -938,10 +938,10 @@ void CCryEditApp::ShowSplashScreen(CCryEditApp* app) QObject::connect(splashScreen, &QObject::destroyed, splashScreen, [=] { - g_splashScreenStateLock.Lock(); + g_splashScreenStateLock.lock(); g_pInitializeUIInfo = nullptr; g_splashScreen = nullptr; - g_splashScreenStateLock.Unlock(); + g_splashScreenStateLock.unlock(); }); } @@ -971,9 +971,9 @@ void CCryEditApp::CloseSplashScreen() if (CStartupLogoDialog::instance()) { delete CStartupLogoDialog::instance(); - g_splashScreenStateLock.Lock(); + g_splashScreenStateLock.lock(); g_splashScreenState = eSplashScreenState_Destroy; - g_splashScreenStateLock.Unlock(); + g_splashScreenStateLock.unlock(); } GetIEditor()->Notify(eNotify_OnSplashScreenDestroyed); @@ -982,12 +982,12 @@ void CCryEditApp::CloseSplashScreen() ///////////////////////////////////////////////////////////////////////////// void CCryEditApp::OutputStartupMessage(QString str) { - g_splashScreenStateLock.Lock(); + g_splashScreenStateLock.lock(); if (g_pInitializeUIInfo) { g_pInitializeUIInfo->SetInfoText(str.toUtf8().data()); } - g_splashScreenStateLock.Unlock(); + g_splashScreenStateLock.unlock(); } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/GameEngine.h b/Code/Editor/GameEngine.h index 84df8bf002..4d183cc38e 100644 --- a/Code/Editor/GameEngine.h +++ b/Code/Editor/GameEngine.h @@ -116,11 +116,11 @@ public: //! mutex used by other threads to lock up the PAK modification, //! so only one thread can modify the PAK at once - static CryMutex& GetPakModifyMutex() + static AZStd::recursive_mutex& GetPakModifyMutex() { //! mutex used to halt copy process while the export to game //! or other pak operation is done in the main thread - static CryMutex s_pakModifyMutex; + static AZStd::recursive_mutex s_pakModifyMutex; return s_pakModifyMutex; } diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp index 006eb9189c..d2a16ccc30 100644 --- a/Code/Editor/GameExporter.cpp +++ b/Code/Editor/GameExporter.cpp @@ -136,7 +136,7 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE m_settings.SetHiQuality(); } - CryAutoLock autoLock(CGameEngine::GetPakModifyMutex()); + AZStd::lock_guard autoLock(CGameEngine::GetPakModifyMutex()); // Close this pak file. if (!CloseLevelPack(m_levelPak, true)) diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp index c09c0a8e62..3c166fbca2 100644 --- a/Code/Editor/IEditorImpl.cpp +++ b/Code/Editor/IEditorImpl.cpp @@ -251,7 +251,7 @@ void CEditorImpl::Uninitialize() void CEditorImpl::UnloadPlugins() { - CryAutoLock lock(m_pluginMutex); + AZStd::lock_guard lock(m_pluginMutex); // Flush core buses. We're about to unload DLLs and need to ensure we don't have module-owned functions left behind. AZ::Data::AssetBus::ExecuteQueuedEvents(); @@ -272,7 +272,7 @@ void CEditorImpl::UnloadPlugins() void CEditorImpl::LoadPlugins() { - CryAutoLock lock(m_pluginMutex); + AZStd::lock_guard lock(m_pluginMutex); static const QString editor_plugins_folder("EditorPlugins"); @@ -1457,7 +1457,7 @@ void CEditorImpl::UnregisterNotifyListener(IEditorNotifyListener* listener) ISourceControl* CEditorImpl::GetSourceControl() { - CryAutoLock lock(m_pluginMutex); + AZStd::lock_guard lock(m_pluginMutex); if (m_pSourceControl) { diff --git a/Code/Editor/IEditorImpl.h b/Code/Editor/IEditorImpl.h index 65389a212e..275214bc57 100644 --- a/Code/Editor/IEditorImpl.h +++ b/Code/Editor/IEditorImpl.h @@ -401,7 +401,7 @@ protected: IImageUtil* m_pImageUtil; // Vladimir@conffx ILogFile* m_pLogFile; // Vladimir@conffx - CryMutex m_pluginMutex; // protect any pointers that come from plugins, such as the source control cached pointer. + AZStd::mutex m_pluginMutex; // protect any pointers that come from plugins, such as the source control cached pointer. static const char* m_crashLogFileName; }; diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp index 581f9a576d..34514b8ef1 100644 --- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp +++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp @@ -22,7 +22,7 @@ namespace { - CryCriticalSection g_cPerforceValues; + AZStd::mutex g_cPerforceValues; } //////////////////////////////////////////////////////////// @@ -30,9 +30,9 @@ ULONG STDMETHODCALLTYPE CPerforceSourceControl::Release() { if ((--m_ref) == 0) { - g_cPerforceValues.Lock(); + g_cPerforceValues.lock(); delete this; - g_cPerforceValues.Unlock(); + g_cPerforceValues.unlock(); return 0; } else @@ -56,7 +56,7 @@ void CPerforceSourceControl::ShowSettings() void CPerforceSourceControl::SetSourceControlState(SourceControlState state) { - CryAutoLock lock(g_cPerforceValues); + AZStd::lock_guard lock(g_cPerforceValues); switch (state) { diff --git a/Code/Legacy/CryCommon/CryAssert_Linux.h b/Code/Legacy/CryCommon/CryAssert_Linux.h index 3debe2bd5d..355194caba 100644 --- a/Code/Legacy/CryCommon/CryAssert_Linux.h +++ b/Code/Legacy/CryCommon/CryAssert_Linux.h @@ -72,7 +72,7 @@ bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, b static const int max_len = 4096; static char gs_command_str[4096]; - static CryLockT lock; + static AZStd::recursive_mutex lock; gEnv->pSystem->OnAssert(szCondition, gs_szMessage, szFile, line); @@ -80,7 +80,7 @@ bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, b if (!gEnv->bNoAssertDialog && !gEnv->bIgnoreAllAsserts) { - CryAutoLock< CryLockT > lk (lock); + AZStd::lock_guard lk (lock); snprintf(gs_command_str, max_len, "xterm -geometry 100x20 -n 'Assert Dialog [Linux Launcher]' -T 'Assert Dialog [Linux Launcher]' -e 'BinLinux/assert_term \"%s\" \"%s\" %d \"%s\"; echo \"$?\" > .assert_return'", szCondition, (file_len > 60) ? szFile + (file_len - 61) : szFile, line, gs_szMessage); int ret = system(gs_command_str); diff --git a/Code/Legacy/CryCommon/CryAssert_Mac.h b/Code/Legacy/CryCommon/CryAssert_Mac.h index ce65b352ab..f0a893630e 100644 --- a/Code/Legacy/CryCommon/CryAssert_Mac.h +++ b/Code/Legacy/CryCommon/CryAssert_Mac.h @@ -70,8 +70,6 @@ bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, b static const int max_len = 4096; static char gs_command_str[4096]; - static CryLockT lock; - gEnv->pSystem->OnAssert(szCondition, gs_szMessage, szFile, line); size_t file_len = strlen(szFile); diff --git a/Code/Legacy/CryCommon/IMaterial.h b/Code/Legacy/CryCommon/IMaterial.h index 1faee0eef9..97a5100018 100644 --- a/Code/Legacy/CryCommon/IMaterial.h +++ b/Code/Legacy/CryCommon/IMaterial.h @@ -432,8 +432,6 @@ struct IMaterial virtual uint32 GetDccMaterialHash() const = 0; virtual void SetDccMaterialHash(uint32 hash) = 0; - virtual CryCriticalSection& GetSubMaterialResizeLock() = 0; - virtual void UpdateShaderItems() = 0; // diff --git a/Code/Legacy/CryCommon/MultiThread_Containers.h b/Code/Legacy/CryCommon/MultiThread_Containers.h index 23f7cd1e0c..8a60adfa6b 100644 --- a/Code/Legacy/CryCommon/MultiThread_Containers.h +++ b/Code/Legacy/CryCommon/MultiThread_Containers.h @@ -34,7 +34,7 @@ namespace CryMT public: typedef T value_type; typedef std::vector container_type; - typedef CryAutoCriticalSection AutoLock; + typedef AZStd::lock_guard AutoLock; ////////////////////////////////////////////////////////////////////////// // std::queue interface @@ -46,7 +46,7 @@ namespace CryMT // classic pop function of queue should not be used for thread safety, use try_pop instead //void pop() { AutoLock lock(m_cs); return v.erase(v.begin()); }; - CryCriticalSection& get_lock() const { return m_cs; } + AZStd::recursive_mutex& get_lock() const { return m_cs; } bool empty() const { AutoLock lock(m_cs); return v.empty(); } int size() const { AutoLock lock(m_cs); return v.size(); } @@ -92,7 +92,7 @@ namespace CryMT } private: container_type v; - mutable CryCriticalSection m_cs; + mutable AZStd::recursive_mutex m_cs; }; }; // namespace CryMT diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.h b/Code/Legacy/CrySystem/LocalizedStringManager.h index 581a657c81..6916dee3c3 100644 --- a/Code/Legacy/CrySystem/LocalizedStringManager.h +++ b/Code/Legacy/CrySystem/LocalizedStringManager.h @@ -309,8 +309,8 @@ private: TLocalizationBitfield m_availableLocalizations; //Lock for - mutable CryCriticalSection m_cs; - typedef CryAutoCriticalSection AutoLock; + mutable AZStd::mutex m_cs; + typedef AZStd::lock_guard AutoLock; }; diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp index 96bc29b58a..e7ba8f5ba7 100644 --- a/Code/Legacy/CrySystem/Log.cpp +++ b/Code/Legacy/CrySystem/Log.cpp @@ -32,17 +32,6 @@ #include #endif - -// Only accept logging from the main thread. -#ifdef WIN32 - -#define THREAD_SAFE_LOG -//#define THREAD_SAFE_LOG CryAutoCriticalSection scope_lock(m_logCriticalSection); - -#else -#define THREAD_SAFE_LOG -#endif //WIN32 - #define LOG_BACKUP_PATH "@log@/LogBackups" #if defined(IOS) @@ -822,13 +811,13 @@ void CLog::PushAssetScopeName(const char* sAssetType, const char* sName) SAssetScopeInfo as; as.sType = sAssetType; as.sName = sName; - CryAutoCriticalSection scope_lock(m_assetScopeQueueLock); + AZStd::lock_guard scope_lock(m_assetScopeQueueLock); m_assetScopeQueue.push_back(as); } void CLog::PopAssetScopeName() { - CryAutoCriticalSection scope_lock(m_assetScopeQueueLock); + AZStd::lock_guard scope_lock(m_assetScopeQueueLock); assert(!m_assetScopeQueue.empty()); if (!m_assetScopeQueue.empty()) { @@ -839,7 +828,7 @@ void CLog::PopAssetScopeName() ////////////////////////////////////////////////////////////////////////// const char* CLog::GetAssetScopeString() { - CryAutoCriticalSection scope_lock(m_assetScopeQueueLock); + AZStd::lock_guard scope_lock(m_assetScopeQueueLock); m_assetScopeString.clear(); for (size_t i = 0; i < m_assetScopeQueue.size(); i++) @@ -1470,7 +1459,7 @@ void CLog::Update() { if (!m_threadSafeMsgQueue.empty()) { - CryAutoCriticalSection lock(m_threadSafeMsgQueue.get_lock()); // Get the lock and hold onto it until we clear the entire queue (prevents other threads adding more things in while we clear it) + AZStd::lock_guard lock(m_threadSafeMsgQueue.get_lock()); // Get the lock and hold onto it until we clear the entire queue (prevents other threads adding more things in while we clear it) // Must be called from main thread SLogMsg msg; while (m_threadSafeMsgQueue.try_pop(msg)) diff --git a/Code/Legacy/CrySystem/Log.h b/Code/Legacy/CrySystem/Log.h index 5b1956b12f..d6b6dcea3e 100644 --- a/Code/Legacy/CrySystem/Log.h +++ b/Code/Legacy/CrySystem/Log.h @@ -168,7 +168,7 @@ private: // ------------------------------------------------------------------- }; std::vector m_assetScopeQueue; - CryCriticalSection m_assetScopeQueueLock; + AZStd::mutex m_assetScopeQueueLock; string m_assetScopeString; #endif @@ -176,8 +176,6 @@ private: // ------------------------------------------------------------------- IConsole* m_pConsole; // - CryCriticalSection m_logCriticalSection; - struct SLogHistoryItem { char str[MAX_WARNING_LENGTH]; diff --git a/Code/Legacy/CrySystem/SystemEventDispatcher.cpp b/Code/Legacy/CrySystem/SystemEventDispatcher.cpp index eb8113c501..525bf1a005 100644 --- a/Code/Legacy/CrySystem/SystemEventDispatcher.cpp +++ b/Code/Legacy/CrySystem/SystemEventDispatcher.cpp @@ -17,17 +17,17 @@ CSystemEventDispatcher::CSystemEventDispatcher() bool CSystemEventDispatcher::RegisterListener(ISystemEventListener* pListener) { - m_listenerRegistrationLock.Lock(); + m_listenerRegistrationLock.lock(); bool ret = m_listeners.Add(pListener); - m_listenerRegistrationLock.Unlock(); + m_listenerRegistrationLock.unlock(); return ret; } bool CSystemEventDispatcher::RemoveListener(ISystemEventListener* pListener) { - m_listenerRegistrationLock.Lock(); + m_listenerRegistrationLock.lock(); m_listeners.Remove(pListener); - m_listenerRegistrationLock.Unlock(); + m_listenerRegistrationLock.unlock(); return true; } @@ -35,12 +35,12 @@ bool CSystemEventDispatcher::RemoveListener(ISystemEventListener* pListener) ////////////////////////////////////////////////////////////////////////// void CSystemEventDispatcher::OnSystemEventAnyThread(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) { - m_listenerRegistrationLock.Lock(); + m_listenerRegistrationLock.lock(); for (TSystemEventListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) { notifier->OnSystemEventAnyThread(event, wparam, lparam); } - m_listenerRegistrationLock.Unlock(); + m_listenerRegistrationLock.unlock(); } diff --git a/Code/Legacy/CrySystem/SystemEventDispatcher.h b/Code/Legacy/CrySystem/SystemEventDispatcher.h index 37ce170abd..a5d33b2542 100644 --- a/Code/Legacy/CrySystem/SystemEventDispatcher.h +++ b/Code/Legacy/CrySystem/SystemEventDispatcher.h @@ -46,7 +46,7 @@ private: typedef CryMT::queue TSystemEventQueue; TSystemEventQueue m_systemEventQueue; - CryCriticalSection m_listenerRegistrationLock; + AZStd::recursive_mutex m_listenerRegistrationLock; }; #endif // CRYINCLUDE_CRYSYSTEM_SYSTEMEVENTDISPATCHER_H From ccc4f27129a7a98fe7cab82eb66e44ac23ae9067 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Tue, 10 Aug 2021 21:09:55 -0700 Subject: [PATCH 111/205] Changed check for latest garbage to a for loop. Signed-off-by: dmcdiar --- Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h index 3f9fed056f..cd8a85a385 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h @@ -180,15 +180,16 @@ namespace AZ m_pendingGarbage.push_back({ AZStd::move(m_pendingObjects), m_currentIteration }); } - if (m_pendingNotifies.size()) + if (!m_pendingNotifies.empty()) { - if (m_pendingGarbage.size()) + if (!m_pendingGarbage.empty()) { // find the newest garbage entry and add any pending notifies Garbage& latestGarbage = m_pendingGarbage.front(); size_t latestGarbageAge = m_currentIteration - latestGarbage.m_collectIteration; - size_t i = 1; - while (i < m_pendingGarbage.size()) + + // check the rest of the entries to see if they are newer + for (size_t i = 1; i < m_pendingGarbage.size(); ++i) { size_t age = m_currentIteration - m_pendingGarbage[i].m_collectIteration; if (age < latestGarbageAge) From 6f2b7baae8032203e5466384c255e1e3ea5bbda3 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Tue, 10 Aug 2021 21:27:22 -0700 Subject: [PATCH 112/205] [redcode/crythread-2nd-pass] removed CryThread*.h files Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Editor/Include/IObjectManager.h | 1 + Code/Editor/Objects/ObjectLoader.h | 2 + Code/Editor/QtUtil.h | 1 + Code/Editor/Util/FileUtil.h | 1 - Code/Editor/Util/Variable.h | 2 + Code/Legacy/CryCommon/CryThread.h | 110 ---------- Code/Legacy/CryCommon/CryThreadImpl.h | 29 --- Code/Legacy/CryCommon/CryThreadImpl_windows.h | 78 ------- Code/Legacy/CryCommon/CryThread_pthreads.h | 199 ------------------ Code/Legacy/CryCommon/CryThread_windows.h | 95 --------- Code/Legacy/CryCommon/Synchronization.h | 1 - Code/Legacy/CryCommon/crycommon_files.cmake | 5 - Code/Legacy/CryCommon/platform.h | 1 - Code/Legacy/CryCommon/platform_impl.cpp | 4 - Code/Legacy/CrySystem/Log.h | 1 - Code/Legacy/CrySystem/SystemEventDispatcher.h | 1 + 16 files changed, 7 insertions(+), 524 deletions(-) delete mode 100644 Code/Legacy/CryCommon/CryThread.h delete mode 100644 Code/Legacy/CryCommon/CryThreadImpl.h delete mode 100644 Code/Legacy/CryCommon/CryThreadImpl_windows.h delete mode 100644 Code/Legacy/CryCommon/CryThread_pthreads.h delete mode 100644 Code/Legacy/CryCommon/CryThread_windows.h diff --git a/Code/Editor/Include/IObjectManager.h b/Code/Editor/Include/IObjectManager.h index ce9d69681b..efc1955a56 100644 --- a/Code/Editor/Include/IObjectManager.h +++ b/Code/Editor/Include/IObjectManager.h @@ -14,6 +14,7 @@ #include #include #include +#include // forward declarations. class CEntityObject; diff --git a/Code/Editor/Objects/ObjectLoader.h b/Code/Editor/Objects/ObjectLoader.h index ccfaeb78f0..fc526970dd 100644 --- a/Code/Editor/Objects/ObjectLoader.h +++ b/Code/Editor/Objects/ObjectLoader.h @@ -15,6 +15,8 @@ #include "Util/GuidUtil.h" #include "ErrorReport.h" +#include + class CPakFile; class CErrorRecord; struct IObjectManager; diff --git a/Code/Editor/QtUtil.h b/Code/Editor/QtUtil.h index bb1f8ba427..69fe03baa1 100644 --- a/Code/Editor/QtUtil.h +++ b/Code/Editor/QtUtil.h @@ -12,6 +12,7 @@ #include #include #include "UnicodeFunctions.h" +#include #include #include diff --git a/Code/Editor/Util/FileUtil.h b/Code/Editor/Util/FileUtil.h index 3be66d6e96..6b2800dd27 100644 --- a/Code/Editor/Util/FileUtil.h +++ b/Code/Editor/Util/FileUtil.h @@ -9,7 +9,6 @@ #pragma once -#include "CryThread.h" #include "StringUtils.h" #include "../Include/SandboxAPI.h" #include diff --git a/Code/Editor/Util/Variable.h b/Code/Editor/Util/Variable.h index 83afee0924..ecd54e42ae 100644 --- a/Code/Editor/Util/Variable.h +++ b/Code/Editor/Util/Variable.h @@ -22,6 +22,8 @@ AZ_PUSH_DISABLE_WARNING(4458, "-Wunknown-warning-option") AZ_POP_DISABLE_WARNING #include +#include + inline const char* to_c_str(const char* str) { return str; } #define MAX_VAR_STRING_LENGTH 4096 diff --git a/Code/Legacy/CryCommon/CryThread.h b/Code/Legacy/CryCommon/CryThread.h deleted file mode 100644 index fcd7be16ba..0000000000 --- a/Code/Legacy/CryCommon/CryThread.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Public include file for the multi-threading API. - - -#pragma once - - -// Include basic multithread primitives. -#include "MultiThread.h" -#include "BitFiddling.h" -#include -////////////////////////////////////////////////////////////////////////// -// Lock types: -// -// CRYLOCK_FAST -// A fast potentially (non-recursive) mutex. -// CRYLOCK_RECURSIVE -// A recursive mutex. -////////////////////////////////////////////////////////////////////////// -enum CryLockType -{ - CRYLOCK_FAST = 1, - CRYLOCK_RECURSIVE = 2, -}; - -#define CRYLOCK_HAVE_FASTLOCK 1 - -///////////////////////////////////////////////////////////////////////////// -// -// Primitive locks and conditions. -// -// Primitive locks are represented by instance of class CryLockT -// -// -template -class CryLockT -{ - /* Unsupported lock type. */ -}; - -////////////////////////////////////////////////////////////////////////// -// Typedefs. -////////////////////////////////////////////////////////////////////////// -typedef CryLockT CryCriticalSection; -typedef CryLockT CryCriticalSectionNonRecursive; -////////////////////////////////////////////////////////////////////////// - - -////////////////////////////////////////////////////////////////////////// -// -// CryAutoCriticalSection implements a helper class to automatically -// lock critical section in constructor and release on destructor. -// -////////////////////////////////////////////////////////////////////////// -template -class CryAutoLock -{ -private: - LockClass* m_pLock; - - CryAutoLock(); - CryAutoLock(const CryAutoLock&); - CryAutoLock& operator = (const CryAutoLock&); - -public: - CryAutoLock(LockClass& Lock) - : m_pLock(&Lock) { m_pLock->Lock(); } - CryAutoLock(const LockClass& Lock) - : m_pLock(const_cast(&Lock)) { m_pLock->Lock(); } - ~CryAutoLock() { m_pLock->Unlock(); } -}; - -////////////////////////////////////////////////////////////////////////// -// -// Auto critical section is the most commonly used type of auto lock. -// -////////////////////////////////////////////////////////////////////////// -typedef CryAutoLock CryAutoCriticalSection; - -/////////////////////////////////////////////////////////////////////////////// -// Include architecture specific code. -#if AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS -#include -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) -#include -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryThread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// Put other platform specific includes here! -#endif - -#if !defined _CRYTHREAD_CONDLOCK_GLITCH -typedef CryLockT CryMutex; -#endif // !_CRYTHREAD_CONDLOCK_GLITCH - -// Include all multithreading containers. -#include "MultiThread_Containers.h" diff --git a/Code/Legacy/CryCommon/CryThreadImpl.h b/Code/Legacy/CryCommon/CryThreadImpl.h deleted file mode 100644 index 4ff2cc6438..0000000000 --- a/Code/Legacy/CryCommon/CryThreadImpl.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - - -#include - -// Include architecture specific code. -#if defined(LINUX) || defined(APPLE) -// noting to include -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) -#include -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryThreadImpl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// Put other platform specific includes here! -#endif diff --git a/Code/Legacy/CryCommon/CryThreadImpl_windows.h b/Code/Legacy/CryCommon/CryThreadImpl_windows.h deleted file mode 100644 index 9157bde9bc..0000000000 --- a/Code/Legacy/CryCommon/CryThreadImpl_windows.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include -#include // for CreateSemaphore - - -////////////////////////////////////////////////////////////////////////// -// CryLock_WinMutex -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -CryLock_WinMutex::CryLock_WinMutex() - : m_hdl(CreateMutex(NULL, FALSE, NULL)) {} -CryLock_WinMutex::~CryLock_WinMutex() -{ - CloseHandle(m_hdl); -} - -////////////////////////////////////////////////////////////////////////// -void CryLock_WinMutex::Lock() -{ - WaitForSingleObject(m_hdl, INFINITE); -} - -////////////////////////////////////////////////////////////////////////// -void CryLock_WinMutex::Unlock() -{ - ReleaseMutex(m_hdl); -} - -////////////////////////////////////////////////////////////////////////// -bool CryLock_WinMutex::TryLock() -{ - return WaitForSingleObject(m_hdl, 0) != WAIT_TIMEOUT; -} - -////////////////////////////////////////////////////////////////////////// -// CryLock_CritSection -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -CryLock_CritSection::CryLock_CritSection() -{ - InitializeCriticalSection((CRITICAL_SECTION*)&m_cs); -} - -////////////////////////////////////////////////////////////////////////// -CryLock_CritSection::~CryLock_CritSection() -{ - DeleteCriticalSection((CRITICAL_SECTION*)&m_cs); -} - -////////////////////////////////////////////////////////////////////////// -void CryLock_CritSection::Lock() -{ - EnterCriticalSection((CRITICAL_SECTION*)&m_cs); -} - -////////////////////////////////////////////////////////////////////////// -void CryLock_CritSection::Unlock() -{ - LeaveCriticalSection((CRITICAL_SECTION*)&m_cs); -} - -////////////////////////////////////////////////////////////////////////// -bool CryLock_CritSection::TryLock() -{ - return TryEnterCriticalSection((CRITICAL_SECTION*)&m_cs) != FALSE; -} diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h deleted file mode 100644 index 9e04784f3f..0000000000 --- a/Code/Legacy/CryCommon/CryThread_pthreads.h +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include - - -#include -#include -#include -#include -#include - -#include -#include -#include - -// Section dictionary -#if defined(AZ_RESTRICTED_PLATFORM) -#define CRYTHREAD_PTHREADS_H_SECTION_REGISTER_THREAD 1 -#define CRYTHREAD_PTHREADS_H_SECTION_TRAITS 2 -#define CRYTHREAD_PTHREADS_H_SECTION_PTHREADCOND 3 -#define CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_CONSTRUCT 4 -#define CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_DESTROY 5 -#define CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_ACQUIRE 6 -#define CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_RELEASE 7 -#define CRYTHREAD_PTHREADS_H_SECTION_TRY_RLOCK 8 -#define CRYTHREAD_PTHREADS_H_SECTION_TRY_WLOCK 9 -#define CRYTHREAD_PTHREADS_H_SECTION_START_RUNNABLE 10 -#define CRYTHREAD_PTHREADS_H_SECTION_START_CPUMASK 11 -#define CRYTHREAD_PTHREADS_H_SECTION_START_CPUMASK_POSTCREATE 12 -#define CRYTHREAD_PTHREADS_H_SECTION_SETCPUMASK 13 -#define CRYTHREAD_PTHREADS_H_SECTION_START_RUNNABLE_CPUMASK_POSTCREATE 14 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_REGISTER_THREAD - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#endif - -#if defined(APPLE) || defined(ANDROID) -// PTHREAD_MUTEX_FAST_NP is only defined by Pthreads-w32, thus not on MAC - #define PTHREAD_MUTEX_FAST_NP PTHREAD_MUTEX_NORMAL -#endif - -#if !defined _CRYTHREAD_HAVE_LOCK -template -class _PthreadLockBase; - -template -class _PthreadLockAttr -{ - friend class _PthreadLockBase; - -protected: - _PthreadLockAttr() - { - pthread_mutexattr_init(&m_Attr); - pthread_mutexattr_settype(&m_Attr, PthreadMutexType); - } - ~_PthreadLockAttr() - { - pthread_mutexattr_destroy(&m_Attr); - } - pthread_mutexattr_t m_Attr; -}; - -template -class _PthreadLockBase -{ -protected: - static pthread_mutexattr_t& GetAttr() - { - static _PthreadLockAttr m_Attr; - return m_Attr.m_Attr; - } -}; - -template -class _PthreadLock - : public _PthreadLockBase -{ - //#if defined(_DEBUG) -public: - //#endif - pthread_mutex_t m_Lock; - -public: - _PthreadLock() - : LockCount(0) - { - pthread_mutex_init( - &m_Lock, - &_PthreadLockBase::GetAttr()); - } - ~_PthreadLock() { pthread_mutex_destroy(&m_Lock); } - - void Lock() { pthread_mutex_lock(&m_Lock); CryInterlockedIncrement(&LockCount); } - - bool TryLock() - { - const int rc = pthread_mutex_trylock(&m_Lock); - if (0 == rc) - { - CryInterlockedIncrement(&LockCount); - return true; - } - return false; - } - - void Unlock() { CryInterlockedDecrement(&LockCount); pthread_mutex_unlock(&m_Lock); } - - // Get the POSIX pthread_mutex_t. - // Warning: - // This method will not be available in the Win32 port of CryThread. - pthread_mutex_t& Get_pthread_mutex_t() { return m_Lock; } - - bool IsLocked() - { -#if defined(LINUX) || defined(APPLE) - // implementation taken from CrysisWars - return LockCount > 0; -#else - return true; -#endif - } - -private: - volatile int LockCount; -}; - -#if defined CRYLOCK_HAVE_FASTLOCK - #if defined(_DEBUG) && defined(PTHREAD_MUTEX_ERRORCHECK_NP) -template<> -class CryLockT - : public _PthreadLock, PTHREAD_MUTEX_ERRORCHECK_NP> - #else -template<> -class CryLockT - : public _PthreadLock, PTHREAD_MUTEX_FAST_NP> - #endif -{ - CryLockT(const CryLockT&); - void operator = (const CryLockT&); - -public: - CryLockT() { } -}; -#endif // CRYLOCK_HAVE_FASTLOCK - -template<> -class CryLockT - : public _PthreadLock, PTHREAD_MUTEX_RECURSIVE> -{ - CryLockT(const CryLockT&); - void operator = (const CryLockT&); - -public: - CryLockT() { } -}; - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_TRAITS - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#else -#if !defined(LINUX) && !defined(APPLE) -#define CRYTHREAD_PTHREADS_H_TRAIT_DEFINE_CRYMUTEX 1 -#endif -#endif - -#if CRYTHREAD_PTHREADS_H_TRAIT_DEFINE_CRYMUTEX -#if defined CRYLOCK_HAVE_FASTLOCK -class CryMutex - : public CryLockT -{ -}; -#else -class CryMutex - : public CryLockT -{ -}; -#endif -#endif // CRYTHREAD_PTHREADS_TRAIT_DEFINE_CRYMUTEX - -#define _CRYTHREAD_HAVE_LOCK 1 - -#endif // !defined _CRYTHREAD_HAVE_LOCK - -#include "MemoryAccess.h" diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h deleted file mode 100644 index 5f83aa48e0..0000000000 --- a/Code/Legacy/CryCommon/CryThread_windows.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define CRYTHREAD_WINDOWS_H_SECTION_1 1 -#define CRYTHREAD_WINDOWS_H_SECTION_2 2 -#endif - -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// from winnt.h -struct CRY_CRITICAL_SECTION -{ - void* DebugInfo; - long LockCount; - long RecursionCount; - threadID OwningThread; - void* LockSemaphore; - unsigned long* SpinCount; // force size on 64-bit systems when packed -}; - -////////////////////////////////////////////////////////////////////////// - -// kernel mutex - don't use... use CryMutex instead -class CryLock_WinMutex -{ -public: - CryLock_WinMutex(); - ~CryLock_WinMutex(); - - void Lock(); - void Unlock(); - bool TryLock(); - - void* _get_win32_handle() { return m_hdl; } - -private: - CryLock_WinMutex(const CryLock_WinMutex&); - CryLock_WinMutex& operator = (const CryLock_WinMutex&); - -private: - void* m_hdl; -}; - -// critical section... don't use... use CryCriticalSection instead -class CryLock_CritSection -{ -public: - CryLock_CritSection(); - ~CryLock_CritSection(); - - void Lock(); - void Unlock(); - bool TryLock(); - - bool IsLocked() - { - return m_cs.RecursionCount > 0 && m_cs.OwningThread == CryGetCurrentThreadId(); - } - -private: - CryLock_CritSection(const CryLock_CritSection&); - CryLock_CritSection& operator = (const CryLock_CritSection&); - -private: - CRY_CRITICAL_SECTION m_cs; -}; - -template <> -class CryLockT - : public CryLock_CritSection -{ -}; -template <> -class CryLockT - : public CryLock_CritSection -{ -}; -class CryMutex - : public CryLock_WinMutex -{ -}; -#define _CRYTHREAD_CONDLOCK_GLITCH 1 diff --git a/Code/Legacy/CryCommon/Synchronization.h b/Code/Legacy/CryCommon/Synchronization.h index 4caa466cb8..3bac215998 100644 --- a/Code/Legacy/CryCommon/Synchronization.h +++ b/Code/Legacy/CryCommon/Synchronization.h @@ -22,7 +22,6 @@ //--------------------------------------------------------------------------- #include "MultiThread.h" -#include "CryThread.h" namespace stl { diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index 487d08b13c..d9d4493632 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -89,8 +89,6 @@ set(FILES CrySizer.h CryString.h CrySystemBus.h - CryThread.h - CryThreadImpl.h CryTypeInfo.h CryVersion.h FrameProfiler.h @@ -160,9 +158,6 @@ set(FILES CryAssert_Mac.h CryLibrary.cpp CryLibrary.h - CryThread_pthreads.h - CryThread_windows.h - CryThreadImpl_windows.h CryWindows.h Linux32Specific.h Linux64Specific.h diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 851da316e0..9f6e8b212d 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -732,7 +732,6 @@ typedef int socklen_t; // Include MultiThreading support. -#include "CryThread.h" #include "MultiThread.h" // In RELEASE disable printf and fprintf diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index 09d7493ae7..e16b18bc06 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -38,10 +38,6 @@ struct SSystemGlobalEnvironment* gEnv = nullptr; #include AZ_RESTRICTED_FILE(platform_impl_h) #endif -////////////////////////////////////////////////////////////////////////// -// If not in static library. -#include - #if defined(WIN32) || defined(WIN64) void CryPureCallHandler() { diff --git a/Code/Legacy/CrySystem/Log.h b/Code/Legacy/CrySystem/Log.h index d6b6dcea3e..447186e613 100644 --- a/Code/Legacy/CrySystem/Log.h +++ b/Code/Legacy/CrySystem/Log.h @@ -10,7 +10,6 @@ #pragma once #include -#include #include #include diff --git a/Code/Legacy/CrySystem/SystemEventDispatcher.h b/Code/Legacy/CrySystem/SystemEventDispatcher.h index a5d33b2542..550292add7 100644 --- a/Code/Legacy/CrySystem/SystemEventDispatcher.h +++ b/Code/Legacy/CrySystem/SystemEventDispatcher.h @@ -14,6 +14,7 @@ #include #include +#include class CSystemEventDispatcher : public ISystemEventDispatcher From adf7a34ef58196fac2863509d35077efb19a050e Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Tue, 10 Aug 2021 23:07:23 -0700 Subject: [PATCH 113/205] Got PassBuilder shader dependency working and removed critical flag from shader builder Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- .../Editor/ShaderVariantAssetBuilder.cpp | 2 +- .../AuxGeom/DynamicPrimitiveProcessor.cpp | 2 +- .../Source/AuxGeom/FixedShapeProcessor.cpp | 4 +- .../DiffuseProbeGridBlendDistancePass.cpp | 2 +- .../DiffuseProbeGridBlendIrradiancePass.cpp | 2 +- .../DiffuseProbeGridBorderUpdatePass.cpp | 2 +- .../DiffuseProbeGridClassificationPass.cpp | 2 +- .../DiffuseProbeGridFeatureProcessor.cpp | 2 +- .../DiffuseProbeGridRayTracingPass.cpp | 6 +- .../DiffuseProbeGridRelocationPass.cpp | 2 +- .../DiffuseProbeGridRenderPass.cpp | 2 +- .../Common/Code/Source/ImGui/ImGuiPass.cpp | 2 +- .../ReflectionProbeFeatureProcessor.cpp | 2 +- .../ReflectionScreenSpaceBlurPass.cpp | 4 +- .../Code/Include/Atom/RPI.Public/RPIUtils.h | 4 +- .../Source/RPI.Builders/Pass/PassBuilder.cpp | 127 +++++++----------- .../RPI.Public/Pass/AttachmentReadback.cpp | 2 +- .../RPI/Code/Source/RPI.Public/RPIUtils.cpp | 28 +++- Gems/LyShine/Code/Source/Draw2d.cpp | 2 +- Gems/LyShine/Code/Source/UiRenderer.cpp | 2 +- 20 files changed, 103 insertions(+), 98 deletions(-) diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp index ee02ae8452..1da4623774 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp @@ -321,7 +321,7 @@ namespace AZ AssetBuilderSDK::JobDescriptor jobDescriptor; jobDescriptor.m_priority = -5000; - jobDescriptor.m_critical = true; + jobDescriptor.m_critical = false; jobDescriptor.m_jobKey = ShaderVariantAssetBuilderJobKey; jobDescriptor.SetPlatformIdentifier(info.m_identifier.data()); diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp index ea726dd914..3a7d50d2a9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp @@ -322,7 +322,7 @@ namespace AZ { const char* auxGeomWorldShaderFilePath = "Shaders/auxgeom/auxgeomworld.azshader"; - m_shader = RPI::LoadShader(auxGeomWorldShaderFilePath); + m_shader = RPI::LoadCriticalShader(auxGeomWorldShaderFilePath); if (!m_shader) { AZ_Error("DynamicPrimitiveProcessor", false, "Failed to get shader"); diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp index 63feee115d..f2b3a93a53 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp @@ -1385,9 +1385,9 @@ namespace AZ const char* litObjectShaderFilePath = "Shaders/auxgeom/auxgeomobjectlit.azshader"; // constant color shader - m_unlitShader = RPI::LoadShader(unlitObjectShaderFilePath); + m_unlitShader = RPI::LoadCriticalShader(unlitObjectShaderFilePath); // direction light shader - m_litShader = RPI::LoadShader(litObjectShaderFilePath); + m_litShader = RPI::LoadCriticalShader(litObjectShaderFilePath); if (m_unlitShader.get() == nullptr || m_litShader == nullptr) { diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp index 5fe472c7f8..a3927b802d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp @@ -38,7 +38,7 @@ namespace AZ // load shader // Note: the shader may not be available on all platforms AZStd::string shaderFilePath = "Shaders/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistance.azshader"; - m_shader = RPI::LoadShader(shaderFilePath); + m_shader = RPI::LoadCriticalShader(shaderFilePath); if (m_shader == nullptr) { return; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp index c1b6653024..6ff8bdd867 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp @@ -38,7 +38,7 @@ namespace AZ // load shader // Note: the shader may not be available on all platforms AZStd::string shaderFilePath = "Shaders/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiance.azshader"; - m_shader = RPI::LoadShader(shaderFilePath); + m_shader = RPI::LoadCriticalShader(shaderFilePath); if (m_shader == nullptr) { return; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp index 0d47b3bd54..ddfe0f11b1 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp @@ -51,7 +51,7 @@ namespace AZ { // load shader // Note: the shader may not be available on all platforms - shader = RPI::LoadShader(shaderFilePath); + shader = RPI::LoadCriticalShader(shaderFilePath); if (shader == nullptr) { return; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp index bb7f87cc61..4c6b07d780 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp @@ -42,7 +42,7 @@ namespace AZ // load shader // Note: the shader may not be available on all platforms AZStd::string shaderFilePath = "Shaders/DiffuseGlobalIllumination/DiffuseProbeGridClassification.azshader"; - m_shader = RPI::LoadShader(shaderFilePath); + m_shader = RPI::LoadCriticalShader(shaderFilePath); if (m_shader == nullptr) { return; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp index f4df4f126a..378e1923f7 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp @@ -74,7 +74,7 @@ namespace AZ // load shader // Note: the shader may not be available on all platforms - Data::Instance shader = RPI::LoadShader("Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRender.azshader"); + Data::Instance shader = RPI::LoadCriticalShader("Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRender.azshader"); if (shader) { m_probeGridRenderData.m_drawListTag = shader->GetDrawListTag(); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.cpp index dd8985935f..958823ef91 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingPass.cpp @@ -52,7 +52,7 @@ namespace AZ // load the ray tracing shader // Note: the shader may not be available on all platforms AZStd::string shaderFilePath = "Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRayTracing.azshader"; - m_rayTracingShader = RPI::LoadShader(shaderFilePath); + m_rayTracingShader = RPI::LoadCriticalShader(shaderFilePath); if (m_rayTracingShader == nullptr) { return; @@ -64,7 +64,7 @@ namespace AZ // closest hit shader AZStd::string closestHitShaderFilePath = "Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingClosestHit.azshader"; - m_closestHitShader = RPI::LoadShader(closestHitShaderFilePath); + m_closestHitShader = RPI::LoadCriticalShader(closestHitShaderFilePath); auto closestHitShaderVariant = m_closestHitShader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId); RHI::PipelineStateDescriptorForRayTracing closestHitShaderDescriptor; @@ -72,7 +72,7 @@ namespace AZ // miss shader AZStd::string missShaderFilePath = "Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRayTracingMiss.azshader"; - m_missShader = RPI::LoadShader(missShaderFilePath); + m_missShader = RPI::LoadCriticalShader(missShaderFilePath); auto missShaderVariant = m_missShader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId); RHI::PipelineStateDescriptorForRayTracing missShaderDescriptor; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp index 56ae50069e..54cf9783cd 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp @@ -42,7 +42,7 @@ namespace AZ // load shader // Note: the shader may not be available on all platforms AZStd::string shaderFilePath = "Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRelocation.azshader"; - m_shader = RPI::LoadShader(shaderFilePath); + m_shader = RPI::LoadCriticalShader(shaderFilePath); if (m_shader == nullptr) { return; diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.cpp index 55d8ca5cba..a4cc101222 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRenderPass.cpp @@ -30,7 +30,7 @@ namespace AZ // create the shader resource group // Note: the shader may not be available on all platforms AZStd::string shaderFilePath = "Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRender.azshader"; - m_shader = RPI::LoadShader(shaderFilePath); + m_shader = RPI::LoadCriticalShader(shaderFilePath); if (m_shader == nullptr) { return; diff --git a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp index 821b9c52b4..cd781390a3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp @@ -446,7 +446,7 @@ namespace AZ } { - m_shader = RPI::LoadShader(ImguiShaderFilePath); + m_shader = RPI::LoadCriticalShader(ImguiShaderFilePath); m_pipelineState = aznew RPI::PipelineStateForDraw; m_pipelineState->Init(m_shader); diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp index a9078e1dd8..c0e25e3da9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp @@ -487,7 +487,7 @@ namespace AZ RHI::DrawListTag& drawListTag) { // load shader - shader = RPI::LoadShader(filePath); + shader = RPI::LoadCriticalShader(filePath); AZ_Error("ReflectionProbeFeatureProcessor", shader, "Failed to find asset for shader [%s]", filePath); // store drawlist tag diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp index f0f947ba03..4f5caca108 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp @@ -52,7 +52,7 @@ namespace AZ // load shaders AZStd::string verticalBlurShaderFilePath = "Shaders/Reflections/ReflectionScreenSpaceBlurVertical.azshader"; - Data::Instance verticalBlurShader = RPI::LoadShader(verticalBlurShaderFilePath); + Data::Instance verticalBlurShader = RPI::LoadCriticalShader(verticalBlurShaderFilePath); if (verticalBlurShader == nullptr) { AZ_Error("PassSystem", false, "[ReflectionScreenSpaceBlurPass '%s']: Failed to load shader '%s'!", GetPathName().GetCStr(), verticalBlurShaderFilePath.c_str()); @@ -60,7 +60,7 @@ namespace AZ } AZStd::string horizontalBlurShaderFilePath = "Shaders/Reflections/ReflectionScreenSpaceBlurHorizontal.azshader"; - Data::Instance horizontalBlurShader = RPI::LoadShader(horizontalBlurShaderFilePath); + Data::Instance horizontalBlurShader = RPI::LoadCriticalShader(horizontalBlurShaderFilePath); if (horizontalBlurShader == nullptr) { AZ_Error("PassSystem", false, "[ReflectionScreenSpaceBlurPass '%s']: Failed to load shader '%s'!", GetPathName().GetCStr(), horizontalBlurShaderFilePath.c_str()); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPIUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPIUtils.h index e6d2bdad82..a2972ff0fd 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPIUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPIUtils.h @@ -22,19 +22,21 @@ namespace AZ class Shader; //! Get the asset ID for a given shader file path - Data::AssetId GetShaderAssetId(const AZStd::string& shaderFilePath); + Data::AssetId GetShaderAssetId(const AZStd::string& shaderFilePath, bool isCritical = false); //! Finds a shader asset for the given shader asset ID. Optional shaderFilePath param for debugging. Data::Asset FindShaderAsset(Data::AssetId shaderAssetId, const AZStd::string& shaderFilePath = ""); //! Finds a shader asset for the given shader file path Data::Asset FindShaderAsset(const AZStd::string& shaderFilePath); + Data::Asset FindCriticalShaderAsset(const AZStd::string& shaderFilePath); //! Loads a shader for the given shader asset ID. Optional shaderFilePath param for debugging. Data::Instance LoadShader(Data::AssetId shaderAssetId, const AZStd::string& shaderFilePath = ""); //! Loads a shader for the given shader file path Data::Instance LoadShader(const AZStd::string& shaderFilePath); + Data::Instance LoadCriticalShader(const AZStd::string& shaderFilePath); //! Loads a streaming image asset for the given file path Data::Instance LoadStreamingTexture(AZStd::string_view path); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp index f582f3ba04..a803ecf31a 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp @@ -67,6 +67,7 @@ namespace AZ // --- Code related to dependency shader asset handling --- + // Helper class to pass parameters to the AddDependency and FindReferencedAssets functions below struct FindPassReferenceAssetParams { void* passAssetObject; @@ -77,50 +78,28 @@ namespace AZ const char* jobKey; // Job key for adding job dependency }; - //! Adds all relevant dependencies for a referenced source file, considering that the path might be relative to the original file location or a full asset path. - //! This will usually include multiple source dependencies and a single job dependency, but will include only source dependencies if the file is not found. - //! Note the AssetBuilderSDK::JobDependency::m_platformIdentifier will not be set by this function. The calling code must set this value before passing back - //! to the AssetBuilderSDK::CreateJobsResponse. - void AddPossibleDependencies( - FindPassReferenceAssetParams& params, - AssetBuilderSDK::CreateJobsResponse& response, - AssetBuilderSDK::JobDescriptor& job) + // Helper function to get a file reference and create a corresponding job dependency + void AddDependency(FindPassReferenceAssetParams& params, AssetBuilderSDK::JobDescriptor* job) { - bool dependencyFileFound = false; + AZStd::string_view& file = params.dependencySourceFile; + AZ::Data::AssetInfo sourceInfo; + AZStd::string watchFolder; + bool fileFound = false; + AzToolsFramework::AssetSystemRequestBus::BroadcastResult(fileFound, &AzToolsFramework::AssetSystem::AssetSystemRequest::GetSourceInfoBySourcePath, file.data(), sourceInfo, watchFolder); - AZStd::vector possibleDependencies = RPI::AssetUtils::GetPossibleDepenencyPaths(params.passAssetSourceFile, params.dependencySourceFile); - for (auto& file : possibleDependencies) + if (fileFound) { - AssetBuilderSDK::SourceFileDependency sourceFileDependency; - sourceFileDependency.m_sourceFileDependencyPath = file; - response.m_sourceFileDependencyList.push_back(sourceFileDependency); - - // The first path found is the highest priority, and will have a job dependency, as this is the one - // the builder will actually use - if (!dependencyFileFound) - { - AZ::Data::AssetInfo sourceInfo; - AZStd::string watchFolder; - AzToolsFramework::AssetSystemRequestBus::BroadcastResult(dependencyFileFound, &AzToolsFramework::AssetSystem::AssetSystemRequest::GetSourceInfoBySourcePath, file.c_str(), sourceInfo, watchFolder); - - if (dependencyFileFound) - { - AssetBuilderSDK::JobDependency jobDependency; - jobDependency.m_jobKey = params.jobKey; - jobDependency.m_type = AssetBuilderSDK::JobDependencyType::Order; - jobDependency.m_sourceFile.m_sourceFileDependencyPath = file; - job.m_jobDependencyList.push_back(jobDependency); - } - } + AssetBuilderSDK::JobDependency jobDependency; + jobDependency.m_jobKey = params.jobKey; + jobDependency.m_type = AssetBuilderSDK::JobDependencyType::Order; + jobDependency.m_sourceFile.m_sourceFileDependencyPath = file; + job->m_jobDependencyList.push_back(jobDependency); + AZ_TracePrintf(PassBuilderName, "Creating job dependency on file [%s] \n", file.data()); } } // Helper function to find all assetId's and object references - bool FindPassReferencedAssets(FindPassReferenceAssetParams& params, - AZStd::unordered_set& referencedAssetList, - AssetBuilderSDK::CreateJobsResponse& response, - AssetBuilderSDK::JobDescriptor& job, - bool jobCreationPhase) + bool FindReferencedAssets(FindPassReferenceAssetParams& params, AssetBuilderSDK::JobDescriptor* job) { SerializeContext::ErrorHandler errorLogger; errorLogger.Reset(); @@ -141,10 +120,10 @@ namespace AZ const AZStd::string& path = assetReference->m_filePath; uint32_t subId = 0; - if (jobCreationPhase) + if (job != nullptr) // Create Job Phase { params.dependencySourceFile = path; - AddPossibleDependencies(params, response, job); + AddDependency(params, job); } else // Process Job Phase { @@ -161,12 +140,6 @@ namespace AZ } } } - - // If the asset ID is valid, add it as a dependency - if (assetReference->m_assetId.IsValid()) - { - referencedAssetList.insert(assetReference->m_assetId); - } } return true; }; @@ -196,15 +169,16 @@ namespace AZ void PassBuilder::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) const { + // --- Handle shutdown case --- + if (m_isShuttingDown) { response.m_result = AssetBuilderSDK::CreateJobsResultCode::ShuttingDown; return; } - AssetBuilderSDK::JobDescriptor job; + // --- Get serialization context --- - // Get serialization context SerializeContext* serializeContext = nullptr; ComponentApplicationBus::BroadcastResult(serializeContext, &ComponentApplicationBus::Events::GetSerializeContext); if (!serializeContext) @@ -213,7 +187,8 @@ namespace AZ return; } - // Load PassAsset + // --- Load PassAsset --- + AZStd::string fullPath; AzFramework::StringFunc::Path::ConstructFull(request.m_watchFolder.c_str(), request.m_sourceFile.c_str(), fullPath, true); @@ -227,7 +202,12 @@ namespace AZ return; } - // Find all Asset IDs we depend on + AssetBuilderSDK::JobDescriptor job; + job.m_jobKey = PassBuilderJobKey; + job.m_critical = true; // Passes are a critical part of the rendering system + + // --- Find all dependencies --- + AZStd::unordered_set dependentList; Uuid passAssetUuid = AzTypeInfo::Uuid(); @@ -238,30 +218,30 @@ namespace AZ params.serializeContext = serializeContext; params.jobKey = "Shader Asset"; - if (!FindPassReferencedAssets(params, dependentList, response, job, true)) + if (!FindReferencedAssets(params, &job)) { return; } + // --- Create a job per platform --- + for (const AssetBuilderSDK::PlatformInfo& platformInfo : request.m_enabledPlatforms) { - job.m_jobKey = PassBuilderJobKey; + for (auto& jobDependency : job.m_jobDependencyList) + { + jobDependency.m_platformIdentifier = platformInfo.m_identifier.c_str(); + } job.SetPlatformIdentifier(platformInfo.m_identifier.c_str()); - - // Passes are a critical part of the rendering system - job.m_critical = true; - response.m_createJobOutputs.push_back(job); } response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; } - - void PassBuilder::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response) const { - // Handle job cancellation and shutdown cases + // --- Handle job cancellation and shutdown cases --- + AssetBuilderSDK::JobCancelListener jobCancelListener(request.m_jobId); if (jobCancelListener.IsCancelled() || m_isShuttingDown) { @@ -269,7 +249,8 @@ namespace AZ return; } - // Get serialization context + // --- Get serialization context --- + SerializeContext* serializeContext = nullptr; ComponentApplicationBus::BroadcastResult(serializeContext, &ComponentApplicationBus::Events::GetSerializeContext); if (!serializeContext) @@ -278,7 +259,8 @@ namespace AZ return; } - // Load PassAsset + // --- Load PassAsset --- + PassAsset passAsset; AZ::Outcome loadResult = JsonSerializationUtils::LoadObjectFromFile(passAsset, request.m_fullPath); @@ -289,8 +271,8 @@ namespace AZ return; } - // Find all Asset IDs we depend on - AZStd::unordered_set dependentList; + // --- Find all dependencies --- + Uuid passAssetUuid = AzTypeInfo::Uuid(); FindPassReferenceAssetParams params; @@ -300,21 +282,20 @@ namespace AZ params.serializeContext = serializeContext; params.jobKey = "Shader Asset"; - AssetBuilderSDK::CreateJobsResponse dummyResponse; - AssetBuilderSDK::JobDescriptor dummyJob; - - if (!FindPassReferencedAssets(params, dependentList, dummyResponse, dummyJob, false)) + if (!FindReferencedAssets(params, nullptr)) { return; } - // Get destination file name and path + // --- Get destination file name and path --- + AZStd::string destFileName; AZStd::string destPath; AzFramework::StringFunc::Path::GetFullFileName(request.m_fullPath.c_str(), destFileName); AzFramework::StringFunc::Path::ConstructFull(request.m_tempDirPath.c_str(), destFileName.c_str(), destPath, true); - // Save the asset to binary format for production + // --- Save the asset to binary format for production --- + bool result = Utils::SaveObjectToFile(destPath, DataStream::ST_BINARY, &passAsset, passAssetUuid, serializeContext); if (result == false) { @@ -322,14 +303,10 @@ namespace AZ return; } - // Success. Save output product(s) to response - AssetBuilderSDK::JobProduct jobProduct(destPath, PassAsset::RTTI_Type(), 0); - for (auto& assetId : dependentList) - { - jobProduct.m_dependencies.emplace_back(AssetBuilderSDK::ProductDependency(assetId, 0)); - } + // --- Save output product(s) to response --- - jobProduct.m_dependenciesHandled = true; // We've output the dependencies immediately above so it's OK to tell the AP we've handled dependencies + AssetBuilderSDK::JobProduct jobProduct(destPath, PassAsset::RTTI_Type(), 0); + jobProduct.m_dependenciesHandled = true; response.m_outputProducts.push_back(jobProduct); response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success; } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/AttachmentReadback.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/AttachmentReadback.cpp index 29a17dc9a8..29af8b7b63 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/AttachmentReadback.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/AttachmentReadback.cpp @@ -121,7 +121,7 @@ namespace AZ // Load shader and srg const char* ShaderPath = "shader/decomposemsimage.azshader"; - m_decomposeShader = LoadShader(ShaderPath); + m_decomposeShader = LoadCriticalShader(ShaderPath); if (m_decomposeShader == nullptr) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp index ebccc87cac..9173b47fad 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp @@ -8,6 +8,7 @@ #include +#include #include #include @@ -20,7 +21,7 @@ namespace AZ namespace RPI { - Data::AssetId GetShaderAssetId(const AZStd::string& shaderFilePath) + Data::AssetId GetShaderAssetId(const AZStd::string& shaderFilePath, bool isCritical) { Data::AssetId shaderAssetId; @@ -34,6 +35,19 @@ namespace AZ if (!shaderAssetId.IsValid()) { + if (isCritical) + { + Data::Asset shaderAsset = RPI::AssetUtils::LoadCriticalAsset(shaderFilePath); + if (shaderAsset.IsReady()) + { + return shaderAsset.GetId(); + } + else + { + AZ_Error("RPI Utils", false, "Could not load critical shader [%s]", shaderFilePath.c_str()); + } + } + AZ_Error("RPI Utils", false, "Failed to get asset id for shader [%s]", shaderFilePath.c_str()); } @@ -83,11 +97,23 @@ namespace AZ return FindShaderAsset(GetShaderAssetId(shaderFilePath), shaderFilePath); } + Data::Asset FindCriticalShaderAsset(const AZStd::string& shaderFilePath) + { + const bool isCritical = true; + return FindShaderAsset(GetShaderAssetId(shaderFilePath, isCritical), shaderFilePath); + } + Data::Instance LoadShader(const AZStd::string& shaderFilePath) { return LoadShader(GetShaderAssetId(shaderFilePath), shaderFilePath); } + Data::Instance LoadCriticalShader(const AZStd::string& shaderFilePath) + { + const bool isCritical = true; + return LoadShader(GetShaderAssetId(shaderFilePath, isCritical), shaderFilePath); + } + AZ::Data::Instance LoadStreamingTexture(AZStd::string_view path) { AzFramework::AssetSystem::AssetStatus status = AzFramework::AssetSystem::AssetStatus_Unknown; diff --git a/Gems/LyShine/Code/Source/Draw2d.cpp b/Gems/LyShine/Code/Source/Draw2d.cpp index 2d3612fc07..b4c8d58fae 100644 --- a/Gems/LyShine/Code/Source/Draw2d.cpp +++ b/Gems/LyShine/Code/Source/Draw2d.cpp @@ -79,7 +79,7 @@ void CDraw2d::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstrapSc // Load the shader to be used for 2d drawing const char* shaderFilepath = "Shaders/SimpleTextured.azshader"; - AZ::Data::Instance shader = AZ::RPI::LoadShader(shaderFilepath); + AZ::Data::Instance shader = AZ::RPI::LoadCriticalShader(shaderFilepath); // Set scene to be associated with the dynamic draw context AZ::RPI::ScenePtr scene; diff --git a/Gems/LyShine/Code/Source/UiRenderer.cpp b/Gems/LyShine/Code/Source/UiRenderer.cpp index 357431c80a..c52c249d20 100644 --- a/Gems/LyShine/Code/Source/UiRenderer.cpp +++ b/Gems/LyShine/Code/Source/UiRenderer.cpp @@ -58,7 +58,7 @@ void UiRenderer::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstra // Load the UI shader const char* uiShaderFilepath = "Shaders/LyShineUI.azshader"; - AZ::Data::Instance uiShader = AZ::RPI::LoadShader(uiShaderFilepath); + AZ::Data::Instance uiShader = AZ::RPI::LoadCriticalShader(uiShaderFilepath); // Create scene to be used by the dynamic draw context if (m_viewportContext) From 6a5a7740ad59ef5db87ba08e2c4ceff74851d038 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Wed, 11 Aug 2021 00:45:27 -0700 Subject: [PATCH 114/205] EMotion FX: Selecting Motion Properties crashes the Editor (#3005) Signed-off-by: Benjamin Jillich --- Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp index 27f83b07a3..5e9cf66fa7 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp @@ -498,7 +498,7 @@ namespace MysticQt } if (findPreviousMaximizedDialogNeeded) { - for (auto curDialog = AZStd::make_reverse_iterator(dialog) + 1; curDialog != m_dialogs.rend(); ++curDialog) + for (auto curDialog = AZStd::make_reverse_iterator(dialog); curDialog != m_dialogs.rend(); ++curDialog) { if (curDialog->m_maximizeSize && curDialog->m_frame->isHidden() == false) { From 5c90bc0d58f359306352f845a094531b6e184c98 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Wed, 11 Aug 2021 00:45:47 -0700 Subject: [PATCH 115/205] Skip blend shapes that influence multiple meshes (#3009) Signed-off-by: Benjamin Jillich --- .../Source/RPI.Builders/Model/MorphTargetExporter.cpp | 11 ++++++++--- .../MeshOptimizer/MeshOptimizerComponent.cpp | 6 ++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp index 0a1fb49ab5..fa437c002f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MorphTargetExporter.cpp @@ -159,9 +159,14 @@ namespace AZ::RPI // Determine the vertex index range for the morph target. const uint32_t numVertices = blendShapeData->GetVertexCount(); - AZ_Assert(blendShapeData->GetVertexCount() == sourceMesh.m_meshData->GetVertexCount(), - "Blend shape (%s) contains more/less vertices (%d) than the neutral mesh (%d).", - blendShapeName.c_str(), numVertices, sourceMesh.m_meshData->GetVertexCount()); + if (blendShapeData->GetVertexCount() != sourceMesh.m_meshData->GetVertexCount()) + { + AZ_Error(ModelAssetBuilderComponent::s_builderName, false, + "Skipping blend shape (%s) as it contains more/less vertices (%d) than the neutral mesh (%d). " + "The blend shape is most likely influencing multiple meshes, which is currently not supported.", + blendShapeName.c_str(), numVertices, sourceMesh.m_meshData->GetVertexCount()); + return; + } // The start index is after any previously added deltas metaData.m_startIndex = aznumeric_cast(packedCompressedMorphTargetVertexData.size()); diff --git a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp index 7541e2fce7..a410c4e6c9 100644 --- a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp +++ b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp @@ -379,10 +379,12 @@ namespace AZ::SceneGenerationComponents auto [optimizedMesh, optimizedUVs, optimizedTangents, optimizedBitangents, optimizedVertexColors, optimizedSkinWeights] = OptimizeMesh(mesh, mesh, uvDatas, tangentDatas, bitangentDatas, colorDatas, skinWeightDatas, meshGroup, hasBlendShapes); - AZ_TracePrintf(AZ::SceneAPI::Utilities::LogWindow, "Base mesh: %zu vertices, optimized mesh: %zu vertices, %0.02f%% of the original", + AZ_TracePrintf(AZ::SceneAPI::Utilities::LogWindow, "Optimized mesh '%s': Original: %zu vertices -> optimized: %zu vertices, %0.02f%% of the original (hasBlendShapes=%s)", + graph.GetNodeName(nodeIndex).GetName(), mesh->GetUsedControlPointCount(), optimizedMesh->GetUsedControlPointCount(), - ((float)optimizedMesh->GetUsedControlPointCount() / (float)mesh->GetUsedControlPointCount()) * 100.0f + ((float)optimizedMesh->GetUsedControlPointCount() / (float)mesh->GetUsedControlPointCount()) * 100.0f, + hasBlendShapes ? "Yes" : "No" ); const NodeIndex optimizedMeshNodeIndex = graph.AddChild(graph.GetNodeParent(nodeIndex), name.c_str(), AZStd::move(optimizedMesh)); From da4dfea9caccf66a3a14072d27a64c66ec9250f5 Mon Sep 17 00:00:00 2001 From: AMZN-AlexOteiza <82234181+AMZN-AlexOteiza@users.noreply.github.com> Date: Wed, 11 Aug 2021 10:15:41 +0100 Subject: [PATCH 116/205] Adjustment to property row so the label is more visible (#2866) Signed-off-by: Garcia Ruiz Co-authored-by: Garcia Ruiz --- .../AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index 5ea36bb30e..05c04872e3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -70,7 +70,7 @@ namespace AzToolsFramework m_leftAreaContainer = new QWidget(this); m_middleAreaContainer = new QWidget(this); - const int minimumControlWidth = 192; + const int minimumControlWidth = 142; m_middleAreaContainer->setMinimumWidth(minimumControlWidth); m_mainLayout->addWidget(m_leftAreaContainer, LabelColumnStretch, Qt::AlignLeft); m_mainLayout->addWidget(m_middleAreaContainer, ValueColumnStretch); From 9ecd0ff9df47b0930d9dacc3fe0dd1860a95ce7f Mon Sep 17 00:00:00 2001 From: AMZN-Alexandre Corcia Aguilera <82398284+aaguilea@users.noreply.github.com> Date: Wed, 11 Aug 2021 10:00:12 +0100 Subject: [PATCH 117/205] Bad Merge fix Signed-off-by: aaguilea --- Code/Editor/editor_lib_files.cmake | 2 -- 1 file changed, 2 deletions(-) diff --git a/Code/Editor/editor_lib_files.cmake b/Code/Editor/editor_lib_files.cmake index b921d4a559..ce11d013dd 100644 --- a/Code/Editor/editor_lib_files.cmake +++ b/Code/Editor/editor_lib_files.cmake @@ -803,8 +803,6 @@ set(FILES EditorViewportCamera.h ViewportManipulatorController.cpp ViewportManipulatorController.h - RenderViewport.cpp - RenderViewport.h TopRendererWnd.cpp TopRendererWnd.h ViewManager.cpp From 3845f430881bcd6770fca90c1c4425cf53d3700c Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 11 Aug 2021 08:13:38 -0700 Subject: [PATCH 118/205] missing header include after merge Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/std/string/conversions.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzCore/AzCore/std/string/conversions.h b/Code/Framework/AzCore/AzCore/std/string/conversions.h index b7887339e2..be71e12275 100644 --- a/Code/Framework/AzCore/AzCore/std/string/conversions.h +++ b/Code/Framework/AzCore/AzCore/std/string/conversions.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include From fbcb6510e68721c19ac17c5618fd1d021514d901 Mon Sep 17 00:00:00 2001 From: sconel <32552662+sconel@users.noreply.github.com> Date: Wed, 11 Aug 2021 10:45:31 -0700 Subject: [PATCH 119/205] Update storage of Prefab Dom info to be best effort (#2862) * Update storage of Prefab Dom info to be best effort Signed-off-by: sconel * Update IssueReporter to Skipped instead of PartialSkip Signed-off-by: sconel * Address PR feedback Signed-off-by: sconel * Fix failing Prefab Unit Test that expected default values to be stripped Signed-off-by: sconel --- .../Instance/InstanceToTemplatePropagator.cpp | 20 +--- .../AzToolsFramework/Prefab/Link/Link.cpp | 3 +- .../Prefab/PrefabDomUtils.cpp | 94 +++++++++++++++---- .../AzToolsFramework/Prefab/PrefabDomUtils.h | 28 ++++-- .../AzToolsFramework/Prefab/PrefabLoader.cpp | 2 +- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 4 +- .../Prefab/Spawnable/EditorInfoRemover.cpp | 2 +- .../Prefab/Spawnable/SpawnableUtils.cpp | 2 +- ...refabInstanceToTemplatePropagatorTests.cpp | 93 ++++++++++++++++++ .../Tests/Prefab/PrefabTestComponent.cpp | 14 +++ .../Tests/Prefab/PrefabTestComponent.h | 18 ++++ .../Tests/Prefab/PrefabTestFixture.cpp | 1 + .../Prefab/PrefabUpdateWithPatchesTests.cpp | 5 +- .../Pipeline/NetworkPrefabProcessor.cpp | 2 +- 14 files changed, 241 insertions(+), 47 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index 814c4e2a7f..36b39f3a72 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -46,7 +46,6 @@ namespace AzToolsFramework bool InstanceToTemplatePropagator::GenerateDomForEntity(PrefabDom& generatedEntityDom, const AZ::Entity& entity) { - //grab the owning instance so we can use the entityIdMapper in settings InstanceOptionalReference owningInstance = m_instanceEntityMapperInterface->FindOwningInstance(entity.GetId()); if (!owningInstance) @@ -54,19 +53,8 @@ namespace AzToolsFramework AZ_Error("Prefab", false, "Entity does not belong to an instance"); return false; } - - InstanceEntityIdMapper entityIdMapper; - entityIdMapper.SetStoringInstance(owningInstance->get()); - //create settings so that the serialized entity dom undergoes mapping from entity id to entity alias - AZ::JsonSerializerSettings settings; - settings.m_metadata.Add(static_cast(&entityIdMapper)); - - //generate PrefabDom using Json serialization system - AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store( - generatedEntityDom, generatedEntityDom.GetAllocator(), entity, settings); - - return result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success; + return PrefabDomUtils::StoreEntityInPrefabDomFormat(entity, owningInstance->get(), generatedEntityDom); } bool InstanceToTemplatePropagator::GenerateDomForInstance(PrefabDom& generatedInstanceDom, const Prefab::Instance& instance) @@ -185,8 +173,10 @@ namespace AzToolsFramework else { AZ_Error( - "Prefab", result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::PartialSkip, - "Some of the patches are not successfully applied."); + "Prefab", + (result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::Skipped) && + (result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::PartialSkip), + "Some of the patches were not successfully applied."); m_prefabSystemComponentInterface->SetTemplateDirtyFlag(templateId, true); m_prefabSystemComponentInterface->PropagateTemplateChanges(templateId, instanceToExclude); return true; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp index 3c7e5ff3f8..940a2787cb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp @@ -196,7 +196,8 @@ namespace AzToolsFramework m_sourceTemplateId, m_targetTemplateId); return false; } - if (applyPatchResult.GetOutcome() == AZ::JsonSerializationResult::Outcomes::PartialSkip) + if (applyPatchResult.GetOutcome() == AZ::JsonSerializationResult::Outcomes::PartialSkip || + applyPatchResult.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Skipped) { AZ_Error( "Prefab", false, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp index 86983d7912..1ad88e53d2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp @@ -26,6 +26,30 @@ namespace AzToolsFramework { namespace PrefabDomUtils { + namespace Internal + { + AZ::JsonSerializationResult::ResultCode JsonIssueReporter(AZStd::string& scratchBuffer, + AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, AZStd::string_view path) + { + namespace JSR = AZ::JsonSerializationResult; + + if (result.GetProcessing() == JSR::Processing::Halted) + { + scratchBuffer.append(message.begin(), message.end()); + scratchBuffer.append("\n Reason: "); + result.AppendToString(scratchBuffer, path); + scratchBuffer.append("."); + AZ_Warning("Prefab Serialization", false, "%s", scratchBuffer.c_str()); + + scratchBuffer.clear(); + + return JSR::ResultCode(result.GetTask(), JSR::Outcomes::Skipped); + } + + return result; + } + } + PrefabDomValueReference FindPrefabDomValue(PrefabDomValue& parentValue, const char* valueName) { PrefabDomValue::MemberIterator valueIterator = parentValue.FindMember(valueName); @@ -48,7 +72,7 @@ namespace AzToolsFramework return valueIterator->value; } - bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom, StoreInstanceFlags flags) + bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom, StoreFlags flags) { InstanceEntityIdMapper entityIdMapper; entityIdMapper.SetStoringInstance(instance); @@ -59,11 +83,21 @@ namespace AzToolsFramework settings.m_metadata.Add(static_cast(&entityIdMapper)); settings.m_metadata.Add(&entityIdMapper); - if ((flags & StoreInstanceFlags::StripDefaultValues) != StoreInstanceFlags::StripDefaultValues) + if ((flags & StoreFlags::StripDefaultValues) != StoreFlags::StripDefaultValues) { settings.m_keepDefaults = true; } + AZStd::string scratchBuffer; + auto issueReportingCallback = [&scratchBuffer] + (AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, + AZStd::string_view path) -> AZ::JsonSerializationResult::ResultCode + { + return Internal::JsonIssueReporter(scratchBuffer, message, result, path); + }; + + settings.m_reporting = AZStd::move(issueReportingCallback); + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), instance, settings); @@ -80,7 +114,38 @@ namespace AzToolsFramework return true; } - bool LoadInstanceFromPrefabDom(Instance& instance, const PrefabDom& prefabDom, LoadInstanceFlags flags) + bool StoreEntityInPrefabDomFormat(const AZ::Entity& entity, Instance& owningInstance, PrefabDom& prefabDom, StoreFlags flags) + { + InstanceEntityIdMapper entityIdMapper; + entityIdMapper.SetStoringInstance(owningInstance); + + //create settings so that the serialized entity dom undergoes mapping from entity id to entity alias + AZ::JsonSerializerSettings settings; + settings.m_metadata.Add(static_cast(&entityIdMapper)); + + if ((flags & StoreFlags::StripDefaultValues) != StoreFlags::StripDefaultValues) + { + settings.m_keepDefaults = true; + } + + AZStd::string scratchBuffer; + auto issueReportingCallback = [&scratchBuffer] + (AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, + AZStd::string_view path) -> AZ::JsonSerializationResult::ResultCode + { + return Internal::JsonIssueReporter(scratchBuffer, message, result, path); + }; + + settings.m_reporting = AZStd::move(issueReportingCallback); + + //generate PrefabDom using Json serialization system + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store( + prefabDom, prefabDom.GetAllocator(), entity, settings); + + return result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success; + } + + bool LoadInstanceFromPrefabDom(Instance& instance, const PrefabDom& prefabDom, LoadFlags flags) { // When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will // be released and reloaded once the entities are built up again. By suspending asset release temporarily the asset reload @@ -89,7 +154,7 @@ namespace AzToolsFramework InstanceEntityIdMapper entityIdMapper; entityIdMapper.SetLoadingInstance(instance); - if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId) + if ((flags & LoadFlags::AssignRandomEntityId) == LoadFlags::AssignRandomEntityId) { entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); } @@ -119,7 +184,7 @@ namespace AzToolsFramework } bool LoadInstanceFromPrefabDom( - Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets, LoadInstanceFlags flags) + Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets, LoadFlags flags) { // When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will // be released and reloaded once the entities are built up again. By suspending asset release temporarily the asset reload @@ -128,7 +193,7 @@ namespace AzToolsFramework InstanceEntityIdMapper entityIdMapper; entityIdMapper.SetLoadingInstance(instance); - if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId) + if ((flags & LoadFlags::AssignRandomEntityId) == LoadFlags::AssignRandomEntityId) { entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); } @@ -161,7 +226,7 @@ namespace AzToolsFramework } bool LoadInstanceFromPrefabDom( - Instance& instance, Instance::EntityList& newlyAddedEntities, const PrefabDom& prefabDom, LoadInstanceFlags flags) + Instance& instance, Instance::EntityList& newlyAddedEntities, const PrefabDom& prefabDom, LoadFlags flags) { // When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will // be released and reloaded once the entities are built up again. By suspending asset release temporarily the asset reload @@ -170,7 +235,7 @@ namespace AzToolsFramework InstanceEntityIdMapper entityIdMapper; entityIdMapper.SetLoadingInstance(instance); - if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId) + if ((flags & LoadFlags::AssignRandomEntityId) == LoadFlags::AssignRandomEntityId) { entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); } @@ -240,15 +305,12 @@ namespace AzToolsFramework AZ::JsonSerializationResult::ResultCode ApplyPatches( PrefabDomValue& prefabDomToApplyPatchesOn, PrefabDom::AllocatorType& allocator, const PrefabDomValue& patches) { - auto issueReportingCallback = [](AZStd::string_view, AZ::JsonSerializationResult::ResultCode result, - AZStd::string_view) -> AZ::JsonSerializationResult::ResultCode + AZStd::string scratchBuffer; + auto issueReportingCallback = [&scratchBuffer] + (AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result, + AZStd::string_view path) -> AZ::JsonSerializationResult::ResultCode { - using namespace AZ::JsonSerializationResult; - if (result.GetProcessing() == Processing::Halted) - { - return ResultCode(result.GetTask(), Outcomes::PartialSkip); - } - return result; + return Internal::JsonIssueReporter(scratchBuffer, message, result, path); }; AZ::JsonApplyPatchSettings applyPatchSettings; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h index e773b581dd..b04cf9f57d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h @@ -38,7 +38,7 @@ namespace AzToolsFramework PrefabDomValueReference FindPrefabDomValue(PrefabDomValue& parentValue, const char* valueName); PrefabDomValueConstReference FindPrefabDomValue(const PrefabDomValue& parentValue, const char* valueName); - enum class StoreInstanceFlags : uint8_t + enum class StoreFlags : uint8_t { //! No flags used during the call to LoadInstanceFromPrefabDom. None = 0, @@ -47,7 +47,7 @@ namespace AzToolsFramework //! such as saving to disk, this flag will control that behavior. StripDefaultValues = 1 << 0 }; - AZ_DEFINE_ENUM_BITWISE_OPERATORS(StoreInstanceFlags); + AZ_DEFINE_ENUM_BITWISE_OPERATORS(StoreFlags); /** * Stores a valid Prefab Instance within a Prefab Dom. Useful for generating Templates @@ -56,9 +56,21 @@ namespace AzToolsFramework * @param flags Controls behavior such as whether to store default values * @return bool on whether the operation succeeded */ - bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom, StoreInstanceFlags flags = StoreInstanceFlags::None); + bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom, StoreFlags flags = StoreFlags::None); - enum class LoadInstanceFlags : uint8_t + /** + * Stores a valid entity in Prefab Dom format. + * @param entity The entity to store + * @param owningInstance The instance owning the passed in entity. + * Used for contextualizing the entity's place in a Prefab hierarchy. + * @param prefabDom The prefabDom that will be used to store the entity data + * @param flags controls behavior such as whether to store default values + * @return bool on whether the operation succeeded + */ + bool StoreEntityInPrefabDomFormat(const AZ::Entity& entity, Instance& owningInstance, PrefabDom& prefabDom, + StoreFlags flags = StoreFlags::None); + + enum class LoadFlags : uint8_t { //! No flags used during the call to LoadInstanceFromPrefabDom. None = 0, @@ -66,7 +78,7 @@ namespace AzToolsFramework //! unique, e.g. when they are duplicates of live entities, this flag will assign them a random new id. AssignRandomEntityId = 1 << 0 }; - AZ_DEFINE_ENUM_BITWISE_OPERATORS(LoadInstanceFlags); + AZ_DEFINE_ENUM_BITWISE_OPERATORS(LoadFlags); /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. @@ -76,7 +88,7 @@ namespace AzToolsFramework * @return bool on whether the operation succeeded. */ bool LoadInstanceFromPrefabDom( - Instance& instance, const PrefabDom& prefabDom, LoadInstanceFlags flags = LoadInstanceFlags::None); + Instance& instance, const PrefabDom& prefabDom, LoadFlags flags = LoadFlags::None); /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. @@ -88,7 +100,7 @@ namespace AzToolsFramework */ bool LoadInstanceFromPrefabDom( Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets, - LoadInstanceFlags flags = LoadInstanceFlags::None); + LoadFlags flags = LoadFlags::None); /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. @@ -101,7 +113,7 @@ namespace AzToolsFramework */ bool LoadInstanceFromPrefabDom( Instance& instance, Instance::EntityList& newlyAddedEntities, const PrefabDom& prefabDom, - LoadInstanceFlags flags = LoadInstanceFlags::None); + LoadFlags flags = LoadFlags::None); inline PrefabDomPath GetPrefabDomInstancePath(const char* instanceName) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp index ea54c9d10c..5091a2d1bc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabLoader.cpp @@ -328,7 +328,7 @@ namespace AzToolsFramework PrefabDom storedPrefabDom(&savingTemplateDom->get().GetAllocator()); if (!PrefabDomUtils::StoreInstanceInPrefabDom(savingPrefabInstance, storedPrefabDom, - PrefabDomUtils::StoreInstanceFlags::StripDefaultValues)) + PrefabDomUtils::StoreFlags::StripDefaultValues)) { return false; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index 955af18a66..fc64e0b5b3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -266,8 +266,8 @@ namespace AzToolsFramework AZ_Error( "Prefab", - result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::PartialSkip || - result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success, + (result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::Skipped) && + (result.GetOutcome() != AZ::JsonSerializationResult::Outcomes::PartialSkip), "Some of the patches are not successfully applied."); //remove the link id placed into the instance diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/EditorInfoRemover.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/EditorInfoRemover.cpp index 1d856fa395..dfba1d54ba 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/EditorInfoRemover.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/EditorInfoRemover.cpp @@ -513,7 +513,7 @@ exportComponent, prefabProcessorContext); // convert Prefab DOM into Prefab Instance. AZStd::unique_ptr instance(aznew Instance()); if (!Prefab::PrefabDomUtils::LoadInstanceFromPrefabDom(*instance, prefab, - Prefab::PrefabDomUtils::LoadInstanceFlags::AssignRandomEntityId)) + Prefab::PrefabDomUtils::LoadFlags::AssignRandomEntityId)) { PrefabDomValueReference sourceReference = PrefabDomUtils::FindPrefabDomValue(prefab, PrefabDomUtils::SourceName); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp index 1373d2fa75..902f439280 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp @@ -30,7 +30,7 @@ namespace AzToolsFramework::Prefab::SpawnableUtils { Instance instance; if (Prefab::PrefabDomUtils::LoadInstanceFromPrefabDom(instance, prefabDom, referencedAssets, - Prefab::PrefabDomUtils::LoadInstanceFlags::AssignRandomEntityId)) // Always assign random entity ids because the spawnable is + Prefab::PrefabDomUtils::LoadFlags::AssignRandomEntityId)) // Always assign random entity ids because the spawnable is // going to be used to create clones of the entities. { AzFramework::Spawnable::EntityList& entities = spawnable.GetEntities(); diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabInstanceToTemplatePropagatorTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabInstanceToTemplatePropagatorTests.cpp index 8379992553..ebe35a5402 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabInstanceToTemplatePropagatorTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabInstanceToTemplatePropagatorTests.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -18,6 +19,98 @@ namespace UnitTest { using PrefabInstanceToTemplateTests = PrefabTestFixture; + TEST_F(PrefabInstanceToTemplateTests, GenerateEntityDom_InvalidType_InvalidTypeSkipped) + { + const char* newEntityName = "New Entity"; + AZ::Entity* newEntity = CreateEntity(newEntityName, false); + ASSERT_TRUE(newEntity); + + // Add a component with a member that is missing reflection info + // and a member that is properly reflected + PrefabTestComponentWithUnReflectedTypeMember* newComponent = + newEntity->CreateComponent(); + + ASSERT_TRUE(newComponent); + + AZStd::unique_ptr prefabInstance = m_prefabSystemComponent->CreatePrefab({ newEntity }, {}, "test/path"); + ASSERT_TRUE(prefabInstance); + + PrefabDom entityDom; + m_instanceToTemplateInterface->GenerateDomForEntity(entityDom, *newEntity); + + auto componentListDom = entityDom.FindMember("Components"); + + // Confirm that there is only one component in the entityDom + ASSERT_NE(componentListDom, entityDom.MemberEnd()); + ASSERT_TRUE(componentListDom->value.IsObject()); + ASSERT_EQ(componentListDom->value.MemberCount(), 1); + + auto testComponentDom = componentListDom->value.MemberBegin(); + ASSERT_TRUE(testComponentDom->value.IsObject()); + + // Confirm that the componentDom does not contained the invalid UnReflectedType + // We want to skip over it and produce a best effort entityDom + auto unReflectedTypeDom = testComponentDom->value.FindMember("UnReflectedType"); + ASSERT_EQ(unReflectedTypeDom, testComponentDom->value.MemberEnd()); + + // Confirm the presence of the valid ReflectedType + auto reflectedTypeDom = testComponentDom->value.FindMember("ReflectedType"); + ASSERT_NE(reflectedTypeDom, testComponentDom->value.MemberEnd()); + + // Confirm the reflected type has the correct type and value + ASSERT_TRUE(reflectedTypeDom->value.IsInt()); + EXPECT_EQ(reflectedTypeDom->value.GetInt(), newComponent->m_reflectedType); + } + + TEST_F(PrefabInstanceToTemplateTests, GenerateInstanceDom_InvalidType_InvalidTypeSkipped) + { + const char* newEntityName = "New Entity"; + AZ::Entity* newEntity = CreateEntity(newEntityName, false); + ASSERT_TRUE(newEntity); + + // Add a component with a member that is missing reflection info + // and a member that is properly reflected + PrefabTestComponentWithUnReflectedTypeMember* newComponent = + newEntity->CreateComponent(); + + ASSERT_TRUE(newComponent); + + AZStd::unique_ptr prefabInstance = m_prefabSystemComponent->CreatePrefab({ newEntity }, {}, "test/path"); + ASSERT_TRUE(prefabInstance); + + PrefabDom instanceDom; + m_instanceToTemplateInterface->GenerateDomForInstance(instanceDom, *prefabInstance); + + // Acquire the entity out of the instanceDom + auto entitiesDom = instanceDom.FindMember(PrefabDomUtils::EntitiesName); + ASSERT_NE(entitiesDom, instanceDom.MemberEnd()); + ASSERT_EQ(entitiesDom->value.MemberCount(), 1); + + auto entityDom = entitiesDom->value.MemberBegin(); + auto componentListDom = entityDom->value.FindMember("Components"); + + // Confirm that there is only one component in the entityDom + ASSERT_NE(componentListDom, entityDom->value.MemberEnd()); + ASSERT_TRUE(componentListDom->value.IsObject()); + ASSERT_EQ(componentListDom->value.MemberCount(), 1); + + auto testComponentDom = componentListDom->value.MemberBegin(); + ASSERT_TRUE(testComponentDom->value.IsObject()); + + // Confirm that the componentDom does not contained the invalid UnReflectedType + // We want to skip over it and produce a best effort entityDom + auto unReflectedTypeDom = testComponentDom->value.FindMember("UnReflectedType"); + ASSERT_EQ(unReflectedTypeDom, testComponentDom->value.MemberEnd()); + + // Confirm the presence of the valid ReflectedType + auto reflectedTypeDom = testComponentDom->value.FindMember("ReflectedType"); + ASSERT_NE(reflectedTypeDom, testComponentDom->value.MemberEnd()); + + // Confirm the reflected type has the correct type and value + ASSERT_TRUE(reflectedTypeDom->value.IsInt()); + EXPECT_EQ(reflectedTypeDom->value.GetInt(), newComponent->m_reflectedType); + } + TEST_F(PrefabInstanceToTemplateTests, PrefabUpdateTemplate_UpdateEntityOnInstance) { //create template with single entity diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.cpp index 8f7ee398a0..5d29b179c4 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.cpp @@ -28,4 +28,18 @@ namespace UnitTest : m_boolProperty(boolProperty) { } + + void PrefabTestComponentWithUnReflectedTypeMember::Reflect(AZ::ReflectContext* reflection) + { + AZ::SerializeContext* serializeContext = AZ::RttiCast(reflection); + + // We reflect our member but not its type this will result in missing reflection data + // when we try to store or load this field + if (serializeContext) + { + serializeContext->Class() + ->Field("UnReflectedType", &PrefabTestComponentWithUnReflectedTypeMember::m_unReflectedType) + ->Field("ReflectedType", &PrefabTestComponentWithUnReflectedTypeMember::m_reflectedType); + } + } } diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.h b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.h index 0ed8f6d9c9..e0e986b7db 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.h +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestComponent.h @@ -27,4 +27,22 @@ namespace UnitTest int m_intProperty = 0; AZ::EntityId m_entityIdProperty; }; + + class UnReflectedType + { + public: + AZ_TYPE_INFO(UnReflectedType, "{FB65262C-CE9A-45CA-99EB-4DDCB19B32DB}"); + int m_unReflectedInt = 42; + }; + + class PrefabTestComponentWithUnReflectedTypeMember + : public AzToolsFramework::Components::EditorComponentBase + { + public: + AZ_EDITOR_COMPONENT(PrefabTestComponentWithUnReflectedTypeMember, "{726281E1-8E47-46AB-8018-D3F4BA823D74}"); + static void Reflect(AZ::ReflectContext* reflection); + + UnReflectedType m_unReflectedType; + int m_reflectedType = 52; + }; } diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestFixture.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestFixture.cpp index ded88d2da3..ed30de09c4 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestFixture.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabTestFixture.cpp @@ -49,6 +49,7 @@ namespace UnitTest EXPECT_TRUE(m_instanceToTemplateInterface); GetApplication()->RegisterComponentDescriptor(PrefabTestComponent::CreateDescriptor()); + GetApplication()->RegisterComponentDescriptor(PrefabTestComponentWithUnReflectedTypeMember::CreateDescriptor()); } AZStd::unique_ptr PrefabTestFixture::CreateTestApplication() diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp index 72e88c6336..c17763f778 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp @@ -136,7 +136,10 @@ namespace UnitTest PrefabDomValueReference wheelEntityComponentBoolPropertyValue = PrefabDomUtils::FindPrefabDomValue(wheelEntityComponentValue->get(), PrefabTestDomUtils::BoolPropertyName); - ASSERT_FALSE(wheelEntityComponentBoolPropertyValue.has_value()); + + ASSERT_TRUE(wheelEntityComponentBoolPropertyValue.has_value()); + ASSERT_TRUE(wheelEntityComponentBoolPropertyValue->get().IsBool()); + ASSERT_FALSE(wheelEntityComponentBoolPropertyValue->get().GetBool()); // Validate that the axles under the car have the same DOM as the axle template. PrefabTestDomUtils::ValidatePrefabDomInstances(axleInstanceAliasesUnderCar, carTemplateDom, axleTemplateDom); diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index d49f6901f3..acfec5eb38 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -56,7 +56,7 @@ namespace Multiplayer // convert Prefab DOM into Prefab Instance. AZStd::unique_ptr sourceInstance(aznew Instance()); - if (!PrefabDomUtils::LoadInstanceFromPrefabDom(*sourceInstance, prefab, PrefabDomUtils::LoadInstanceFlags::AssignRandomEntityId)) + if (!PrefabDomUtils::LoadInstanceFromPrefabDom(*sourceInstance, prefab, PrefabDomUtils::LoadFlags::AssignRandomEntityId)) { PrefabDomValueConstReference sourceReference = PrefabDomUtils::FindPrefabDomValue(prefab, PrefabDomUtils::SourceName); From 39d56a8834c7aa08db5b0c7ac1b2b507bedf40f8 Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Wed, 11 Aug 2021 10:45:48 -0700 Subject: [PATCH 120/205] Removing product dependency check from pass builder test since shaders references are now registered as a job dependency and not a product dependency Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- Gems/Atom/RPI/Code/Tests.Builders/PassBuilderTest.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Gems/Atom/RPI/Code/Tests.Builders/PassBuilderTest.cpp b/Gems/Atom/RPI/Code/Tests.Builders/PassBuilderTest.cpp index ad1df41824..4e088cece5 100644 --- a/Gems/Atom/RPI/Code/Tests.Builders/PassBuilderTest.cpp +++ b/Gems/Atom/RPI/Code/Tests.Builders/PassBuilderTest.cpp @@ -112,9 +112,6 @@ namespace UnitTest EXPECT_TRUE(response.m_resultCode == AssetBuilderSDK::ProcessJobResult_Success); EXPECT_TRUE(response.m_outputProducts.size() == 1); - // Verify the dependency was registered - EXPECT_TRUE(response.m_outputProducts[0].m_dependencies.size() == 1); - // Verify input and output names are the same Data::Asset readAsset = LoadAssetFromFile(response.m_outputProducts[0].m_productFileName.c_str()); RPI::PassAsset* readPassAsset = static_cast(readAsset.GetData()); From 6d1bb8e439eb2b0b8aeaebd45e69115b156275f7 Mon Sep 17 00:00:00 2001 From: jromnoa <80134229+jromnoa@users.noreply.github.com> Date: Wed, 11 Aug 2021 11:19:22 -0700 Subject: [PATCH 121/205] Add Light component GPU (screenshot) test to AutomatedTesting nightly o3de runs. (#2923) * adds the Light component GPU screenshot test to AutomatedTesting Signed-off-by: jromnoa * add LIGHT_TYPE_PROPERTY constant to test script since it is re-used multiple times Signed-off-by: jromnoa * removes redundant f strings, adds LIGHT_COMPONENT and LIGHT_TYPE_PROPERTY constants for re-use, removed formattng errors, increase CMakeLists.txt timeout, add attach_component_to_entity() to hydra_editor_utils.py Signed-off-by: jromnoa * fix ImportError Signed-off-by: jromnoa * moves the LIGHT_TYPES constant to a new file since scripts rely on it that do not have the Editor launched (can't see hydra bindings so failes with ModuleNotFound error) Signed-off-by: jromnoa --- .../hydra_editor_utils.py | 30 ++ .../PythonTests/atom_renderer/CMakeLists.txt | 2 +- ...dra_AtomEditorComponents_LightComponent.py | 2 +- .../hydra_GPUTest_LightComponent.py | 268 ++++++++++++++++++ .../atom_utils/atom_component_helper.py | 191 ++++++++++++- .../atom_utils/atom_constants.py | 19 ++ .../atom_utils/screenshot_utils.py | 17 ++ .../golden_images/AreaLight_1.ppm | 3 + .../golden_images/AreaLight_2.ppm | 3 + .../golden_images/AreaLight_3.ppm | 3 + .../golden_images/AreaLight_4.ppm | 3 + .../golden_images/AreaLight_5.ppm | 3 + .../golden_images/SpotLight_1.ppm | 3 + .../golden_images/SpotLight_2.ppm | 3 + .../golden_images/SpotLight_3.ppm | 3 + .../golden_images/SpotLight_4.ppm | 3 + .../golden_images/SpotLight_5.ppm | 3 + .../golden_images/SpotLight_6.ppm | 3 + .../atom_renderer/test_Atom_GPUTests.py | 61 +++- .../atom_renderer/test_Atom_MainSuite.py | 2 +- 20 files changed, 607 insertions(+), 18 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py index cec1b6456b..985e32ede5 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py @@ -8,6 +8,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT import azlmbr.bus as bus import azlmbr.editor as editor import azlmbr.entity as entity +import azlmbr.legacy.general as general import azlmbr.object from typing import List @@ -428,3 +429,32 @@ def get_component_type_id_map(component_name_list): type_ids_by_component[component_names[i]] = typeId return type_ids_by_component + + +def attach_component_to_entity(entity_id, component_name): + # type: (azlmbr.entity.EntityId, str) -> azlmbr.entity.EntityComponentIdPair + """ + Adds the component if not added already. + :param entity_id: EntityId of the entity to attach the component to + :param component_name: name of the component + :return: If successful, returns the EntityComponentIdPair, otherwise returns None. + """ + type_ids_list = editor.EditorComponentAPIBus( + bus.Broadcast, 'FindComponentTypeIdsByEntityType', [component_name], 0) + general.log(f"Components found = {len(type_ids_list)}") + if len(type_ids_list) < 1: + general.log(f"ERROR: A component class with name {component_name} doesn't exist") + return None + elif len(type_ids_list) > 1: + general.log(f"ERROR: Found more than one component classes with same name: {component_name}") + return None + # Before adding the component let's check if it is already attached to the entity. + component_outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', entity_id, type_ids_list[0]) + if component_outcome.IsSuccess(): + return component_outcome.GetValue() # In this case the value is not a list. + component_outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', entity_id, type_ids_list) + if component_outcome.IsSuccess(): + general.log(f"{component_name} Component added to entity.") + return component_outcome.GetValue()[0] + general.log(f"ERROR: Failed to add component [{component_name}] to entity") + return None diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt index d4f036faeb..f056623ecd 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt @@ -39,7 +39,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED AND AutomatedT TEST_SUITE main TEST_REQUIRES gpu TEST_SERIAL - TIMEOUT 800 + TIMEOUT 1200 PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_GPUTests.py RUNTIME_DEPENDENCIES AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py index ec8dc199ae..24866f3b19 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py @@ -19,7 +19,7 @@ import azlmbr.legacy.general as general sys.path.append(os.path.join(azlmbr.paths.devassets, "Gem", "PythonTests")) import editor_python_test_tools.hydra_editor_utils as hydra -from atom_renderer.atom_utils.atom_component_helper import LIGHT_TYPES +from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES LIGHT_TYPE_PROPERTY = 'Controller|Configuration|Light type' SPHERE_AND_SPOT_DISK_LIGHT_PROPERTIES = [ diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py new file mode 100644 index 0000000000..08f921e68b --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py @@ -0,0 +1,268 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +Hydra script that is used to create an entity with a Light component attached. +It then updates the property values of the Light component and takes a screenshot. +The screenshot is compared against an expected golden image for test verification. + +See the run() function for more in-depth test info. +""" +import os +import sys + +import azlmbr.asset as asset +import azlmbr.bus as bus +import azlmbr.editor as editor +import azlmbr.math as math +import azlmbr.paths +import azlmbr.legacy.general as general + +sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) + +import editor_python_test_tools.hydra_editor_utils as hydra +from atom_renderer.atom_utils import screenshot_utils +from atom_renderer.atom_utils import atom_component_helper +from editor_python_test_tools.editor_test_helper import EditorTestHelper + +helper = EditorTestHelper(log_prefix="Atom_EditorTestHelper") + +LEVEL_NAME = "auto_test" +LIGHT_COMPONENT = "Light" +LIGHT_TYPE_PROPERTY = 'Controller|Configuration|Light type' +DEGREE_RADIAN_FACTOR = 0.0174533 + + +def run(): + """ + Sets up the tests by making sure the required level is created & setup correctly. + It then executes 2 test cases - see each associated test function's docstring for more info. + + Finally prints the string "Light component tests completed" after completion + + Tests will fail immediately if any of these log lines are found: + 1. Trace::Assert + 2. Trace::Error + 3. Traceback (most recent call last): + + :return: None + """ + atom_component_helper.create_basic_atom_level(level_name=LEVEL_NAME) + + # Run tests. + area_light_test() + spot_light_test() + general.log("Light component tests completed.") + + +def area_light_test(): + """ + Basic test for the "Light" component attached to an "area_light" entity. + + Test Case - Light Component: Capsule, Spot (disk), and Point (sphere): + 1. Creates "area_light" entity w/ a Light component that has a Capsule Light type w/ the color set to 255, 0, 0 + 2. Enters game mode to take a screenshot for comparison, then exits game mode. + 3. Sets the Light component Intensity Mode to Lumens (default). + 4. Ensures the Light component Mode is Automatic (default). + 5. Sets the Intensity value of the Light component to 0.0 + 6. Enters game mode again, takes another screenshot for comparison, then exits game mode. + 7. Updates the Intensity value of the Light component to 1000.0 + 8. Enters game mode again, takes another screenshot for comparison, then exits game mode. + 9. Swaps the Capsule light type option to Spot (disk) light type on the Light component + 10. Updates "area_light" entity Transform rotate value to x: 90.0, y:0.0, z:0.0 + 11. Enters game mode again, takes another screenshot for comparison, then exits game mode. + 12. Swaps the Spot (disk) light type for the Point (sphere) light type in the Light component. + 13. Enters game mode again, takes another screenshot for comparison, then exits game mode. + 14. Deletes the Light component from the "area_light" entity and verifies its successful. + """ + # Create an "area_light" entity with "Light" component using Light type of "Capsule" + area_light_entity_name = "area_light" + area_light = hydra.Entity(area_light_entity_name) + area_light.create_entity(math.Vector3(-1.0, -2.0, 3.0), [LIGHT_COMPONENT]) + general.log( + f"{area_light_entity_name}_test: Component added to the entity: " + f"{hydra.has_components(area_light.id, [LIGHT_COMPONENT])}") + light_component_id_pair = hydra.attach_component_to_entity(area_light.id, LIGHT_COMPONENT) + + # Select the "Capsule" light type option. + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + atom_component_helper.LIGHT_TYPES['capsule'] + ) + + # Update color and take screenshot in game mode + color = math.Color(255.0, 0.0, 0.0, 0.0) + area_light.get_set_test(0, "Controller|Configuration|Color", color) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_1", area_light_entity_name) + + # Update intensity value to 0.0 and take screenshot in game mode + area_light.get_set_test(0, "Controller|Configuration|Attenuation Radius|Mode", 1) + area_light.get_set_test(0, "Controller|Configuration|Intensity", 0.0) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_2", area_light_entity_name) + + # Update intensity value to 1000.0 and take screenshot in game mode + area_light.get_set_test(0, "Controller|Configuration|Intensity", 1000.0) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_3", area_light_entity_name) + + # Swap the "Capsule" light type option to "Spot (disk)" light type + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + atom_component_helper.LIGHT_TYPES['spot_disk'] + ) + area_light_rotation = math.Vector3(DEGREE_RADIAN_FACTOR * 90.0, 0.0, 0.0) + azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", area_light.id, area_light_rotation) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_4", area_light_entity_name) + + # Swap the "Spot (disk)" light type to the "Point (sphere)" light type and take screenshot. + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + atom_component_helper.LIGHT_TYPES['sphere'] + ) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("AreaLight_5", area_light_entity_name) + + editor.ToolsApplicationRequestBus(bus.Broadcast, "DeleteEntityById", area_light.id) + + +def spot_light_test(): + """ + Basic test for the Light component attached to a "spot_light" entity. + + Test Case - Light Component: Spot (disk) with shadows & colors: + 1. Creates "spot_light" entity w/ a Light component attached to it. + 2. Selects the "directional_light" entity already present in the level and disables it. + 3. Selects the "global_skylight" entity already present in the level and disables the HDRi Skybox component, + as well as the Global Skylight (IBL) component. + 4. Enters game mode to take a screenshot for comparison, then exits game mode. + 5. Selects the "ground_plane" entity and changes updates the material to a new material. + 6. Enters game mode to take a screenshot for comparison, then exits game mode. + 7. Selects the "spot_light" entity and increases the Light component Intensity to 800 lm + 8. Enters game mode to take a screenshot for comparison, then exits game mode. + 9. Selects the "spot_light" entity and sets the Light component Color to 47, 75, 37 + 10. Enters game mode to take a screenshot for comparison, then exits game mode. + 11. Selects the "spot_light" entity and modifies the Shutter controls to the following values: + - Enable shutters: True + - Inner Angle: 60.0 + - Outer Angle: 75.0 + 12. Enters game mode to take a screenshot for comparison, then exits game mode. + 13. Selects the "spot_light" entity and modifies the Shadow controls to the following values: + - Enable Shadow: True + - ShadowmapSize: 256 + 14. Modifies the world translate position of the "spot_light" entity to 0.7, -2.0, 1.9 (for casting shadows better) + 15. Enters game mode to take a screenshot for comparison, then exits game mode. + """ + # Disable "Directional Light" component for the "directional_light" entity + # "directional_light" entity is created by the create_basic_atom_level() function by default. + directional_light_entity_id = hydra.find_entity_by_name("directional_light") + directional_light = hydra.Entity(name='directional_light', id=directional_light_entity_id) + directional_light_component_type = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Directional Light"], 0)[0] + directional_light_component = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', directional_light.id, directional_light_component_type + ).GetValue() + editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [directional_light_component]) + general.idle_wait(0.5) + + # Disable "Global Skylight (IBL)" and "HDRi Skybox" components for the "global_skylight" entity + global_skylight_entity_id = hydra.find_entity_by_name("global_skylight") + global_skylight = hydra.Entity(name='global_skylight', id=global_skylight_entity_id) + global_skylight_component_type = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Global Skylight (IBL)"], 0)[0] + global_skylight_component = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', global_skylight.id, global_skylight_component_type + ).GetValue() + editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [global_skylight_component]) + hdri_skybox_component_type = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["HDRi Skybox"], 0)[0] + hdri_skybox_component = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', global_skylight.id, hdri_skybox_component_type + ).GetValue() + editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [hdri_skybox_component]) + general.idle_wait(0.5) + + # Create a "spot_light" entity with "Light" component using Light Type of "Spot (disk)" + spot_light_entity_name = "spot_light" + spot_light = hydra.Entity(spot_light_entity_name) + spot_light.create_entity(math.Vector3(0.7, -2.0, 1.0), [LIGHT_COMPONENT]) + general.log( + f"{spot_light_entity_name}_test: Component added to the entity: " + f"{hydra.has_components(spot_light.id, [LIGHT_COMPONENT])}") + rotation = math.Vector3(DEGREE_RADIAN_FACTOR * 300.0, 0.0, 0.0) + azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", spot_light.id, rotation) + light_component_type = hydra.attach_component_to_entity(spot_light.id, LIGHT_COMPONENT) + editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_type, + LIGHT_TYPE_PROPERTY, + atom_component_helper.LIGHT_TYPES['spot_disk'] + ) + + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_1", spot_light_entity_name) + + # Change default material of ground plane entity and take screenshot + ground_plane_entity_id = hydra.find_entity_by_name("ground_plane") + ground_plane = hydra.Entity(name='ground_plane', id=ground_plane_entity_id) + ground_plane_asset_path = os.path.join("Materials", "Presets", "MacBeth", "22_neutral_5-0_0-70d.azmaterial") + ground_plane_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", ground_plane_asset_path, math.Uuid(), False) + material_property_path = "Default Material|Material Asset" + material_component_type = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Material"], 0)[0] + material_component = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', ground_plane.id, material_component_type).GetValue() + editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + material_component, + material_property_path, + ground_plane_asset_value + ) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_2", spot_light_entity_name) + + # Increase intensity value of the Spot light and take screenshot in game mode + spot_light.get_set_test(0, "Controller|Configuration|Intensity", 800.0) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_3", spot_light_entity_name) + + # Update the Spot light color and take screenshot in game mode + color_value = math.Color(47.0 / 255.0, 75.0 / 255.0, 37.0 / 255.0, 255.0 / 255.0) + spot_light.get_set_test(0, "Controller|Configuration|Color", color_value) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_4", spot_light_entity_name) + + # Update the Shutter controls of the Light component and take screenshot + spot_light.get_set_test(0, "Controller|Configuration|Shutters|Enable shutters", True) + spot_light.get_set_test(0, "Controller|Configuration|Shutters|Inner angle", 60.0) + spot_light.get_set_test(0, "Controller|Configuration|Shutters|Outer angle", 75.0) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_5", spot_light_entity_name) + + # Update the Shadow controls, move the spot_light entity world translate position and take screenshot + spot_light.get_set_test(0, "Controller|Configuration|Shadows|Enable shadow", True) + spot_light.get_set_test(0, "Controller|Configuration|Shadows|Shadowmap size", 256.0) + azlmbr.components.TransformBus( + azlmbr.bus.Event, "SetWorldTranslation", spot_light.id, math.Vector3(0.7, -2.0, 1.9)) + general.idle_wait(1.0) + screenshot_utils.take_screenshot_game_mode("SpotLight_6", spot_light_entity_name) + + +if __name__ == "__main__": + run() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py index de4e28bb36..58b72ef01a 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py @@ -3,17 +3,184 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright SPDX-License-Identifier: Apache-2.0 OR MIT -File to assist with common hydra component functions or constants used across various Atom tests. +File to assist with common hydra component functions used across various Atom tests. """ +import os -# Light type options for the Light component. -LIGHT_TYPES = { - 'unknown': 0, - 'sphere': 1, - 'spot_disk': 2, - 'capsule': 3, - 'quad': 4, - 'polygon': 5, - 'simple_point': 6, - 'simple_spot': 7, -} +from editor_python_test_tools.editor_test_helper import EditorTestHelper + +helper = EditorTestHelper(log_prefix="Atom_EditorTestHelper") + + +def create_basic_atom_level(level_name): + """ + Creates a new level inside the Editor matching level_name & adds the following: + 1. "default_level" entity to hold all other entities. + 2. Adds Grid, Global Skylight (IBL), ground Mesh, Directional Light, Sphere w/ material+mesh, & Camera components. + 3. Each of these components has its settings tweaked slightly to match the ideal scene to test Atom rendering. + :param level_name: name of the level to create and apply this basic setup to. + :return: None + """ + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.camera as camera + import azlmbr.editor as editor + import azlmbr.entity as entity + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.object + + import editor_python_test_tools.hydra_editor_utils as hydra + + # Create a new level. + new_level_name = level_name + heightmap_resolution = 512 + heightmap_meters_per_pixel = 1 + terrain_texture_resolution = 412 + use_terrain = False + + # Return codes are ECreateLevelResult defined in CryEdit.h + return_code = general.create_level_no_prompt( + new_level_name, heightmap_resolution, heightmap_meters_per_pixel, terrain_texture_resolution, use_terrain) + if return_code == 1: + general.log(f"{new_level_name} level already exists") + elif return_code == 2: + general.log("Failed to create directory") + elif return_code == 3: + general.log("Directory length is too long") + elif return_code != 0: + general.log("Unknown error, failed to create level") + else: + general.log(f"{new_level_name} level created successfully") + + # Enable idle and update viewport. + general.idle_enable(True) + general.idle_wait(1.0) + general.update_viewport() + general.idle_wait(0.5) # half a second is more than enough for updating the viewport. + + # Close out problematic windows, FPS meters, and anti-aliasing. + if general.is_helpers_shown(): # Turn off the helper gizmos if visible + general.toggle_helpers() + general.idle_wait(1.0) + if general.is_pane_visible("Error Report"): # Close Error Report windows that block focus. + general.close_pane("Error Report") + if general.is_pane_visible("Error Log"): # Close Error Log windows that block focus. + general.close_pane("Error Log") + general.idle_wait(1.0) + general.run_console("r_displayInfo=0") + general.run_console("r_antialiasingmode=0") + general.idle_wait(1.0) + + # Delete all existing entities & create default_level entity + search_filter = azlmbr.entity.SearchFilter() + all_entities = entity.SearchBus(azlmbr.bus.Broadcast, "SearchEntities", search_filter) + editor.ToolsApplicationRequestBus(bus.Broadcast, "DeleteEntities", all_entities) + default_level = hydra.Entity("default_level") + default_position = math.Vector3(0.0, 0.0, 0.0) + default_level.create_entity(default_position, ["Grid"]) + default_level.get_set_test(0, "Controller|Configuration|Secondary Grid Spacing", 1.0) + + # Set the viewport up correctly after adding the parent default_level entity. + screen_width = 1280 + screen_height = 720 + degree_radian_factor = 0.0174533 # Used by "Rotation" property for the Transform component. + general.set_viewport_size(screen_width, screen_height) + general.update_viewport() + helper.wait_for_condition( + function=lambda: helper.isclose(a=general.get_viewport_size().x, b=screen_width, rel_tol=0.1) + and helper.isclose(a=general.get_viewport_size().y, b=screen_height, rel_tol=0.1), + timeout_in_seconds=4.0 + ) + result = helper.isclose(a=general.get_viewport_size().x, b=screen_width, rel_tol=0.1) and helper.isclose( + a=general.get_viewport_size().y, b=screen_height, rel_tol=0.1) + general.log(general.get_viewport_size().x) + general.log(general.get_viewport_size().y) + general.log(general.get_viewport_size().z) + general.log(f"Viewport is set to the expected size: {result}") + general.log("Basic level created") + general.run_console("r_DisplayInfo = 0") + + # Create global_skylight entity and set the properties + global_skylight = hydra.Entity("global_skylight") + global_skylight.create_entity( + entity_position=default_position, + components=["HDRi Skybox", "Global Skylight (IBL)"], + parent_id=default_level.id) + global_skylight_asset_path = os.path.join( + "LightingPresets", "greenwich_park_02_4k_iblskyboxcm_iblspecular.exr.streamingimage") + global_skylight_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", global_skylight_asset_path, math.Uuid(), False) + global_skylight.get_set_test(0, "Controller|Configuration|Cubemap Texture", global_skylight_asset_value) + global_skylight.get_set_test(1, "Controller|Configuration|Diffuse Image", global_skylight_asset_value) + global_skylight.get_set_test(1, "Controller|Configuration|Specular Image", global_skylight_asset_value) + + # Create ground_plane entity and set the properties + ground_plane = hydra.Entity("ground_plane") + ground_plane.create_entity( + entity_position=default_position, + components=["Material"], + parent_id=default_level.id) + azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalUniformScale", ground_plane.id, 32.0) + ground_plane_material_asset_path = os.path.join( + "Materials", "Presets", "PBR", "metal_chrome.azmaterial") + ground_plane_material_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", ground_plane_material_asset_path, math.Uuid(), False) + ground_plane.get_set_test(0, "Default Material|Material Asset", ground_plane_material_asset_value) + + # Work around to add the correct Atom Mesh component + mesh_type_id = azlmbr.globals.property.EditorMeshComponentTypeId + ground_plane.components.append( + editor.EditorComponentAPIBus( + bus.Broadcast, "AddComponentsOfType", ground_plane.id, [mesh_type_id] + ).GetValue()[0] + ) + ground_plane_mesh_asset_path = os.path.join("Models", "plane.azmodel") + ground_plane_mesh_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", ground_plane_mesh_asset_path, math.Uuid(), False) + ground_plane.get_set_test(1, "Controller|Configuration|Mesh Asset", ground_plane_mesh_asset_value) + + # Create directional_light entity and set the properties + directional_light = hydra.Entity("directional_light") + directional_light.create_entity( + entity_position=math.Vector3(0.0, 0.0, 10.0), + components=["Directional Light"], + parent_id=default_level.id) + directional_light_rotation = math.Vector3(degree_radian_factor * -90.0, 0.0, 0.0) + azlmbr.components.TransformBus( + azlmbr.bus.Event, "SetLocalRotation", directional_light.id, directional_light_rotation) + + # Create sphere entity and set the properties + sphere_entity = hydra.Entity("sphere") + sphere_entity.create_entity( + entity_position=math.Vector3(0.0, 0.0, 1.0), + components=["Material"], + parent_id=default_level.id) + sphere_material_asset_path = os.path.join("Materials", "Presets", "PBR", "metal_brass_polished.azmaterial") + sphere_material_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", sphere_material_asset_path, math.Uuid(), False) + sphere_entity.get_set_test(0, "Default Material|Material Asset", sphere_material_asset_value) + + # Work around to add the correct Atom Mesh component + sphere_entity.components.append( + editor.EditorComponentAPIBus( + bus.Broadcast, "AddComponentsOfType", sphere_entity.id, [mesh_type_id] + ).GetValue()[0] + ) + sphere_mesh_asset_path = os.path.join("Models", "sphere.azmodel") + sphere_mesh_asset_value = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", sphere_mesh_asset_path, math.Uuid(), False) + sphere_entity.get_set_test(1, "Controller|Configuration|Mesh Asset", sphere_mesh_asset_value) + + # Create camera component and set the properties + camera_entity = hydra.Entity("camera") + camera_entity.create_entity( + entity_position=math.Vector3(5.5, -12.0, 9.0), + components=["Camera"], + parent_id=default_level.id) + rotation = math.Vector3( + degree_radian_factor * -27.0, degree_radian_factor * -12.0, degree_radian_factor * 25.0 + ) + azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", camera_entity.id, rotation) + camera_entity.get_set_test(0, "Controller|Configuration|Field of view", 60.0) + camera.EditorCameraViewRequestBus(azlmbr.bus.Event, "ToggleCameraAsActiveView", camera_entity.id) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py new file mode 100644 index 0000000000..88a959f198 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_constants.py @@ -0,0 +1,19 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +Hold constants used across both hydra and non-hydra scripts. +""" + +# Light type options for the Light component. +LIGHT_TYPES = { + 'unknown': 0, + 'sphere': 1, + 'spot_disk': 2, + 'capsule': 3, + 'quad': 4, + 'polygon': 5, + 'simple_point': 6, + 'simple_spot': 7, +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py index 28a4037dcc..a7a02816ac 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/screenshot_utils.py @@ -91,3 +91,20 @@ class ScreenshotHelper(object): else: frames_waited = frames_waited + 1 general.log(f"(waited {frames_waited} frames)") + + +def take_screenshot_game_mode(screenshot_name, entity_name=None): + """ + Enters game mode & takes a screenshot, then exits game mode after. + :param screenshot_name: name to give the captured screenshot .ppm file. + :param entity_name: name of the entity being tested (for generating unique log lines). + :return: None + """ + general.enter_game_mode() + helper.wait_for_condition(lambda: general.is_in_game_mode(), 2.0) + general.log(f"{entity_name}_test: Entered game mode: {general.is_in_game_mode()}") + ScreenshotHelper(general.idle_wait_frames).capture_screenshot_blocking(f"{screenshot_name}.ppm") + general.idle_wait(1.0) + general.exit_game_mode() + helper.wait_for_condition(lambda: not general.is_in_game_mode(), 2.0) + general.log(f"{entity_name}_test: Exit game mode: {not general.is_in_game_mode()}") diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm new file mode 100644 index 0000000000..0725999dcf --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_1.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:954d7d0df47c840a24e313893800eb3126d0c0d47c3380926776b51833778db7 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm new file mode 100644 index 0000000000..3a45bd31e3 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_2.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e81c19128f42ba362a2d5f3ccf159dfbc942d67ceeb1ac8c21f295a6fd9d2ce5 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm new file mode 100644 index 0000000000..15d679b784 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_3.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e20801213e065b6ea8c95ede81c23faa9b6dc70a2002dc5bced293e1bed989f +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm new file mode 100644 index 0000000000..85c083a386 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_4.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e250f812e594e5152bf2d6f23caa8b53b78276bfdf344d7a8d355dd96cb995c0 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm new file mode 100644 index 0000000000..d575de761e --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/AreaLight_5.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95be359041f8291c74b335297a4dfe9902a180510f24a181b15e1a5ba4d3b024 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm new file mode 100644 index 0000000000..bbbd127929 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_1.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:118e43e4b915e262726183467cc4b82f244565213fea5b6bfe02be07f0851ab1 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm new file mode 100644 index 0000000000..8e716fabcc --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_2.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc2ce3256a6552975962c9e113c52c1a22bf3817d417151f6f60640dd568e0fa +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm new file mode 100644 index 0000000000..6b6a5a5d6e --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_3.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:287d98890b35427688999760f9d066bcbff1a3bc9001534241dc212b32edabd8 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm new file mode 100644 index 0000000000..eb05228cc2 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_4.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66e91c92c868167c850078cd91714db47e10a96e23cc30191994486bd79c353f +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm new file mode 100644 index 0000000000..5e12edc46d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_5.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d950d173f5101820c5e18205401ca08ce5feeff2302ac2920b292750d86a8fa4 +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm new file mode 100644 index 0000000000..d442d90287 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/golden_images/SpotLight_6.ppm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72eddb7126eae0c839b933886e0fb69d78229f72d49ef13199de28df2b7879db +size 6220817 diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py index 9165bced90..7be1ed1b12 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py @@ -15,11 +15,11 @@ import pytest import ly_test_tools.environment.file_system as file_system from ly_test_tools.image.screenshot_compare_qssim import qssim as compare_screenshots from ly_test_tools.benchmark.data_aggregator import BenchmarkDataAggregator + import editor_python_test_tools.hydra_test_utils as hydra logger = logging.getLogger(__name__) DEFAULT_SUBFOLDER_PATH = 'user/PythonTests/Automated/Screenshots' -EDITOR_TIMEOUT = 600 TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "atom_hydra_scripts") @@ -67,6 +67,7 @@ class TestAllComponentsIndepthTests(object): "Trace::Assert", "Trace::Error", "Traceback (most recent call last):", + "Screenshot failed" ] hydra.launch_and_validate_results( @@ -74,7 +75,7 @@ class TestAllComponentsIndepthTests(object): TEST_DIRECTORY, editor, "hydra_GPUTest_BasicLevelSetup.py", - timeout=EDITOR_TIMEOUT, + timeout=180, expected_lines=level_creation_expected_lines, unexpected_lines=unexpected_lines, halt_on_unexpected=True, @@ -85,6 +86,60 @@ class TestAllComponentsIndepthTests(object): for test_screenshot, golden_screenshot in zip(test_screenshots, golden_images): compare_screenshots(test_screenshot, golden_screenshot) + def test_LightComponent_ScreenshotMatchesGoldenImage( + self, request, editor, workspace, project, launcher_platform, level): + """ + Please review the hydra script run by this test for more specific test info. + Tests that the Light component screenshots in a rendered level appear the same as the golden images. + """ + screenshot_names = [ + "AreaLight_1.ppm", + "AreaLight_2.ppm", + "AreaLight_3.ppm", + "AreaLight_4.ppm", + "AreaLight_5.ppm", + "SpotLight_1.ppm", + "SpotLight_2.ppm", + "SpotLight_3.ppm", + "SpotLight_4.ppm", + "SpotLight_5.ppm", + "SpotLight_6.ppm", + ] + test_screenshots = [] + for screenshot in screenshot_names: + screenshot_path = os.path.join(workspace.paths.project(), DEFAULT_SUBFOLDER_PATH, screenshot) + test_screenshots.append(screenshot_path) + file_system.delete(test_screenshots, True, True) + + golden_images = [] + for golden_image in screenshot_names: + golden_image_path = os.path.join(golden_images_directory(), golden_image) + golden_images.append(golden_image_path) + + expected_lines = ["Light component tests completed."] + unexpected_lines = [ + "Trace::Assert", + "Trace::Error", + "Traceback (most recent call last):", + "Screenshot failed", + ] + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "hydra_GPUTest_LightComponent.py", + timeout=180, + expected_lines=expected_lines, + unexpected_lines=unexpected_lines, + halt_on_unexpected=True, + cfg_args=[level], + null_renderer=False, + ) + + for test_screenshot, golden_screenshot in zip(test_screenshots, golden_images): + compare_screenshots(test_screenshot, golden_screenshot) + + @pytest.mark.parametrize('rhi', ['dx12', 'vulkan']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.parametrize("launcher_platform", ["windows_editor"]) @@ -116,7 +171,7 @@ class TestPerformanceBenchmarkSuite(object): TEST_DIRECTORY, editor, "hydra_GPUTest_AtomFeatureIntegrationBenchmark.py", - timeout=EDITOR_TIMEOUT, + timeout=600, expected_lines=expected_lines, unexpected_lines=unexpected_lines, halt_on_unexpected=True, diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index 98d2ba0632..39689816b8 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -12,7 +12,7 @@ import os import pytest import editor_python_test_tools.hydra_test_utils as hydra -from atom_renderer.atom_utils.atom_component_helper import LIGHT_TYPES +from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES logger = logging.getLogger(__name__) EDITOR_TIMEOUT = 120 From 2564e8f8dce6fc65804500dee166f72a574477f9 Mon Sep 17 00:00:00 2001 From: smurly Date: Wed, 11 Aug 2021 12:15:31 -0700 Subject: [PATCH 122/205] MaterialEditor BasicTests added to AutomatedTesting for AR (#3022) * MaterialEditor BasicTests added to AutomatedTesting for AR Signed-off-by: Scott Murray * launch_and_validate_results adding a waiter.wait_for to the log monitor so the log file exists Signed-off-by: Scott Murray --- .../AssetProcessorGamePlatformConfig.setreg | 19 ++ .../hydra_test_utils.py | 15 +- .../hydra_AtomMaterialEditor_BasicTests.py | 183 ++++++++++++ .../atom_utils/material_editor_utils.py | 274 ++++++++++++++++++ .../atom_renderer/test_Atom_MainSuite.py | 63 ++++ 5 files changed, 552 insertions(+), 2 deletions(-) create mode 100644 AutomatedTesting/AssetProcessorGamePlatformConfig.setreg create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py diff --git a/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg b/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg new file mode 100644 index 0000000000..5457b3f1ca --- /dev/null +++ b/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg @@ -0,0 +1,19 @@ +{ + "Amazon": { + "AssetProcessor": { + "Settings": { + "RC cgf": { + "ignore": true + }, + "RC fbx": { + "ignore": true + }, + "ScanFolder AtomTestData": { + "watch": "@ENGINEROOT@/Gems/Atom/TestData", + "recursive": 1, + "order": 1000 + } + } + } + } +} diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py index 3004b9ec7d..3d4d9ea419 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py @@ -29,7 +29,7 @@ def teardown_editor(editor): def launch_and_validate_results(request, test_directory, editor, editor_script, expected_lines, unexpected_lines=[], halt_on_unexpected=False, run_python="--runpythontest", auto_test_mode=True, null_renderer=True, cfg_args=[], - timeout=300): + timeout=300, log_file_name="Editor.log"): """ Runs the Editor with the specified script, and monitors for expected log lines. :param request: Special fixture providing information of the requesting test function. @@ -44,6 +44,7 @@ def launch_and_validate_results(request, test_directory, editor, editor_script, :param null_renderer: Specifies the test does not require the renderer. Defaults to True. :param cfg_args: Additional arguments for CFG, such as LevelName. :param timeout: Length of time for test to run. Default is 60. + :param log_file_name: Name of the log file created by the editor. Defaults to 'Editor.log' """ test_case = os.path.join(test_directory, editor_script) request.addfinalizer(lambda: teardown_editor(editor)) @@ -58,7 +59,17 @@ def launch_and_validate_results(request, test_directory, editor, editor_script, with editor.start(): - editorlog_file = os.path.join(editor.workspace.paths.project_log(), 'Editor.log') + editorlog_file = os.path.join(editor.workspace.paths.project_log(), log_file_name) + + # Log monitor requires the file to exist. + logger.debug(f"Waiting until log file <{editorlog_file}> exists...") + waiter.wait_for( + lambda: os.path.exists(editorlog_file), + timeout=60, + exc=f"Log file '{editorlog_file}' was never created by another process.", + interval=1, + ) + logger.debug(f"Done! log file <{editorlog_file}> exists.") # Initialize the log monitor and set time to wait for log creation log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=editor, log_file_path=editorlog_file) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py new file mode 100644 index 0000000000..b3c51ca912 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py @@ -0,0 +1,183 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +import azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe +This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe +You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. +""" + +import os +import sys +import time + +import azlmbr.math as math +import azlmbr.paths + +sys.path.append(os.path.join(azlmbr.paths.devassets, "Gem", "PythonTests")) + +import atom_renderer.atom_utils.material_editor_utils as material_editor + +NEW_MATERIAL = "test_material.material" +NEW_MATERIAL_1 = "test_material_1.material" +NEW_MATERIAL_2 = "test_material_2.material" +TEST_MATERIAL_1 = "001_DefaultWhite.material" +TEST_MATERIAL_2 = "002_BaseColorLerp.material" +TEST_MATERIAL_3 = "003_MetalMatte.material" +TEST_DATA_PATH = os.path.join( + azlmbr.paths.devroot, "Gems", "Atom", "TestData", "TestData", "Materials", "StandardPbrTestCases" +) +MATERIAL_TYPE_PATH = os.path.join( + azlmbr.paths.devroot, "Gems", "Atom", "Feature", "Common", "Assets", + "Materials", "Types", "StandardPBR.materialtype", +) + + +def run(): + """ + Summary: + Material Editor basic tests including the below + 1. Opening an Existing Asset + 2. Creating a New Asset + 3. Closing Selected Material + 4. Closing All Materials + 5. Closing all but Selected Material + 6. Saving Material + 7. Saving as a New Material + 8. Saving as a Child Material + 9. Saving all Open Materials + + Expected Result: + All the above functions work as expected in Material Editor. + + :return: None + """ + + # 1) Test Case: Opening an Existing Asset + document_id = material_editor.open_material(MATERIAL_TYPE_PATH) + print(f"Material opened: {material_editor.is_open(document_id)}") + + # Verify if the test material exists initially + target_path = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL) + print(f"Test asset doesn't exist initially: {not os.path.exists(target_path)}") + + # 2) Test Case: Creating a New Material Using Existing One + material_editor.save_document_as_child(document_id, target_path) + material_editor.wait_for_condition(lambda: os.path.exists(target_path), 2.0) + print(f"New asset created: {os.path.exists(target_path)}") + + # Verify if the newly created document is open + new_document_id = material_editor.open_material(target_path) + material_editor.wait_for_condition(lambda: material_editor.is_open(new_document_id)) + print(f"New Material opened: {material_editor.is_open(new_document_id)}") + + # 3) Test Case: Closing Selected Material + print(f"Material closed: {material_editor.close_document(new_document_id)}") + + # Open materials initially + document1_id, document2_id, document3_id = ( + material_editor.open_material(os.path.join(TEST_DATA_PATH, material)) + for material in [TEST_MATERIAL_1, TEST_MATERIAL_2, TEST_MATERIAL_3] + ) + + # 4) Test Case: Closing All Materials + print(f"All documents closed: {material_editor.close_all_documents()}") + + # 5) Test Case: Closing all but Selected Material + document1_id, document2_id, document3_id = ( + material_editor.open_material(os.path.join(TEST_DATA_PATH, material)) + for material in [TEST_MATERIAL_1, TEST_MATERIAL_2, TEST_MATERIAL_3] + ) + result = material_editor.close_all_except_selected(document1_id) + print(f"Close All Except Selected worked as expected: {result and material_editor.is_open(document1_id)}") + + # 6) Test Case: Saving Material + document_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + property_name = azlmbr.name.Name("baseColor.color") + initial_color = material_editor.get_property(document_id, property_name) + # Assign new color to the material file and save the actual material + expected_color = math.Color(0.25, 0.25, 0.25, 1.0) + material_editor.set_property(document_id, property_name, expected_color) + material_editor.save_document(document_id) + + # 7) Test Case: Saving as a New Material + # Assign new color to the material file and save the document as copy + expected_color_1 = math.Color(0.5, 0.5, 0.5, 1.0) + material_editor.set_property(document_id, property_name, expected_color_1) + target_path_1 = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL_1) + material_editor.save_document_as_copy(document_id, target_path_1) + time.sleep(2.0) + + # 8) Test Case: Saving as a Child Material + # Assign new color to the material file save the document as child + expected_color_2 = math.Color(0.75, 0.75, 0.75, 1.0) + material_editor.set_property(document_id, property_name, expected_color_2) + target_path_2 = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL_2) + material_editor.save_document_as_child(document_id, target_path_2) + time.sleep(2.0) + + # Close/Reopen documents + material_editor.close_all_documents() + document_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + document1_id = material_editor.open_material(target_path_1) + document2_id = material_editor.open_material(target_path_2) + + # Verify if the changes are saved in the actual document + actual_color = material_editor.get_property(document_id, property_name) + print(f"Actual Document saved with changes: {material_editor.compare_colors(actual_color, expected_color)}") + + # Verify if the changes are saved in the document saved as copy + actual_color = material_editor.get_property(document1_id, property_name) + result_copy = material_editor.compare_colors(actual_color, expected_color_1) + print(f"Document saved as copy is saved with changes: {result_copy}") + + # Verify if the changes are saved in the document saved as child + actual_color = material_editor.get_property(document2_id, property_name) + result_child = material_editor.compare_colors(actual_color, expected_color_2) + print(f"Document saved as child is saved with changes: {result_child}") + + # Revert back the changes in the actual document + material_editor.set_property(document_id, property_name, initial_color) + material_editor.save_document(document_id) + material_editor.close_all_documents() + + # 9) Test Case: Saving all Open Materials + # Open first material and make change to the values + document1_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + property1_name = azlmbr.name.Name("metallic.factor") + initial_metallic_factor = material_editor.get_property(document1_id, property1_name) + expected_metallic_factor = 0.444 + material_editor.set_property(document1_id, property1_name, expected_metallic_factor) + + # Open second material and make change to the values + document2_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_2)) + property2_name = azlmbr.name.Name("baseColor.color") + initial_color = material_editor.get_property(document2_id, property2_name) + expected_color = math.Color(0.4156, 0.0196, 0.6862, 1.0) + material_editor.set_property(document2_id, property2_name, expected_color) + + # Save all and close all documents + material_editor.save_all() + material_editor.close_all_documents() + + # Reopen materials and verify values + document1_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + result = material_editor.is_close( + material_editor.get_property(document1_id, property1_name), expected_metallic_factor, 0.00001 + ) + document2_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_2)) + result = result and material_editor.compare_colors( + expected_color, material_editor.get_property(document2_id, property2_name)) + print(f"Save All worked as expected: {result}") + + # Revert the changes made + material_editor.set_property(document1_id, property1_name, initial_metallic_factor) + material_editor.set_property(document2_id, property2_name, initial_color) + material_editor.save_all() + material_editor.close_all_documents() + + +if __name__ == "__main__": + run() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py new file mode 100644 index 0000000000..77d1285188 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py @@ -0,0 +1,274 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +import azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe +This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe +You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. +""" + +import os +import sys +import time +import azlmbr.atom +import azlmbr.materialeditor as materialeditor +import azlmbr.bus as bus +import azlmbr.atomtools.general as general + + +def is_close(actual, expected, buffer=sys.float_info.min): + """ + :param actual: actual value + :param expected: expected value + :param buffer: acceptable variation from expected + :return: bool + """ + return abs(actual - expected) < buffer + + +def compare_colors(color1, color2, buffer=0.00001): + """ + Compares the red, green and blue properties of a color allowing a slight variance of buffer + :param color1: first color to compare + :param color2: second color + :param buffer: allowed variance in individual color value + :return: bool + """ + return ( + is_close(color1.r, color2.r, buffer) + and is_close(color1.g, color2.g, buffer) + and is_close(color1.b, color2.b, buffer) + ) + + +def open_material(file_path): + """ + :return: uuid of material document opened + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "OpenDocument", file_path) + + +def is_open(document_id): + """ + :return: bool + """ + return materialeditor.MaterialDocumentRequestBus(bus.Event, "IsOpen", document_id) + + +def save_document(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "SaveDocument", document_id) + + +def save_document_as_copy(document_id, target_path): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus( + bus.Broadcast, "SaveDocumentAsCopy", document_id, target_path + ) + + +def save_document_as_child(document_id, target_path): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus( + bus.Broadcast, "SaveDocumentAsChild", document_id, target_path + ) + + +def save_all(): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "SaveAllDocuments") + + +def close_document(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseDocument", document_id) + + +def close_all_documents(): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocuments") + + +def close_all_except_selected(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocumentsExcept", document_id) + + +def get_property(document_id, property_name): + """ + :return: property value or invalid value if the document is not open or the property_name can't be found + """ + return materialeditor.MaterialDocumentRequestBus(bus.Event, "GetPropertyValue", document_id, property_name) + + +def set_property(document_id, property_name, value): + materialeditor.MaterialDocumentRequestBus(bus.Event, "SetPropertyValue", document_id, property_name, value) + + +def is_pane_visible(pane_name): + """ + :return: bool + """ + return materialeditor.MaterialEditorWindowRequestBus(bus.Broadcast, "IsDockWidgetVisible", pane_name) + + +def set_pane_visibility(pane_name, value): + materialeditor.MaterialEditorWindowRequestBus(bus.Broadcast, "SetDockWidgetVisible", pane_name, value) + + +def select_lighting_config(config_name): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SelectLightingPresetByName", config_name) + + +def set_grid_enable_disable(value): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SetGridEnabled", value) + + +def get_grid_enable_disable(): + """ + :return: bool + """ + return azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "GetGridEnabled") + + +def set_shadowcatcher_enable_disable(value): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SetShadowCatcherEnabled", value) + + +def get_shadowcatcher_enable_disable(): + """ + :return: bool + """ + return azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "GetShadowCatcherEnabled") + + +def select_model_config(configname): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SelectModelPresetByName", configname) + + +def wait_for_condition(function, timeout_in_seconds=1.0): + # type: (function, float) -> bool + """ + Function to run until it returns True or timeout is reached + the function can have no parameters and + waiting idle__wait_* is handled here not in the function + + :param function: a function that returns a boolean indicating a desired condition is achieved + :param timeout_in_seconds: when reached, function execution is abandoned and False is returned + """ + with Timeout(timeout_in_seconds) as t: + while True: + try: + general.idle_wait_frames(1) + except Exception: + print("WARNING: Couldn't wait for frame") + + if t.timed_out: + return False + + ret = function() + if not isinstance(ret, bool): + raise TypeError("return value for wait_for_condition function must be a bool") + if ret: + return True + + +class Timeout: + # type: (float) -> None + """ + contextual timeout + :param seconds: float seconds to allow before timed_out is True + """ + + def __init__(self, seconds): + self.seconds = seconds + + def __enter__(self): + self.die_after = time.time() + self.seconds + return self + + def __exit__(self, type, value, traceback): + pass + + @property + def timed_out(self): + return time.time() > self.die_after + + +screenshotsFolder = os.path.join(azlmbr.paths.devroot, "AtomTest", "Cache" "pc", "Screenshots") + + +class ScreenshotHelper: + """ + A helper to capture screenshots and wait for them. + """ + + def __init__(self, idle_wait_frames_callback): + super().__init__() + self.done = False + self.capturedScreenshot = False + self.max_frames_to_wait = 60 + + self.idle_wait_frames_callback = idle_wait_frames_callback + + def capture_screenshot_blocking(self, filename): + """ + Capture a screenshot and block the execution until the screenshot has been written to the disk. + """ + self.handler = azlmbr.atom.FrameCaptureNotificationBusHandler() + self.handler.connect() + self.handler.add_callback("OnCaptureFinished", self.on_screenshot_captured) + + self.done = False + self.capturedScreenshot = False + success = azlmbr.atom.FrameCaptureRequestBus(azlmbr.bus.Broadcast, "CaptureScreenshot", filename) + if success: + self.wait_until_screenshot() + print("Screenshot taken.") + else: + print("screenshot failed") + return self.capturedScreenshot + + def on_screenshot_captured(self, parameters): + # the parameters come in as a tuple + if parameters[0]: + print("screenshot saved: {}".format(parameters[1])) + self.capturedScreenshot = True + else: + print("screenshot failed: {}".format(parameters[1])) + self.done = True + self.handler.disconnect() + + def wait_until_screenshot(self): + frames_waited = 0 + while self.done == False: + self.idle_wait_frames_callback(1) + if frames_waited > self.max_frames_to_wait: + print("timeout while waiting for the screenshot to be written") + self.handler.disconnect() + break + else: + frames_waited = frames_waited + 1 + print("(waited {} frames)".format(frames_waited)) + + +def capture_screenshot(file_path): + return ScreenshotHelper(azlmbr.atomtools.general.idle_wait_frames).capture_screenshot_blocking( + os.path.join(file_path) + ) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index 39689816b8..be75801b63 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -11,6 +11,7 @@ import os import pytest +import ly_test_tools.environment.file_system as file_system import editor_python_test_tools.hydra_test_utils as hydra from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES @@ -242,3 +243,65 @@ class TestAtomEditorComponentsMain(object): null_renderer=True, cfg_args=cfg_args, ) + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("launcher_platform", ['windows_generic']) +@pytest.mark.system +class TestMaterialEditorBasicTests(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request, workspace, project): + def delete_files(): + file_system.delete( + [ + os.path.join(workspace.paths.project(), "Materials", "test_material.material"), + os.path.join(workspace.paths.project(), "Materials", "test_material_1.material"), + os.path.join(workspace.paths.project(), "Materials", "test_material_2.material"), + ], + True, + True, + ) + # Cleanup our newly created materials + delete_files() + + def teardown(): + # Cleanup our newly created materials + delete_files() + + request.addfinalizer(teardown) + + @pytest.mark.parametrize("exe_file_name", ["MaterialEditor"]) + def test_MaterialEditorBasicTests( + self, request, workspace, project, launcher_platform, generic_launcher, exe_file_name): + + expected_lines = [ + "Material opened: True", + "Test asset doesn't exist initially: True", + "New asset created: True", + "New Material opened: True", + "Material closed: True", + "All documents closed: True", + "Close All Except Selected worked as expected: True", + "Actual Document saved with changes: True", + "Document saved as copy is saved with changes: True", + "Document saved as child is saved with changes: True", + "Save All worked as expected: True", + ] + unexpected_lines = [ + # "Trace::Assert", + # "Trace::Error", + "Traceback (most recent call last):" + ] + + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + generic_launcher, + "hydra_AtomMaterialEditor_BasicTests.py", + run_python="--runpython", + timeout=80, + expected_lines=expected_lines, + unexpected_lines=unexpected_lines, + halt_on_unexpected=True, + log_file_name="MaterialEditor.log", + ) From ce7598c10bbc615ba3a954e6bdbfd7ced16c9e61 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Wed, 11 Aug 2021 12:59:32 -0700 Subject: [PATCH 123/205] [redcode/crythread-2nd-pass] fixed missing includes Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp | 1 + Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm | 2 ++ Code/Legacy/CryCommon/VectorMap.h | 1 + .../AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h | 2 +- 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp b/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp index 1e87b902a6..3030dcc740 100644 --- a/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp +++ b/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp @@ -10,6 +10,7 @@ #include #include // for AZ_MAX_PATH_LEN +#include #include diff --git a/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm b/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm index cfba0d8aac..f4ea67c6e6 100644 --- a/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm +++ b/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm @@ -11,6 +11,8 @@ #include <../Common/Apple/Launcher_Apple.h> #include <../Common/UnixLike/Launcher_UnixLike.h> +#include + #if AZ_TESTS_ENABLED int main(int argc, char* argv[]) diff --git a/Code/Legacy/CryCommon/VectorMap.h b/Code/Legacy/CryCommon/VectorMap.h index 1a42f0e48f..ee99c6f952 100644 --- a/Code/Legacy/CryCommon/VectorMap.h +++ b/Code/Legacy/CryCommon/VectorMap.h @@ -14,6 +14,7 @@ #define CRYINCLUDE_CRYCOMMON_VECTORMAP_H #pragma once +#include // for stl::free_container //-------------------------------------------------------------------------- // VectorMap diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h index 7dd2629bd0..018bc74877 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h @@ -96,7 +96,7 @@ namespace AZ void UnregisterFont(const char* fontName); private: - using FontMap = std::unordered_map; + using FontMap = AZStd::unordered_map; using FontMapItor = FontMap::iterator; using FontMapConstItor = FontMap::const_iterator; From 3142367fa8910475223b1556ec1144fca75186ae Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Wed, 11 Aug 2021 15:21:54 -0500 Subject: [PATCH 124/205] move main window bus reflection to atom tools update python scripts Signed-off-by: Guthrie Adams --- .../Code/Source/AtomToolsFrameworkModule.cpp | 7 +- .../AtomToolsMainWindowSystemComponent.cpp | 73 +++++++++++++++++++ .../AtomToolsMainWindowSystemComponent.h | 36 +++++++++ .../Code/atomtoolsframework_files.cmake | 2 + .../Window/MaterialEditorWindowComponent.cpp | 35 ++------- .../Scripts/GenerateAllMaterialScreenshots.py | 7 +- ...ShaderManagementConsoleWindowComponent.cpp | 19 ++--- 7 files changed, 132 insertions(+), 47 deletions(-) create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.cpp create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.h diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp index bee27dfdca..b601596032 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp @@ -8,20 +8,23 @@ #include #include +#include namespace AtomToolsFramework { AtomToolsFrameworkModule::AtomToolsFrameworkModule() { m_descriptors.insert(m_descriptors.end(), { - AtomToolsFrameworkSystemComponent::CreateDescriptor(), - }); + AtomToolsFrameworkSystemComponent::CreateDescriptor(), + AtomToolsMainWindowSystemComponent::CreateDescriptor(), + }); } AZ::ComponentTypeList AtomToolsFrameworkModule::GetRequiredSystemComponents() const { return AZ::ComponentTypeList{ azrtti_typeid(), + azrtti_typeid(), }; } } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.cpp new file mode 100644 index 0000000000..3114a5d9f7 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include + +namespace AtomToolsFramework +{ + void AtomToolsMainWindowSystemComponent::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serialize = azrtti_cast(context)) + { + serialize->Class() + ->Version(0); + } + + if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) + { + behaviorContext->EBus("AtomToolsMainWindowFactoryRequestBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Editor") + ->Attribute(AZ::Script::Attributes::Module, "atomtools") + ->Event("CreateMainWindow", &AtomToolsMainWindowFactoryRequestBus::Events::CreateMainWindow) + ->Event("DestroyMainWindow", &AtomToolsMainWindowFactoryRequestBus::Events::DestroyMainWindow) + ; + + behaviorContext->EBus("AtomToolsMainWindowRequestBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Editor") + ->Attribute(AZ::Script::Attributes::Module, "atomtools") + ->Event("ActivateWindow", &AtomToolsMainWindowRequestBus::Events::ActivateWindow) + ->Event("SetDockWidgetVisible", &AtomToolsMainWindowRequestBus::Events::SetDockWidgetVisible) + ->Event("IsDockWidgetVisible", &AtomToolsMainWindowRequestBus::Events::IsDockWidgetVisible) + ->Event("GetDockWidgetNames", &AtomToolsMainWindowRequestBus::Events::GetDockWidgetNames) + ->Event("ResizeViewportRenderTarget", &AtomToolsMainWindowRequestBus::Events::ResizeViewportRenderTarget) + ->Event("LockViewportRenderTargetSize", &AtomToolsMainWindowRequestBus::Events::LockViewportRenderTargetSize) + ->Event("UnlockViewportRenderTargetSize", &AtomToolsMainWindowRequestBus::Events::UnlockViewportRenderTargetSize) + ; + } + } + + void AtomToolsMainWindowSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("AtomToolsMainWindowSystemService")); + } + + void AtomToolsMainWindowSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("AtomToolsMainWindowSystemService")); + } + + void AtomToolsMainWindowSystemComponent::Init() + { + } + + void AtomToolsMainWindowSystemComponent::Activate() + { + } + + void AtomToolsMainWindowSystemComponent::Deactivate() + { + } + +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.h new file mode 100644 index 0000000000..b982327326 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace AtomToolsFramework +{ + //! AtomToolsMainWindowSystemComponent is used for initialization and registration of other classes. + class AtomToolsMainWindowSystemComponent + : public AZ::Component + { + public: + AZ_COMPONENT(AtomToolsMainWindowSystemComponent, "{6E42380B-4ECD-47CF-B904-E16AB4E87D0D}"); + + static void Reflect(AZ::ReflectContext* context); + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + + private: + + //////////////////////////////////////////////////////////////////////// + // AZ::Component interface implementation + void Init() override; + void Activate() override; + void Deactivate() override; + //////////////////////////////////////////////////////////////////////// + }; +} diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index 49e641eb9c..8eb82778e3 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -45,4 +45,6 @@ set(FILES Source/Viewport/RenderViewportWidget.cpp Source/Viewport/ModularViewportCameraController.cpp Source/Window/AtomToolsMainWindow.cpp + Source/Window/AtomToolsMainWindowSystemComponent.cpp + Source/Window/AtomToolsMainWindowSystemComponent.h ) \ No newline at end of file diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 8406ae891f..5359ba8e53 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -30,47 +30,24 @@ namespace MaterialEditor serialize->Class() ->Version(0); } - - if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) - { - behaviorContext->EBus("MaterialEditorWindowAtomRequestBus") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) - ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "materialeditor") - ->Event("CreateMaterialEditorWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::CreateMainWindow) - ->Event("DestroyMaterialEditorWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::DestroyMainWindow) - ; - - behaviorContext->EBus("MaterialEditorWindowRequestBus") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) - ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "materialeditor") - ->Event("ActivateWindow", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::ActivateWindow) - ->Event("SetDockWidgetVisible", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::SetDockWidgetVisible) - ->Event("IsDockWidgetVisible", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::IsDockWidgetVisible) - ->Event("GetDockWidgetNames", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::GetDockWidgetNames) - ->Event("ResizeViewportRenderTarget", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::ResizeViewportRenderTarget) - ->Event("LockViewportRenderTargetSize", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::LockViewportRenderTargetSize) - ->Event("UnlockViewportRenderTargetSize", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::UnlockViewportRenderTargetSize) - ; - } } void MaterialEditorWindowComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { - required.push_back(AZ_CRC("AssetBrowserService", 0x1e54fffb)); - required.push_back(AZ_CRC("PropertyManagerService", 0x63a3d7ad)); - required.push_back(AZ_CRC("SourceControlService", 0x67f338fd)); + required.push_back(AZ_CRC_CE("AssetBrowserService")); + required.push_back(AZ_CRC_CE("PropertyManagerService")); + required.push_back(AZ_CRC_CE("SourceControlService")); + required.push_back(AZ_CRC_CE("AtomToolsMainWindowSystemService")); } void MaterialEditorWindowComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { - provided.push_back(AZ_CRC("MaterialEditorWindowService", 0xb6e7d922)); + provided.push_back(AZ_CRC_CE("MaterialEditorWindowService")); } void MaterialEditorWindowComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { - incompatible.push_back(AZ_CRC("MaterialEditorWindowService", 0xb6e7d922)); + incompatible.push_back(AZ_CRC_CE("MaterialEditorWindowService")); } void MaterialEditorWindowComponent::Init() diff --git a/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py b/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py index d7f52d7a24..2116a3de6c 100755 --- a/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py +++ b/Gems/Atom/Tools/MaterialEditor/Scripts/GenerateAllMaterialScreenshots.py @@ -6,6 +6,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT """ import azlmbr.bus +import azlmbr.atomtools import azlmbr.materialeditor import azlmbr.name import azlmbr.render @@ -122,12 +123,12 @@ def CaptureScreenshot(screenshotOutputPath): def ResizeViewport(width, height): # This locks the size of the render target to the desired resolution - azlmbr.materialeditor.MaterialEditorWindowRequestBus(azlmbr.bus.Broadcast, 'LockViewportRenderTargetSize', width, height) + azlmbr.atomtools.AtomToolsMainWindowRequestBus(azlmbr.bus.Broadcast, 'LockViewportRenderTargetSize', width, height) # This resizes the window to closely match the render target resolution so it doesn't appear stretched while the script is running - azlmbr.materialeditor.MaterialEditorWindowRequestBus(azlmbr.bus.Broadcast, 'ResizeViewportRenderTarget', width, height) + azlmbr.atomtools.AtomToolsMainWindowRequestBus(azlmbr.bus.Broadcast, 'ResizeViewportRenderTarget', width, height) def ReleaseViewportResolutionLock(): - azlmbr.materialeditor.MaterialEditorWindowRequestBus(azlmbr.bus.Broadcast, 'UnlockViewportRenderTargetSize') + azlmbr.atomtools.AtomToolsMainWindowRequestBus(azlmbr.bus.Broadcast, 'UnlockViewportRenderTargetSize') def GenerateMaterialScreenshot(materialName, uniqueSuffix="", diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp index 44715ef64f..a89cdfddb8 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp @@ -44,14 +44,6 @@ namespace ShaderManagementConsole if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("ShaderManagementConsoleWindowRequestBus") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) - ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "shadermanagementconsole") - ->Event("CreateShaderManagementConsoleWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::CreateMainWindow) - ->Event("DestroyShaderManagementConsoleWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::DestroyMainWindow) - ; - behaviorContext->EBus("ShaderManagementConsoleRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) ->Attribute(AZ::Script::Attributes::Category, "Editor") @@ -65,19 +57,20 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindowComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { - required.push_back(AZ_CRC("AssetBrowserService", 0x1e54fffb)); - required.push_back(AZ_CRC("PropertyManagerService", 0x63a3d7ad)); - required.push_back(AZ_CRC("SourceControlService", 0x67f338fd)); + required.push_back(AZ_CRC_CE("AssetBrowserService")); + required.push_back(AZ_CRC_CE("PropertyManagerService")); + required.push_back(AZ_CRC_CE("SourceControlService")); + required.push_back(AZ_CRC_CE("AtomToolsMainWindowSystemService")); } void ShaderManagementConsoleWindowComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { - provided.push_back(AZ_CRC("ShaderManagementConsoleWindowService", 0xb6e7d922)); + provided.push_back(AZ_CRC_CE("ShaderManagementConsoleWindowService")); } void ShaderManagementConsoleWindowComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { - incompatible.push_back(AZ_CRC("ShaderManagementConsoleWindowService", 0xb6e7d922)); + incompatible.push_back(AZ_CRC_CE("ShaderManagementConsoleWindowService")); } void ShaderManagementConsoleWindowComponent::Init() From 633cf818f7498f7a764629693cfd01663290eb07 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Wed, 11 Aug 2021 15:54:13 -0500 Subject: [PATCH 125/205] updating test scripts Signed-off-by: Guthrie Adams --- .../atom_renderer/atom_utils/material_editor_utils.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py index 77d1285188..1d72885504 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py @@ -13,9 +13,9 @@ import os import sys import time import azlmbr.atom +import azlmbr.atomtools as atomtools import azlmbr.materialeditor as materialeditor import azlmbr.bus as bus -import azlmbr.atomtools.general as general def is_close(actual, expected, buffer=sys.float_info.min): @@ -125,11 +125,11 @@ def is_pane_visible(pane_name): """ :return: bool """ - return materialeditor.MaterialEditorWindowRequestBus(bus.Broadcast, "IsDockWidgetVisible", pane_name) + return atomtools.AtomToolsWindowRequestBus(bus.Broadcast, "IsDockWidgetVisible", pane_name) def set_pane_visibility(pane_name, value): - materialeditor.MaterialEditorWindowRequestBus(bus.Broadcast, "SetDockWidgetVisible", pane_name, value) + atomtools.AtomToolsWindowRequestBus(bus.Broadcast, "SetDockWidgetVisible", pane_name, value) def select_lighting_config(config_name): @@ -175,7 +175,7 @@ def wait_for_condition(function, timeout_in_seconds=1.0): with Timeout(timeout_in_seconds) as t: while True: try: - general.idle_wait_frames(1) + atomtools.general.idle_wait_frames(1) except Exception: print("WARNING: Couldn't wait for frame") @@ -269,6 +269,6 @@ class ScreenshotHelper: def capture_screenshot(file_path): - return ScreenshotHelper(azlmbr.atomtools.general.idle_wait_frames).capture_screenshot_blocking( + return ScreenshotHelper(atomtools.general.idle_wait_frames).capture_screenshot_blocking( os.path.join(file_path) ) From 041aa42307fcf42bfdb41871530acac7464efe82 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Wed, 11 Aug 2021 13:56:03 -0700 Subject: [PATCH 126/205] fixes after merge Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Include/IFileUtil.h | 1 + Code/Legacy/CryCommon/CrySizer.h | 1 + Code/Legacy/CryCommon/WinBase.cpp | 3 ++- Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp | 4 ++-- Gems/Maestro/Code/Source/Cinematics/Movie.cpp | 8 ++++---- 5 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Code/Editor/Include/IFileUtil.h b/Code/Editor/Include/IFileUtil.h index 746a81b87c..700e04f6d3 100644 --- a/Code/Editor/Include/IFileUtil.h +++ b/Code/Editor/Include/IFileUtil.h @@ -9,6 +9,7 @@ #pragma once #include "../Include/SandboxAPI.h" +#include class QWidget; diff --git a/Code/Legacy/CryCommon/CrySizer.h b/Code/Legacy/CryCommon/CrySizer.h index b541b698f9..3f9eed84f6 100644 --- a/Code/Legacy/CryCommon/CrySizer.h +++ b/Code/Legacy/CryCommon/CrySizer.h @@ -30,6 +30,7 @@ #include #include #include +#include // forward declarations for overloads struct AABB; diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 4e48d29ed7..a2b4056a56 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -12,6 +12,7 @@ #include "platform.h" // Note: This should be first to get consistent debugging definitions +#include #include #if defined(AZ_RESTRICTED_PLATFORM) @@ -29,7 +30,7 @@ #include AZ_RESTRICTED_FILE(WinBase_cpp) #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #else #include #endif diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp index 5d6cbe90eb..35fde93e83 100644 --- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp +++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp @@ -27,11 +27,11 @@ // Serialization for anim nodes & param types #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(eUiAnimNodeType_ ## name) == g_animNodeEnumToStringMap.end()); \ g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = AZ_STRINGIZE(name); \ - g_animNodeStringToEnumMap[string(STRINGIFY(name))] = eUiAnimNodeType_ ## name; + g_animNodeStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = eUiAnimNodeType_ ## name; #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(eUiAnimParamType_ ## name) == g_animParamEnumToStringMap.end()); \ g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = AZ_STRINGIZE(name); \ - g_animParamStringToEnumMap[string(STRINGIFY(name))] = eUiAnimParamType_ ## name; + g_animParamStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = eUiAnimParamType_ ## name; namespace { diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp index 8bbaf6e0c8..cf51ef3729 100644 --- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp @@ -74,12 +74,12 @@ static SMovieSequenceAutoComplete s_movieSequenceAutoComplete; ////////////////////////////////////////////////////////////////////////// // Serialization for anim nodes & param types #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(AnimNodeType::name) == g_animNodeEnumToStringMap.end()); \ - g_animNodeEnumToStringMap[AnimNodeType::name] = AZ_STRINGIZE(name); \ - g_animNodeStringToEnumMap[string(STRINGIFY(name))] = AnimNodeType::name; + g_animNodeEnumToStringMap[AnimNodeType::name] = AZ_STRINGIZE(name); \ + g_animNodeStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = AnimNodeType::name; #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(AnimParamType::name) == g_animParamEnumToStringMap.end()); \ - g_animParamEnumToStringMap[AnimParamType::name] = AZ_STRINGIZE(name); \ - g_animParamStringToEnumMap[string(STRINGIFY(name))] = AnimParamType::name; + g_animParamEnumToStringMap[AnimParamType::name] = AZ_STRINGIZE(name); \ + g_animParamStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = AnimParamType::name; namespace { From c6714595b1edb22748a68f25c9d9e59a479390fa Mon Sep 17 00:00:00 2001 From: Junbo Liang <68558268+junbo75@users.noreply.github.com> Date: Wed, 11 Aug 2021 13:59:29 -0700 Subject: [PATCH 127/205] Define a new Jenkins build script to deploy AWS resources (#2983) * Define a new Jenkins job to deploy AWS resources Signed-off-by: junbo * Address PR comments Signed-off-by: junbo * Add error checking for all the calls Signed-off-by: junbo * Remove the weekly-build-metrics tag Signed-off-by: junbo * Parameterize ARN/Region and move it to a Jenkins envvar. Signed-off-by: junbo * Revert the changes for build_config.json Signed-off-by: junbo --- .../Windows/deploy_cdk_applications.cmd | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 scripts/build/Platform/Windows/deploy_cdk_applications.cmd diff --git a/scripts/build/Platform/Windows/deploy_cdk_applications.cmd b/scripts/build/Platform/Windows/deploy_cdk_applications.cmd new file mode 100644 index 0000000000..2845707923 --- /dev/null +++ b/scripts/build/Platform/Windows/deploy_cdk_applications.cmd @@ -0,0 +1,105 @@ +@ECHO OFF +REM +REM Copyright (c) Contributors to the Open 3D Engine Project. +REM For complete copyright and license terms please see the LICENSE at the root of this distribution. +REM +REM SPDX-License-Identifier: Apache-2.0 OR MIT +REM +REM + +REM Deploy the CDK applcations for AWS gems (Windows only) +REM Prerequisites: +REM 1) Node.js is installed +REM 2) Node.js version >= 10.13.0, except for versions 13.0.0 - 13.6.0. A version in active long-term support is recommended. +SETLOCAL EnableDelayedExpansion + +SET SOURCE_DIRECTORY=%CD% +SET PATH=%SOURCE_DIRECTORY%\python;%PATH% +SET GEM_DIRECTORY=%SOURCE_DIRECTORY%\Gems + +REM Create and activate a virtualenv for the CDK deployment +CALL python -m venv .env +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to create a virtualenv for the CDK deployment + exit /b 1 +) +CALL .env\Scripts\activate.bat +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to activate the virtualenv for the CDK deployment + exit /b 1 +) + +ECHO [cdk_installation] Install the latest version of CDK +CALL npm uninstall -g aws-cdk +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to uninstall the current version of CDK + exit /b 1 +) +CALL npm install -g aws-cdk@latest +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to install the latest version of CDK + exit /b 1 +) + +REM Set temporary AWS credentials from the assume role +FOR /f "tokens=1,2,3" %%a IN ('CALL aws sts assume-role --query Credentials.[SecretAccessKey^,SessionToken^,AccessKeyId] --output text --role-arn %ASSUME_ROLE_ARN% --role-session-name o3de-Automation-session') DO ( + SET AWS_SECRET_ACCESS_KEY=%%a + SET AWS_SESSION_TOKEN=%%b + SET AWS_ACCESS_KEY_ID=%%c +) +FOR /F "tokens=4 delims=:" %%a IN ("%ASSUME_ROLE_ARN%") DO SET O3DE_AWS_DEPLOY_ACCOUNT=%%a + +REM Bootstrap and deploy the CDK applications +ECHO [cdk_bootstrap] Bootstrap CDK +CALL cdk bootstrap aws://%O3DE_AWS_DEPLOY_ACCOUNT%/%O3DE_AWS_DEPLOY_REGION% +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to bootstrap CDK + exit /b 1 +) + +CALL :DeployCDKApplication AWSCore --all +IF ERRORLEVEL 1 ( + exit /b 1 +) +CALL :DeployCDKApplication AWSClientAuth +IF ERRORLEVEL 1 ( + exit /b 1 +) +CALL :DeployCDKApplication AWSMetrics "-c batch_processing=true" +IF ERRORLEVEL 1 ( + exit /b 1 +) + +EXIT /b 0 + +:DeployCDKApplication +REM Deploy the CDK application for a specific AWS gem +SET GEM_NAME=%~1 +SET ADDITIONAL_ARGUMENTS=%~2 +ECHO [cdk_deployment] Deploy the CDK application for the %GEM_NAME% gem +PUSHD %GEM_DIRECTORY%\%GEM_NAME%\cdk + +REM Revert the CDK application code to a stable state using the provided commit ID +CALL git checkout %COMMIT_ID% -- . +IF ERRORLEVEL 1 ( + ECHO [git_checkout] Failed to checkout the CDK application for the %GEM_NAME% gem using commit ID %COMMIT_ID% + POPD + exit /b 1 +) + +REM Install required packages for the CDK application +CALL python -m pip install -r requirements.txt +IF ERRORLEVEL 1 ( + ECHO [cdk_deployment] Failed to install required packages for the %GEM_NAME% gem + POPD + exit /b 1 +) + +REM Deploy the CDK application +CALL cdk deploy %ADDITIONAL_ARGUMENTS% --require-approval never +IF ERRORLEVEL 1 ( + ECHO [cdk_deployment] Failed to deploy the CDK application for the %GEM_NAME% gem + POPD + exit /b 1 +) +POPD From 8b8e249e05852e4d2d6da1435df7275f92f894f6 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Wed, 11 Aug 2021 13:59:41 -0700 Subject: [PATCH 128/205] Add new functions to mock unit test class. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h index 7c132b29a3..a63e782146 100644 --- a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h +++ b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h @@ -25,6 +25,10 @@ namespace AZ MOCK_CONST_METHOD2(Visit, bool(const VisitorCallback&, AZStd::string_view)); MOCK_METHOD1(RegisterNotifier, NotifyEventHandler(const NotifyCallback&)); MOCK_METHOD1(RegisterNotifier, NotifyEventHandler(NotifyCallback&&)); + MOCK_METHOD1(RegisterPreMergeEvent, PreMergeEventHandler(const PreMergeEventCallback&)); + MOCK_METHOD1(RegisterPreMergeEvent, PreMergeEventHandler(PreMergeEventCallback&&)); + MOCK_METHOD1(PostMergeEventHandler, PreMergeEventHandler(const PostMergeEventCallback&)); + MOCK_METHOD1(PostMergeEventHandler, PreMergeEventHandler(PostMergeEventCallback&&)); MOCK_CONST_METHOD2(Get, bool(bool&, AZStd::string_view)); MOCK_CONST_METHOD2(Get, bool(s64&, AZStd::string_view)); From 7e5cbdab1e26fa829fdc70c0978914a22ac128ca Mon Sep 17 00:00:00 2001 From: chiyenteng <82238204+chiyenteng@users.noreply.github.com> Date: Wed, 11 Aug 2021 14:11:26 -0700 Subject: [PATCH 129/205] Create a new automated test for Prefab basic workflows (#2715) Adds a new ebus for prefab apis and refactored the apis Removed an empty test level Auto delete tmp level when teardown tests Add Base test level in Prefab folder Removed unused comments Checked if absolute path as an input of Create Prefab functions Changed created prefab file path to support all platfroms Added missing includes Signed-off-by: chiyteng --- .../prefab/PrefabLevel_BasicWorkflow.py | 66 ++++++++++++++++ .../Gem/PythonTests/prefab/TestSuite_Main.py | 6 ++ .../Levels/Prefab/Base/Base.prefab | 53 +++++++++++++ .../API/ToolsApplicationAPI.h | 4 +- .../Application/ToolsApplication.cpp | 1 - .../Prefab/PrefabPublicHandler.cpp | 48 +++++++---- .../Prefab/PrefabPublicHandler.h | 7 +- .../Prefab/PrefabPublicInterface.h | 21 ++++- .../Prefab/PrefabPublicRequestBus.h | 56 +++++++++++++ .../Prefab/PrefabPublicRequestHandler.cpp | 79 +++++++++++++++++++ .../Prefab/PrefabPublicRequestHandler.h | 41 ++++++++++ .../Prefab/PrefabSystemComponent.cpp | 4 +- .../Prefab/PrefabSystemComponent.h | 4 + .../UI/Prefab/PrefabIntegrationManager.cpp | 8 +- .../aztoolsframework_files.cmake | 3 + 15 files changed, 372 insertions(+), 29 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py create mode 100644 AutomatedTesting/Levels/Prefab/Base/Base.prefab create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py new file mode 100644 index 0000000000..44b7dc2ee4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py @@ -0,0 +1,66 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt:off +class Tests(): + create_new_entity = ("Entity: 'CreateNewEntity' passed", "Entity: 'CreateNewEntity' failed") + create_prefab = ("Prefab: 'CreatePrefab' passed", "Prefab: 'CreatePrefab' failed") + instantiate_prefab = ("Prefab: 'InstantiatePrefab' passed", "Prefab: 'InstantiatePrefab' failed") + new_prefab_position = ("Prefab: new prefab's position is at the expected position", "Prefab: new prefab's position is *not* at the expected position") +# fmt:on + +def PrefabLevel_BasicWorkflow(): + """ + This test will help verify if the following functions related to Prefab work as expected: + - CreatePrefab + - InstantiatePrefab + """ + + import os + import sys + + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + import editor_python_test_tools.hydra_editor_utils as hydra + + import azlmbr.bus as bus + import azlmbr.entity as entity + from azlmbr.entity import EntityId + import azlmbr.editor as editor + import azlmbr.prefab as prefab + from azlmbr.math import Vector3 + import azlmbr.legacy.general as general + + EXPECTED_NEW_PREFAB_POSITION = Vector3(10.00, 20.0, 30.0) + + helper.init_idle() + helper.open_level("Prefab", "Base") + +# Create a new Entity at the root level + new_entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', EntityId()) + Report.result(Tests.create_new_entity, new_entity_id.IsValid()) + +# Checks for prefab creation passed or not + new_prefab_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'new_prefab.prefab') + create_prefab_result = prefab.PrefabPublicRequestBus(bus.Broadcast, 'CreatePrefabInMemory', [new_entity_id], new_prefab_file_path) + Report.result(Tests.create_prefab, create_prefab_result) + +# Checks for prefab instantiation passed or not + container_entity_id = prefab.PrefabPublicRequestBus(bus.Broadcast, 'InstantiatePrefab', new_prefab_file_path, EntityId(), EXPECTED_NEW_PREFAB_POSITION) + Report.result(Tests.instantiate_prefab, container_entity_id.IsValid()) + +# Checks if the new prefab is at the correct position and if it fails, it will provide the expected postion and the actual postion of the entity in the Editor log + new_prefab_position = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", container_entity_id) + is_at_position = new_prefab_position.IsClose(EXPECTED_NEW_PREFAB_POSITION) + Report.result(Tests.new_prefab_position, is_at_position) + if not is_at_position: + Report.info(f'Expected position: {EXPECTED_NEW_PREFAB_POSITION.ToString()}, actual position: {new_prefab_position.ToString()}') + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(PrefabLevel_BasicWorkflow) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py index acd8f60b07..4e3d6ba77f 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py @@ -16,6 +16,7 @@ from ly_test_tools import LAUNCHERS sys.path.append (os.path.dirname (os.path.abspath (__file__)) + '/../automatedtesting_shared') +import ly_test_tools.environment.file_system as file_system from base import TestAutomationBase @pytest.mark.SUITE_main @@ -29,3 +30,8 @@ class TestAutomation(TestAutomationBase): def test_PrefabLevel_OpensLevelWithEntities(self, request, workspace, editor, launcher_platform): from . import PrefabLevel_OpensLevelWithEntities as test_module self._run_prefab_test(request, workspace, editor, test_module) + + def test_PrefabLevel_BasicWorkflow(self, request, workspace, editor, launcher_platform): + from . import PrefabLevel_BasicWorkflow as test_module + self._run_prefab_test(request, workspace, editor, test_module) + diff --git a/AutomatedTesting/Levels/Prefab/Base/Base.prefab b/AutomatedTesting/Levels/Prefab/Base/Base.prefab new file mode 100644 index 0000000000..f7e42e7731 --- /dev/null +++ b/AutomatedTesting/Levels/Prefab/Base/Base.prefab @@ -0,0 +1,53 @@ +{ + "ContainerEntity": { + "Id": "Entity_[1146574390643]", + "Name": "Level", + "Components": { + "Component_[10641544592923449938]": { + "$type": "EditorInspectorComponent", + "Id": 10641544592923449938 + }, + "Component_[12039882709170782873]": { + "$type": "EditorOnlyEntityComponent", + "Id": 12039882709170782873 + }, + "Component_[12265484671603697631]": { + "$type": "EditorPendingCompositionComponent", + "Id": 12265484671603697631 + }, + "Component_[14126657869720434043]": { + "$type": "EditorEntitySortComponent", + "Id": 14126657869720434043 + }, + "Component_[15230859088967841193]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 15230859088967841193, + "Parent Entity": "" + }, + "Component_[16239496886950819870]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 16239496886950819870 + }, + "Component_[5688118765544765547]": { + "$type": "EditorEntityIconComponent", + "Id": 5688118765544765547 + }, + "Component_[6545738857812235305]": { + "$type": "SelectionComponent", + "Id": 6545738857812235305 + }, + "Component_[7247035804068349658]": { + "$type": "EditorPrefabComponent", + "Id": 7247035804068349658 + }, + "Component_[9307224322037797205]": { + "$type": "EditorLockComponent", + "Id": 9307224322037797205 + }, + "Component_[9562516168917670048]": { + "$type": "EditorVisibilityComponent", + "Id": 9562516168917670048 + } + } + } +} \ No newline at end of file diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h index 0ba10d7388..f6046b9f25 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h @@ -600,8 +600,8 @@ namespace AzToolsFramework * Open 3D Engine Internal use only. * * Run a specific redo command separate from the undo/redo system. - * In many cases before a modifcation on an entity takes place, it is first packaged into - * undo/redo commands. Running the modification's redo command separete from the undo/redo + * In many cases before a modification on an entity takes place, it is first packaged into + * undo/redo commands. Running the modification's redo command separate from the undo/redo * system simulates its execution, and avoids some code duplication. */ virtual void RunRedoSeparately(UndoSystem::URSequencePoint* redoCommand) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp index 970f5aa28c..56ef749247 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp @@ -1781,5 +1781,4 @@ namespace AzToolsFramework { appType.m_maskValue = AZ::ApplicationTypeQuery::Masks::Tool; }; - } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index bb394720c9..7af953efca 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -61,7 +61,7 @@ namespace AzToolsFramework m_prefabUndoCache.Destroy(); } - PrefabOperationResult PrefabPublicHandler::CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) + PrefabOperationResult PrefabPublicHandler::CreatePrefabInMemory(const AZStd::vector& entityIds, AZ::IO::PathView filePath) { EntityList inputEntityList, topLevelEntities; AZ::EntityId commonRootEntityId; @@ -73,8 +73,6 @@ namespace AzToolsFramework return findCommonRootOutcome; } - AZ_Assert(absolutePath.IsAbsolute(), "CreatePrefab requires an absolute path for saving the initial prefab file."); - InstanceOptionalReference instanceToCreate; { // Initialize Undo Batch object @@ -125,7 +123,7 @@ namespace AzToolsFramework PrefabDom linkPatchesCopy; linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); nestedInstanceLinkPatchesMap.emplace(nestedInstance, AZStd::move(linkPatchesCopy)); - + RemoveLink(outInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); instancePtrs.emplace_back(AZStd::move(outInstance)); @@ -139,18 +137,20 @@ namespace AzToolsFramework if (!prefabEditorEntityOwnershipInterface) { return AZ::Failure(AZStd::string("Could not create a new prefab out of the entities provided - internal error " - "(PrefabEditorEntityOwnershipInterface unavailable).")); + "(PrefabEditorEntityOwnershipInterface unavailable).")); } // Create the Prefab + AZ_Assert(filePath.IsAbsolute(), "CreatePrefabInMemory requires an absolute file path."); + instanceToCreate = prefabEditorEntityOwnershipInterface->CreatePrefab( - entities, AZStd::move(instancePtrs), m_prefabLoaderInterface->GenerateRelativePath(absolutePath), + entities, AZStd::move(instancePtrs), m_prefabLoaderInterface->GenerateRelativePath(filePath), commonRootEntityOwningInstance); if (!instanceToCreate) { return AZ::Failure(AZStd::string("Could not create a new prefab out of the entities provided - internal error " - "(A null instance is returned).")); + "(A null instance is returned).")); } AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); @@ -218,7 +218,7 @@ namespace AzToolsFramework linkUpdate.Redo(); } }); - + // Create a link between the templates of the newly created instance and the instance it's being parented under. CreateLink( instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), @@ -255,18 +255,35 @@ namespace AzToolsFramework // Select Container Entity { - auto selectionUndo = aznew SelectionCommand({containerEntityId}, "Select Prefab Container Entity"); + auto selectionUndo = aznew SelectionCommand({ containerEntityId }, "Select Prefab Container Entity"); selectionUndo->SetParent(undoBatch.GetUndoBatch()); ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequestBus::Events::RunRedoSeparately, selectionUndo); } } - // Save Template to file - m_prefabLoaderInterface->SaveTemplateToFile(instanceToCreate->get().GetTemplateId(), absolutePath); - return AZ::Success(); } + PrefabOperationResult PrefabPublicHandler::CreatePrefabInDisk(const AZStd::vector& entityIds, AZ::IO::PathView filePath) + { + auto result = CreatePrefabInMemory(entityIds, filePath); + if (result.IsSuccess()) + { + // Save Template to file + auto relativePath = m_prefabLoaderInterface->GenerateRelativePath(filePath); + Prefab::TemplateId templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(relativePath); + if (!m_prefabLoaderInterface->SaveTemplateToFile(templateId, filePath)) + { + AZStd::string_view filePathString(filePath); + return AZ::Failure(AZStd::string::format( + "Could not save the newly created prefab to file path %.*s - internal error ", + AZ_STRING_ARG(filePathString))); + } + } + + return result; + } + PrefabDom PrefabPublicHandler::ApplyContainerTransformAndGeneratePatch(AZ::EntityId containerEntityId, AZ::EntityId parentEntityId, const EntityList& childEntities) { AZ::Entity* containerEntity = GetEntityById(containerEntityId); @@ -301,7 +318,7 @@ namespace AzToolsFramework return AZStd::move(patch); } - PrefabOperationResult PrefabPublicHandler::InstantiatePrefab( + InstantiatePrefabResult PrefabPublicHandler::InstantiatePrefab( AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) { auto prefabEditorEntityOwnershipInterface = AZ::Interface::Get(); @@ -347,6 +364,7 @@ namespace AzToolsFramework relativePath.Native().c_str(), instanceToParentUnder->get().GetTemplateSourcePath().Native().c_str())); } + AZ::EntityId containerEntityId; { // Initialize Undo Batch object ScopedUndoBatch undoBatch("Instantiate Prefab"); @@ -367,7 +385,7 @@ namespace AzToolsFramework instanceToParentUnder->get(), "Update prefab instance", instanceToParentUnderDomBeforeCreate, undoBatch.GetUndoBatch()); // Create Link with correct container patches - AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); + containerEntityId = instanceToCreate->get().GetContainerEntityId(); AZ::Entity* containerEntity = GetEntityById(containerEntityId); AZ_Assert(containerEntity, "Invalid container entity detected in InstantiatePrefab."); @@ -394,7 +412,7 @@ namespace AzToolsFramework &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); } - return AZ::Success(); + return AZ::Success(containerEntityId); } PrefabOperationResult PrefabPublicHandler::FindCommonRootOwningInstance( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 0e24b0841d..8f124e8edd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -42,8 +42,11 @@ namespace AzToolsFramework void UnregisterPrefabPublicHandlerInterface(); // PrefabPublicInterface... - PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) override; - PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; + PrefabOperationResult CreatePrefabInDisk( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + PrefabOperationResult CreatePrefabInMemory( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + InstantiatePrefabResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; PrefabOperationResult SavePrefab(AZ::IO::Path filePath) override; PrefabEntityResult CreateEntity(AZ::EntityId parentId, const AZ::Vector3& position) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h index 6b3fdcd391..67d65dfca6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h @@ -25,6 +25,7 @@ namespace AzToolsFramework namespace Prefab { typedef AZ::Outcome PrefabOperationResult; + typedef AZ::Outcome InstantiatePrefabResult; typedef AZ::Outcome PrefabRequestResult; typedef AZ::Outcome PrefabEntityResult; @@ -39,22 +40,34 @@ namespace AzToolsFramework AZ_RTTI(PrefabPublicInterface, "{931AAE9D-C775-4818-9070-A2DA69489CBE}"); /** - * Create a prefab out of the entities provided, at the path provided. + * Create a prefab out of the entities provided, at the path provided, and save it in disk immediately. * Automatically detects descendants of entities, and discerns between entities and child instances. * @param entityIds The entities that should form the new prefab (along with their descendants). * @param filePath The absolute path for the new prefab file. * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) = 0; + virtual PrefabOperationResult CreatePrefabInDisk( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) = 0; + + /** + * Create a prefab out of the entities provided, at the path provided, and keep it in memory. + * Automatically detects descendants of entities, and discerns between entities and child instances. + * @param entityIds The entities that should form the new prefab (along with their descendants). + * @param filePath The absolute path for the new prefab file. + * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. + */ + virtual PrefabOperationResult CreatePrefabInMemory( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) = 0; /** * Instantiate a prefab from a prefab file. * @param filePath The path to the prefab file to instantiate. * @param parent The entity the prefab should be a child of in the transform hierarchy. * @param position The position in world space the prefab should be instantiated in. - * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. + * @return An outcome object with an entityId of the new prefab's container entity; + * on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; + virtual InstantiatePrefabResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; /** * Saves changes to prefab to disk. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h new file mode 100644 index 0000000000..1b86d3cd4e --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace AzToolsFramework +{ + namespace Prefab + { + /** + * The primary purpose of this bus is to facilitate writing automated tests for prefabs. + * It calls PrefabPublicInterface internally to talk to the prefab system. + * If you would like to integrate prefabs into your system, please call PrefabPublicInterface + * directly for better performance. + */ + class PrefabPublicRequests + : public AZ::EBusTraits + { + public: + using Bus = AZ::EBus; + + ////////////////////////////////////////////////////////////////////////// + // EBusTraits overrides + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + ////////////////////////////////////////////////////////////////////////// + + virtual ~PrefabPublicRequests() = default; + + /** + * Create a prefab out of the entities provided, at the path provided, and keep it in memory. + * Automatically detects descendants of entities, and discerns between entities and child instances. + */ + virtual bool CreatePrefabInMemory( + const AZStd::vector& entityIds, AZStd::string_view filePath) = 0; + + /** + * Instantiate a prefab from a prefab file. + */ + virtual AZ::EntityId InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; + }; + + using PrefabPublicRequestBus = AZ::EBus; + + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp new file mode 100644 index 0000000000..0e68a286a6 --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +#include + +namespace AzToolsFramework +{ + namespace Prefab + { + void PrefabPublicRequestHandler::Reflect(AZ::ReflectContext* context) + { + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->EBus("PrefabPublicRequestBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) + ->Attribute(AZ::Script::Attributes::Category, "Prefab") + ->Attribute(AZ::Script::Attributes::Module, "prefab") + ->Event("CreatePrefabInMemory", &PrefabPublicRequests::CreatePrefabInMemory) + ->Event("InstantiatePrefab", &PrefabPublicRequests::InstantiatePrefab) + ; + } + } + + void PrefabPublicRequestHandler::Connect() + { + m_prefabPublicInterface = AZ::Interface::Get(); + AZ_Assert(m_prefabPublicInterface, "PrefabPublicRequestHandler - Could not retrieve instance of PrefabPublicInterface"); + + PrefabPublicRequestBus::Handler::BusConnect(); + } + + void PrefabPublicRequestHandler::Disconnect() + { + PrefabPublicRequestBus::Handler::BusDisconnect(); + + m_prefabPublicInterface = nullptr; + } + + bool PrefabPublicRequestHandler::CreatePrefabInMemory(const AZStd::vector& entityIds, AZStd::string_view filePath) + { + auto createPrefabOutcome = m_prefabPublicInterface->CreatePrefabInMemory(entityIds, filePath); + if (!createPrefabOutcome.IsSuccess()) + { + AZ_Error("CreatePrefabInMemory", false, + "Failed to create Prefab on file path '%.*s'. Error message: %s.", + AZ_STRING_ARG(filePath), + createPrefabOutcome.GetError().c_str()); + + return false; + } + + return true; + } + + AZ::EntityId PrefabPublicRequestHandler::InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) + { + auto instantiatePrefabOutcome = m_prefabPublicInterface->InstantiatePrefab(filePath, parent, position); + if (!instantiatePrefabOutcome.IsSuccess()) + { + AZ_Error("InstantiatePrefab", false, + "Failed to instantiate Prefab on file path '%.*s'. Error message: %s.", + AZ_STRING_ARG(filePath), + instantiatePrefabOutcome.GetError().c_str()); + + return AZ::EntityId(); + } + + return instantiatePrefabOutcome.GetValue(); + } + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h new file mode 100644 index 0000000000..548bc8e04a --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +#include + +namespace AzToolsFramework +{ + namespace Prefab + { + class PrefabPublicInterface; + + class PrefabPublicRequestHandler final + : public PrefabPublicRequestBus::Handler + { + public: + AZ_CLASS_ALLOCATOR(PrefabPublicRequestHandler, AZ::SystemAllocator, 0); + AZ_RTTI(PrefabPublicRequestHandler, "{83FBDDF9-10BE-4373-B1DC-44B47EE4805C}"); + + static void Reflect(AZ::ReflectContext* context); + + void Connect(); + void Disconnect(); + + bool CreatePrefabInMemory(const AZStd::vector& entityIds, AZStd::string_view filePath) override; + AZ::EntityId InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; + + private: + PrefabPublicInterface* m_prefabPublicInterface = nullptr; + }; + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index bfdb6b79f2..1051e530c8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -35,12 +35,14 @@ namespace AzToolsFramework m_instanceUpdateExecutor.RegisterInstanceUpdateExecutorInterface(); m_instanceToTemplatePropagator.RegisterInstanceToTemplateInterface(); m_prefabPublicHandler.RegisterPrefabPublicHandlerInterface(); + m_prefabPublicRequestHandler.Connect(); AZ::SystemTickBus::Handler::BusConnect(); } void PrefabSystemComponent::Deactivate() { AZ::SystemTickBus::Handler::BusDisconnect(); + m_prefabPublicRequestHandler.Disconnect(); m_prefabPublicHandler.UnregisterPrefabPublicHandlerInterface(); m_instanceToTemplatePropagator.UnregisterInstanceToTemplateInterface(); m_instanceUpdateExecutor.UnregisterInstanceUpdateExecutorInterface(); @@ -54,6 +56,7 @@ namespace AzToolsFramework AzToolsFramework::Prefab::PrefabConversionUtils::PrefabConversionPipeline::Reflect(context); AzToolsFramework::Prefab::PrefabConversionUtils::PrefabCatchmentProcessor::Reflect(context); AzToolsFramework::Prefab::PrefabConversionUtils::EditorInfoRemover::Reflect(context); + PrefabPublicRequestHandler::Reflect(context); AZ::SerializeContext* serialize = azrtti_cast(context); if (serialize) @@ -62,7 +65,6 @@ namespace AzToolsFramework } AZ::JsonRegistrationContext* jsonRegistration = azrtti_cast(context); - if (jsonRegistration) { jsonRegistration->Serializer()->HandlesType(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index 04457b5a97..b07ccbada6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -369,6 +370,9 @@ namespace AzToolsFramework // Used for updating Templates when Instances are modified InstanceToTemplatePropagator m_instanceToTemplatePropagator; + + // Handler of the public Prefab requests + PrefabPublicRequestHandler m_prefabPublicRequestHandler; }; } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 5bf9b15abe..eb9cf2b65f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -256,11 +256,11 @@ namespace AzToolsFramework void PrefabIntegrationManager::HandleSourceFileType(AZStd::string_view sourceFilePath, AZ::EntityId parentId, AZ::Vector3 position) const { - auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(sourceFilePath, parentId, position); + auto instantiatePrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(sourceFilePath, parentId, position); - if (!createPrefabOutcome.IsSuccess()) + if (!instantiatePrefabOutcome.IsSuccess()) { - WarnUserOfError("Prefab Instantiation Error", createPrefabOutcome.GetError()); + WarnUserOfError("Prefab Instantiation Error", instantiatePrefabOutcome.GetError()); } } @@ -348,7 +348,7 @@ namespace AzToolsFramework } } - auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefab(selectedEntities, prefabFilePath.data()); + auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefabInDisk(selectedEntities, prefabFilePath.data()); if (!createPrefabOutcome.IsSuccess()) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 53173f83af..14c5f34f90 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -657,6 +657,9 @@ set(FILES Prefab/PrefabPublicHandler.cpp Prefab/PrefabPublicInterface.h Prefab/PrefabPublicNotificationBus.h + Prefab/PrefabPublicRequestBus.h + Prefab/PrefabPublicRequestHandler.h + Prefab/PrefabPublicRequestHandler.cpp Prefab/PrefabUndo.h Prefab/PrefabUndo.cpp Prefab/PrefabUndoCache.cpp From e0410385d568f7377439ed23c3a6c102d1d08fdd Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Wed, 11 Aug 2021 16:38:13 -0500 Subject: [PATCH 130/205] AtomTools: fixing status bar messages fixed problems with status bar messages not appearing added status bar messages to shader management console got rid of central widget variable and moved layout to atom tools window base class Signed-off-by: Guthrie Adams --- .../Window/AtomToolsMainWindow.h | 5 +- .../Source/Window/AtomToolsMainWindow.cpp | 18 +++-- .../Source/Window/MaterialEditorWindow.cpp | 55 ++++++------- .../Window/ShaderManagementConsoleWindow.cpp | 80 ++++++++++++++----- .../Window/ShaderManagementConsoleWindow.h | 3 + 5 files changed, 100 insertions(+), 61 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h index 82444246fd..751b30a907 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -16,8 +16,8 @@ #include #include +#include #include -#include #include namespace AtomToolsFramework @@ -53,10 +53,9 @@ namespace AtomToolsFramework virtual void SelectNextTab(); AzQtComponents::FancyDocking* m_advancedDockManager = nullptr; - QWidget* m_centralWidget = nullptr; QMenuBar* m_menuBar = nullptr; AzQtComponents::TabWidget* m_tabWidget = nullptr; - QStatusBar* m_statusBar = nullptr; + QLabel* m_statusMessage = nullptr; AZStd::unordered_map m_dockWidgets; }; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp index f6e56b1ff6..55bec32dc7 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp @@ -7,6 +7,8 @@ */ #include +#include +#include namespace AtomToolsFramework { @@ -21,11 +23,15 @@ namespace AtomToolsFramework setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); - m_statusBar = new QStatusBar(this); - m_statusBar->setObjectName("StatusBar"); - statusBar()->addPermanentWidget(m_statusBar, 1); + m_statusMessage = new QLabel(statusBar()); + statusBar()->addPermanentWidget(m_statusMessage, 1); - m_centralWidget = new QWidget(this); + auto centralWidget = new QWidget(this); + auto centralWidgetLayout = new QVBoxLayout(centralWidget); + centralWidgetLayout->setMargin(0); + centralWidgetLayout->setContentsMargins(0, 0, 0, 0); + centralWidget->setLayout(centralWidgetLayout); + setCentralWidget(centralWidget); AtomToolsMainWindowRequestBus::Handler::BusConnect(); } @@ -111,7 +117,7 @@ namespace AtomToolsFramework void AtomToolsMainWindow::CreateTabBar() { - m_tabWidget = new AzQtComponents::TabWidget(m_centralWidget); + m_tabWidget = new AzQtComponents::TabWidget(centralWidget()); m_tabWidget->setObjectName("TabWidget"); m_tabWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); m_tabWidget->setContentsMargins(0, 0, 0, 0); @@ -131,6 +137,8 @@ namespace AtomToolsFramework { OpenTabContextMenu(); }); + + centralWidget()->layout()->addWidget(m_tabWidget); } void AtomToolsMainWindow::AddTabForDocumentId( diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index f4dfa3df1b..fca3cc59eb 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -36,8 +36,6 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnin #include #include #include -#include -#include #include AZ_POP_DISABLE_WARNING @@ -77,20 +75,13 @@ namespace MaterialEditor m_toolBar->setObjectName("ToolBar"); addToolBar(m_toolBar); - m_materialViewport = new MaterialViewportWidget(m_centralWidget); - m_materialViewport->setObjectName("Viewport"); - m_materialViewport->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - CreateMenu(); CreateTabBar(); - QVBoxLayout* vl = new QVBoxLayout(m_centralWidget); - vl->setMargin(0); - vl->setContentsMargins(0, 0, 0, 0); - vl->addWidget(m_tabWidget); - vl->addWidget(m_materialViewport); - m_centralWidget->setLayout(vl); - setCentralWidget(m_centralWidget); + m_materialViewport = new MaterialViewportWidget(centralWidget()); + m_materialViewport->setObjectName("Viewport"); + m_materialViewport->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + centralWidget()->layout()->addWidget(m_materialViewport); AddDockWidget("Asset Browser", new MaterialBrowserWidget, Qt::BottomDockWidgetArea, Qt::Vertical); AddDockWidget("Inspector", new MaterialInspector, Qt::RightDockWidgetArea, Qt::Horizontal); @@ -200,7 +191,7 @@ namespace MaterialEditor // Create a new tab for the document ID and assign it's label to the file name of the document. AddTabForDocumentId(documentId, filename, absolutePath, [this]{ // The tab widget requires a dummy page per tab - auto contentWidget = new QWidget(m_centralWidget); + auto contentWidget = new QWidget(centralWidget()); contentWidget->setContentsMargins(0, 0, 0, 0); contentWidget->setFixedSize(0, 0); return contentWidget; @@ -247,8 +238,8 @@ namespace MaterialEditor const QString documentPath = GetDocumentPath(documentId); if (!documentPath.isEmpty()) { - const QString status = QString("Material closed: %1").arg(documentPath); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Document closed: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } } @@ -257,8 +248,8 @@ namespace MaterialEditor RemoveTabForDocumentId(documentId); const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Material closed: %1").arg(documentPath); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Document closed: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } void MaterialEditorWindow::OnDocumentModified(const AZ::Uuid& documentId) @@ -296,8 +287,8 @@ namespace MaterialEditor UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Material closed: %1").arg(documentPath); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Document closed: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } void MaterialEditorWindow::CreateMenu() @@ -341,8 +332,8 @@ namespace MaterialEditor if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to save material: %1").arg(documentPath); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Failed to save document: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Save); @@ -355,8 +346,8 @@ namespace MaterialEditor documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - const QString status = QString("Failed to save material: %1").arg(documentPath); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Failed to save document: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::SaveAs); @@ -369,8 +360,8 @@ namespace MaterialEditor documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - const QString status = QString("Failed to save material: %1").arg(documentPath); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Failed to save document: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } }); @@ -379,8 +370,8 @@ namespace MaterialEditor MaterialDocumentSystemRequestBus::BroadcastResult(result, &MaterialDocumentSystemRequestBus::Events::SaveAllDocuments); if (!result) { - const QString status = QString("Failed to save materials."); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Failed to save documents."); + m_statusMessage->setText(QString("%1").arg(status)); } }); @@ -425,8 +416,8 @@ namespace MaterialEditor if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform Undo in material: %1").arg(documentPath); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Failed to perform Undo on document: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Undo); @@ -437,8 +428,8 @@ namespace MaterialEditor if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform Undo in material: %1").arg(documentPath); - m_statusBar->setWindowIconText(QString("%1").arg(status)); + const QString status = QString("Failed to perform Redo on document: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Redo); diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 0a082f3c33..ec9ad08e21 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -8,6 +8,8 @@ #include #include +#include +#include #include #include #include @@ -23,11 +25,8 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnin #include #include #include -#include #include #include -#include -#include #include AZ_POP_DISABLE_WARNING @@ -36,6 +35,14 @@ namespace ShaderManagementConsole ShaderManagementConsoleWindow::ShaderManagementConsoleWindow(QWidget* parent /* = 0 */) : AtomToolsFramework::AtomToolsMainWindow(parent) { + resize(1280, 1024); + + // Among other things, we need the window wrapper to save the main window size, position, and state + auto mainWindowWrapper = + new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionAutoTitleBarButtons); + mainWindowWrapper->setGuest(this); + mainWindowWrapper->enableSaveRestoreGeometry("O3DE", "ShaderManagementConsole", "mainWindowGeometry"); + setWindowTitle("Shader Management Console"); setObjectName("ShaderManagementConsoleWindow"); @@ -47,16 +54,14 @@ namespace ShaderManagementConsole CreateMenu(); CreateTabBar(); - QVBoxLayout* vl = new QVBoxLayout(m_centralWidget); - vl->setMargin(0); - vl->setContentsMargins(0, 0, 0, 0); - vl->addWidget(m_tabWidget); - m_centralWidget->setLayout(vl); - setCentralWidget(m_centralWidget); - AddDockWidget("Asset Browser", new ShaderManagementConsoleBrowserWidget, Qt::BottomDockWidgetArea, Qt::Vertical); AddDockWidget("Python Terminal", new AzToolsFramework::CScriptTermDialog, Qt::BottomDockWidgetArea, Qt::Horizontal); + SetDockWidgetVisible("Python Terminal", false); + + // Restore geometry and show the window + mainWindowWrapper->showFromSettings(); + ShaderManagementConsoleDocumentNotificationBus::Handler::BusConnect(); OnDocumentOpened(AZ::Uuid::CreateNull()); } @@ -103,8 +108,7 @@ namespace ShaderManagementConsole // Create a new tab for the document ID and assign it's label to the file name of the document. AddTabForDocumentId(documentId, filename, absolutePath, [this, documentId]{ // The document tab contains a table view. - auto contentWidget = new QTableView(m_centralWidget); - contentWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + auto contentWidget = new QTableView(centralWidget()); contentWidget->setSelectionBehavior(QAbstractItemView::SelectRows); contentWidget->setModel(CreateDocumentContent(documentId)); return contentWidget; @@ -142,11 +146,22 @@ namespace ShaderManagementConsole activateWindow(); raise(); + + const QString documentPath = GetDocumentPath(documentId); + if (!documentPath.isEmpty()) + { + const QString status = QString("Document closed: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); + } } void ShaderManagementConsoleWindow::OnDocumentClosed(const AZ::Uuid& documentId) { RemoveTabForDocumentId(documentId); + + const QString documentPath = GetDocumentPath(documentId); + const QString status = QString("Document closed: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } void ShaderManagementConsoleWindow::OnDocumentModified(const AZ::Uuid& documentId) @@ -182,6 +197,10 @@ namespace ShaderManagementConsole AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); + + const QString documentPath = GetDocumentPath(documentId); + const QString status = QString("Document closed: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); } void ShaderManagementConsoleWindow::CreateMenu() @@ -254,12 +273,26 @@ namespace ShaderManagementConsole m_actionUndo = m_menuEdit->addAction("&Undo", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); - ShaderManagementConsoleDocumentRequestBus::Event(documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Undo); + bool result = false; + ShaderManagementConsoleDocumentRequestBus::EventResult(result, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Undo); + if (!result) + { + const QString documentPath = GetDocumentPath(documentId); + const QString status = QString("Failed to perform Undo on document: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); + } }, QKeySequence::Undo); m_actionRedo = m_menuEdit->addAction("&Redo", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); - ShaderManagementConsoleDocumentRequestBus::Event(documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Redo); + bool result = false; + ShaderManagementConsoleDocumentRequestBus::EventResult(result, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::Redo); + if (!result) + { + const QString documentPath = GetDocumentPath(documentId); + const QString status = QString("Failed to perform Redo on document: %1").arg(documentPath); + m_statusMessage->setText(QString("%1").arg(status)); + } }, QKeySequence::Redo); m_menuEdit->addSeparator(); @@ -278,13 +311,11 @@ namespace ShaderManagementConsole SetDockWidgetVisible(label, !IsDockWidgetVisible(label)); }); - m_actionPythonTerminal = m_menuView->addAction( - "Python &Terminal", - [this]() - { - const AZStd::string label = "Python Terminal"; - SetDockWidgetVisible(label, !IsDockWidgetVisible(label)); - }); + m_actionPythonTerminal = m_menuView->addAction("Python &Terminal", [this]() { + const AZStd::string label = "Python Terminal"; + SetDockWidgetVisible(label, !IsDockWidgetVisible(label)); + }); + m_menuView->addSeparator(); @@ -321,6 +352,13 @@ namespace ShaderManagementConsole }); } + QString ShaderManagementConsoleWindow::GetDocumentPath(const AZ::Uuid& documentId) const + { + AZStd::string absolutePath; + ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Handler::GetAbsolutePath); + return absolutePath.c_str(); + } + void ShaderManagementConsoleWindow::OpenTabContextMenu() { const QTabBar* tabBar = m_tabWidget->tabBar(); diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h index aae31d1000..37efcb1b45 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -52,6 +52,9 @@ namespace ShaderManagementConsole void CreateMenu() override; void CreateTabBar() override; + + QString GetDocumentPath(const AZ::Uuid& documentId) const; + void OpenTabContextMenu() override; void SelectDocumentForTab(const int tabIndex); From aaa847a56931f1ba9a5ebffe6a1ea1911d9aae1e Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Wed, 11 Aug 2021 14:40:34 -0700 Subject: [PATCH 131/205] Remove empty User Functions and Script Event sections Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- .../View/Widgets/ScriptCanvasNodePaletteDockWidget.cpp | 5 ++--- .../Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp | 3 ++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Editor/View/Widgets/ScriptCanvasNodePaletteDockWidget.cpp b/Gems/ScriptCanvas/Code/Editor/View/Widgets/ScriptCanvasNodePaletteDockWidget.cpp index 8341cc1e24..96b0ac353f 100644 --- a/Gems/ScriptCanvas/Code/Editor/View/Widgets/ScriptCanvasNodePaletteDockWidget.cpp +++ b/Gems/ScriptCanvas/Code/Editor/View/Widgets/ScriptCanvasNodePaletteDockWidget.cpp @@ -80,12 +80,11 @@ namespace ScriptCanvasEditor GraphCanvas::NodePaletteTreeItem* variablesRoot = root->CreateChildNode("Variables"); root->RegisterCategoryNode(variablesRoot, "Variables"); - // We always want to keep these around as place holders GraphCanvas::NodePaletteTreeItem* customEventRoot = root->GetCategoryNode("Script Events"); - customEventRoot->SetAllowPruneOnEmpty(false); + customEventRoot->SetAllowPruneOnEmpty(true); GraphCanvas::NodePaletteTreeItem* globalFunctionRoot = root->GetCategoryNode("User Functions"); - globalFunctionRoot->SetAllowPruneOnEmpty(false); + globalFunctionRoot->SetAllowPruneOnEmpty(true); } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp index 81d6445556..9d1626fb73 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp @@ -509,7 +509,8 @@ namespace ScriptCanvas bool SubgraphInterface::HasAnyFunctionality() const { - return IsActiveDefaultObject() || HasPublicFunctionality(); + // \todo restore default object addition when ndoes can define an variable, as well + return /*IsActiveDefaultObject() || */ HasPublicFunctionality(); } bool SubgraphInterface::HasBranches() const From fb1ee0f037b0bda8f9cf87e7c4690956804d5c67 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Wed, 11 Aug 2021 16:45:51 -0500 Subject: [PATCH 132/205] updated undo/redo messages Signed-off-by: Guthrie Adams --- .../Code/Source/Window/MaterialEditorWindow.cpp | 4 ++-- .../Code/Source/Window/ShaderManagementConsoleWindow.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index fca3cc59eb..ffe5ec408a 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -416,7 +416,7 @@ namespace MaterialEditor if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform Undo on document: %1").arg(documentPath); + const QString status = QString("Failed to perform undo on document: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Undo); @@ -428,7 +428,7 @@ namespace MaterialEditor if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform Redo on document: %1").arg(documentPath); + const QString status = QString("Failed to perform redo on document: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Redo); diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index ec9ad08e21..a7c8d79130 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -278,7 +278,7 @@ namespace ShaderManagementConsole if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform Undo on document: %1").arg(documentPath); + const QString status = QString("Failed to perform undo on document: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Undo); @@ -290,7 +290,7 @@ namespace ShaderManagementConsole if (!result) { const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Failed to perform Redo on document: %1").arg(documentPath); + const QString status = QString("Failed to perform redo on document: %1").arg(documentPath); m_statusMessage->setText(QString("%1").arg(status)); } }, QKeySequence::Redo); From 584c125fbc2a69d79934c5ef478f53f9526e5213 Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Wed, 11 Aug 2021 15:11:20 -0700 Subject: [PATCH 133/205] rename serializer Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- ...ScriptUserDataSerializer.cpp => RuntimeVariableSerializer.cpp} | 0 .../{ScriptUserDataSerializer.h => RuntimeVariableSerializer.h} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/{ScriptUserDataSerializer.cpp => RuntimeVariableSerializer.cpp} (100%) rename Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/{ScriptUserDataSerializer.h => RuntimeVariableSerializer.h} (100%) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/ScriptUserDataSerializer.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.cpp similarity index 100% rename from Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/ScriptUserDataSerializer.cpp rename to Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.cpp diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/ScriptUserDataSerializer.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.h similarity index 100% rename from Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/ScriptUserDataSerializer.h rename to Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.h From 935bef61b2dff21624c197dd52aa30ecf46ae2d5 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Wed, 11 Aug 2021 15:29:42 -0700 Subject: [PATCH 134/205] Rename NonUniformScale svg icon to fix warning. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../Viewport/{Non Uniform Scale.svg => NonUniformScale.svg} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Assets/Editor/Icons/Components/Viewport/{Non Uniform Scale.svg => NonUniformScale.svg} (100%) diff --git a/Assets/Editor/Icons/Components/Viewport/Non Uniform Scale.svg b/Assets/Editor/Icons/Components/Viewport/NonUniformScale.svg similarity index 100% rename from Assets/Editor/Icons/Components/Viewport/Non Uniform Scale.svg rename to Assets/Editor/Icons/Components/Viewport/NonUniformScale.svg From 016cfef6ca569b3a407e819481ef6a83d661202c Mon Sep 17 00:00:00 2001 From: Jacob Hilliard <64656371+jcbhl@users.noreply.github.com> Date: Wed, 11 Aug 2021 15:32:11 -0700 Subject: [PATCH 135/205] Visualizer: fix empty rows being shown (#2881) Fixes a bug with the visualizer where there would be empty rows shown, e.g. threads without any profiling regions. This was especially noticable when going from a high thread count sample (MultiThread) to a low thread count sample, where most of the visualizer would be empty lines. This adds a data culling step to remove the threads without any remaining execution data + an early out so that all threads shown onscreen must have some regions recorded. Signed-off-by: Jacob Hilliard --- .../Code/Include/Atom/Utils/ImGuiCpuProfiler.inl | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl index ffc9a60c00..a24fdbf1d8 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl @@ -329,7 +329,7 @@ namespace AZ ImGui::Text("Viewport width: %.3f ms", CpuProfilerImGuiHelper::TicksToMs(GetViewportTickWidth())); ImGui::Text("Ticks [%lld , %lld]", m_viewportStartTick, m_viewportEndTick); - ImGui::Text("Recording %ld threads", RHI::CpuProfiler::Get()->GetTimeRegionMap().size()); + ImGui::Text("Recording %zu threads", m_savedData.size()); ImGui::Text("%llu profiling events saved", m_savedRegionCount); ImGui::NextColumn(); @@ -389,6 +389,11 @@ namespace AZ return wrapper.m_startTick < target; }); + if (regionItr == singleThreadData.end()) + { + continue; + } + // Draw all of the blocks for a given thread/row u64 maxDepth = 0; while (regionItr != singleThreadData.end()) @@ -559,6 +564,14 @@ namespace AZ m_savedRegionCount -= sizeBeforeRemove - savedRegions.size(); } + + // Remove any threads from the top-level map that no longer hold data + AZStd::erase_if( + m_savedData, + [](const auto& singleThreadDataEntry) + { + return singleThreadDataEntry.second.empty(); + }); } inline void ImGuiCpuProfiler::DrawBlock(const TimeRegion& block, u64 targetRow) From 6c83dcd702ed015d9f6d6a3b08685a4f59752673 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Wed, 11 Aug 2021 15:44:04 -0700 Subject: [PATCH 136/205] [redcode/crythread-2nd-pass] fixed another missing include Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp b/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp index 5cc3070cdb..44426f6d01 100644 --- a/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp +++ b/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp @@ -9,6 +9,7 @@ #include #include +#include int APIENTRY WinMain([[maybe_unused]] HINSTANCE hInstance, [[maybe_unused]] HINSTANCE hPrevInstance, [[maybe_unused]] LPSTR lpCmdLine, [[maybe_unused]] int nCmdShow) { From 5a891c8cbdd769744a75c1118b6445199ce249fd Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Wed, 11 Aug 2021 15:54:59 -0700 Subject: [PATCH 137/205] [redcode/crythread-2nd-pass] replaced remaining CrySpinLock/CryWriteLock usage with equivalent AZStd version Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Legacy/CryCommon/Synchronization.h | 33 ++++-------------------- Code/Legacy/CryCommon/physinterface.h | 6 +++-- Code/Legacy/CrySystem/DebugCallStack.cpp | 7 ++--- 3 files changed, 13 insertions(+), 33 deletions(-) diff --git a/Code/Legacy/CryCommon/Synchronization.h b/Code/Legacy/CryCommon/Synchronization.h index 3bac215998..d38160c967 100644 --- a/Code/Legacy/CryCommon/Synchronization.h +++ b/Code/Legacy/CryCommon/Synchronization.h @@ -21,7 +21,7 @@ // //--------------------------------------------------------------------------- -#include "MultiThread.h" +#include namespace stl { @@ -51,43 +51,20 @@ namespace stl struct PSyncMultiThread { - PSyncMultiThread() - : _Semaphore(0) {} + PSyncMultiThread() {} void Lock() { - CryWriteLock(&_Semaphore); + m_lock.lock(); } void Unlock() { - CryReleaseWriteLock(&_Semaphore); - } - int IsLocked() const volatile - { - return _Semaphore; + m_lock.unlock(); } private: - volatile int _Semaphore; + AZStd::spin_mutex m_lock; }; - -#ifdef _DEBUG - - struct PSyncDebug - : public PSyncMultiThread - { - void Lock() - { - assert(!IsLocked()); - PSyncMultiThread::Lock(); - } - }; - -#else - - typedef PSyncNone PSyncDebug; - -#endif }; #endif // CRYINCLUDE_CRYCOMMON_SYNCHRONIZATION_H diff --git a/Code/Legacy/CryCommon/physinterface.h b/Code/Legacy/CryCommon/physinterface.h index 89b7318eaa..b1aaa5aef4 100644 --- a/Code/Legacy/CryCommon/physinterface.h +++ b/Code/Legacy/CryCommon/physinterface.h @@ -26,6 +26,8 @@ #include +#include + ////////////////////////////////////////////////////////////////////////// // Physics defines. ////////////////////////////////////////////////////////////////////////// @@ -2834,8 +2836,8 @@ struct IGeometry virtual int PointInsideStatus(const Vec3& pt) = 0; // for meshes, will create an auxiliary hashgrid for acceleration // IntersectLocked - the main function for geomtries. pdata1,pdata2,pparams can be 0 - defaults will be assumed. // returns a pointer to an internal thread-specific contact buffer, locked with the lock argument - virtual int IntersectLocked(IGeometry* pCollider, geom_world_data* pdata1, geom_world_data* pdata2, intersection_params* pparams, geom_contact*& pcontacts, WriteLockCond& lock) = 0; - virtual int IntersectLocked(IGeometry* pCollider, geom_world_data* pdata1, geom_world_data* pdata2, intersection_params* pparams, geom_contact*& pcontacts, WriteLockCond& lock, int iCaller) = 0; + virtual int IntersectLocked(IGeometry* pCollider, geom_world_data* pdata1, geom_world_data* pdata2, intersection_params* pparams, geom_contact*& pcontacts, AZStd::spin_mutex& lock) = 0; + virtual int IntersectLocked(IGeometry* pCollider, geom_world_data* pdata1, geom_world_data* pdata2, intersection_params* pparams, geom_contact*& pcontacts, AZStd::spin_mutex& lock, int iCaller) = 0; // Intersect - same as Intersect, but doesn't lock pcontacts virtual int Intersect(IGeometry* pCollider, geom_world_data* pdata1, geom_world_data* pdata2, intersection_params* pparams, geom_contact*& pcontacts) = 0; // FindClosestPoint - for non-convex meshes only does local search, doesn't guarantee global minimum diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp index 576c3ee9fb..a043f16756 100644 --- a/Code/Legacy/CrySystem/DebugCallStack.cpp +++ b/Code/Legacy/CrySystem/DebugCallStack.cpp @@ -18,6 +18,7 @@ #include #include +#include #define VS_VERSION_INFO 1 #define IDD_CRITICAL_ERROR 101 @@ -152,13 +153,13 @@ void DebugCallStack::SetUserDialogEnable(const bool bUserDialogEnable) DWORD g_idDebugThreads[10]; const char* g_nameDebugThreads[10]; int g_nDebugThreads = 0; -volatile int g_lockThreadDumpList = 0; +AZStd::spin_mutex g_lockThreadDumpList = 0; void MarkThisThreadForDebugging(const char* name) { EBUS_EVENT(AZ::Debug::EventTraceDrillerSetupBus, SetThreadName, AZStd::this_thread::get_id(), name); - WriteLock lock(g_lockThreadDumpList); + AZStd::lock_guard lock(g_lockThreadDumpList); DWORD id = GetCurrentThreadId(); if (g_nDebugThreads == sizeof(g_idDebugThreads) / sizeof(g_idDebugThreads[0])) { @@ -178,7 +179,7 @@ void MarkThisThreadForDebugging(const char* name) void UnmarkThisThreadFromDebugging() { - WriteLock lock(g_lockThreadDumpList); + AZStd::lock_guard lock(g_lockThreadDumpList); DWORD id = GetCurrentThreadId(); for (int i = g_nDebugThreads - 1; i >= 0; i--) { From 337ea488b6539ced5d2e9bf2518b52c93b8fdf56 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Wed, 11 Aug 2021 15:57:49 -0700 Subject: [PATCH 138/205] [redcode/crythread-2nd-pass] replaced remaining CryInterlocked* usage with equivalent AZStd version Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Legacy/CryCommon/IFunctorBase.h | 8 +++-- Code/Legacy/CryCommon/smartptr.h | 36 ++++++++----------- .../Code/Source/Engine/AudioRequests.cpp | 2 +- 3 files changed, 20 insertions(+), 26 deletions(-) diff --git a/Code/Legacy/CryCommon/IFunctorBase.h b/Code/Legacy/CryCommon/IFunctorBase.h index 2a8af50d33..c7d39ee923 100644 --- a/Code/Legacy/CryCommon/IFunctorBase.h +++ b/Code/Legacy/CryCommon/IFunctorBase.h @@ -15,6 +15,8 @@ #pragma once +#include + // Base class for functor storage. // Not intended for direct usage. class IFunctorBase @@ -27,19 +29,19 @@ public: void AddRef() { - CryInterlockedIncrement(&m_nReferences); + m_nReferences.fetch_add(1, AZStd::memory_order_acq_rel); } void Release() { - if (CryInterlockedDecrement(&m_nReferences) <= 0) + if (m_nReferences.fetch_sub(1, AZStd::memory_order_acq_rel) == 1) { delete this; } } protected: - volatile int m_nReferences; + AZStd::atomic_int m_nReferences; }; // Base Template for specialization. diff --git a/Code/Legacy/CryCommon/smartptr.h b/Code/Legacy/CryCommon/smartptr.h index 246e18d541..fd833b12e3 100644 --- a/Code/Legacy/CryCommon/smartptr.h +++ b/Code/Legacy/CryCommon/smartptr.h @@ -18,6 +18,9 @@ void CryFatalError(const char*, ...) PRINTF_PARAMS(1, 2); #if defined(APPLE) #include #endif + +#include + ////////////////////////////////////////////////////////////////// // SMART POINTER ////////////////////////////////////////////////////////////////// @@ -352,38 +355,32 @@ protected: class CMultiThreadRefCount { public: - CMultiThreadRefCount() - : m_cnt(0) {} + CMultiThreadRefCount() {} virtual ~CMultiThreadRefCount() {} inline int AddRef() { - return CryInterlockedIncrement(&m_cnt); + return m_count.fetch_add(1, AZStd::memory_order_acq_rel) + 1; // because we get the original value back } inline int Release() { - const int nCount = CryInterlockedDecrement(&m_cnt); - assert(nCount >= 0); + const int nCount = m_count.fetch_sub(1, AZStd::memory_order_acq_rel) - 1; // because we get the original value back + AZ_Assert(nCount >= 0, "Deleting Reference Counted Object Twice"); if (nCount == 0) { delete this; } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } return nCount; } - inline int GetRefCount() const { return m_cnt; } + inline int GetRefCount() const { return m_count.load(AZStd::memory_order_acquire); } protected: // Allows the memory for the object to be deallocated in the dynamic module where it was originally constructed, as it may use different memory manager (Debug/Release configurations) virtual void DeleteThis() { delete this; } private: - volatile int m_cnt; + AZStd::atomic_int m_count{ 0 }; }; // base class for interfaces implementing reference counting that needs to be thread-safe @@ -404,29 +401,24 @@ public: virtual void AddRef() { - CryInterlockedIncrement(&m_nRefCounter); + m_nRefCounter.fetch_add(1, AZStd::memory_order_acq_rel); } virtual void Release() { - const int nCount = CryInterlockedDecrement(&m_nRefCounter); - assert(nCount >= 0); + const int nCount = m_nRefCounter.fetch_sub(1, AZStd::memory_order_acq_rel) - 1; // because we get the original value back + AZ_Assert(nCount >= 0, "Deleting Reference Counted Object Twice"); if (nCount == 0) { delete this; } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } } - Counter NumRefs() const { return m_nRefCounter; } + Counter NumRefs() const { return m_nRefCounter.load(AZStd::memory_order_acquire); } protected: - volatile Counter m_nRefCounter; + AZStd::atomic m_nRefCounter{ 0 }; }; typedef _i_reference_target _i_reference_target_t; diff --git a/Gems/AudioSystem/Code/Source/Engine/AudioRequests.cpp b/Gems/AudioSystem/Code/Source/Engine/AudioRequests.cpp index 35da74b0de..0862483ab8 100644 --- a/Gems/AudioSystem/Code/Source/Engine/AudioRequests.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/AudioRequests.cpp @@ -153,7 +153,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////////// void SAudioRequestDataInternal::Release() { - const int nCount = CryInterlockedDecrement(&m_nRefCounter); + const int nCount = m_nRefCounter.fetch_sub(1, AZStd::memory_order_acq_rel) - 1; // because we get the original value back AZ_Assert(nCount >= 0, "AudioRequests Release - Decremented reference counter too many times!"); if (nCount == 0) From dba26cc2357b001da4a890ca211a78db3afce335 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 11 Aug 2021 16:07:46 -0700 Subject: [PATCH 139/205] Fix code that trips -Wsign-compare (#3046) Signed-off-by: Chris Burel --- .../Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp index ac824bfc4d..3dd49574fd 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp @@ -43,7 +43,7 @@ void CUiAVNewSequenceDialog::OnOK() return; } - for (int k = 0; k < CUiAnimViewSequenceManager::GetSequenceManager()->GetCount(); ++k) + for (unsigned int k = 0; k < CUiAnimViewSequenceManager::GetSequenceManager()->GetCount(); ++k) { CUiAnimViewSequence* pSequence = CUiAnimViewSequenceManager::GetSequenceManager()->GetSequenceByIndex(k); QString fullname = pSequence->GetName(); From 094d06f1e370c04fe0edd0a8abea190f71994253 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 11 Aug 2021 16:08:05 -0700 Subject: [PATCH 140/205] Update EMotionFX layouts to deal with changed QObject names (#3045) Commit 1837d05169 changed some of the EMotionFX editor's QObject names to match their new class member names. Unfortunately this broke the EMotionFX layouts. This recreates the good layouts to contain the new QObject names. Signed-off-by: Chris Burel --- .../Assets/Editor/Layouts/AnimGraph.layout | Bin 6480 -> 7200 bytes .../Editor/Layouts/SimulatedObjects.layout | Bin 7203 -> 6901 bytes 2 files changed, 0 insertions(+), 0 deletions(-) diff --git a/Gems/EMotionFX/Assets/Editor/Layouts/AnimGraph.layout b/Gems/EMotionFX/Assets/Editor/Layouts/AnimGraph.layout index 85fa2f2253311fb9b538d0953c5951658f46a683..e85d6054a3e54df86030125994f050171e52f622 100644 GIT binary patch literal 7200 zcmc&&Ux-vy82@J1RWV4TAPb8tSZD~{bN|epD^YD~F8q?~xIc5abQ$-r z#FKHU8_%6MAKsaqe;wnAW7@lZ^nT{i?kT~|RO7Bu;?HhIpOfFO*Yf53#aZKqrigE* zPVEd5Gxiv~Wf&OE zN$Sh_e8;x6-m2DX*5+3$wbq2Zq3zuB#|}sPBj#sDuV@aBYtZfKX#CN2XRlCCBcJcd ztI^lYH}8M94r{wse)rYY((tb0&^E^lY{&7Pg0fvl)*f5_4e`ynamhc^>Ccm^Kh^TC zAD`ie@-9xUzSKGHlM^2&_*)@SApLatvr`;r^rF7Q^)c(YYHhTBNHXNXwN>akFt|_0!w3PjeU!^k zIbjCzu(LW|v7W6~4oQ|gATJ69#|=G(MCfF|!}dm{Rvfl=RBEG@rl}MQUMH1rdyZ3Z z1B8R^N(MYc>&1j*%Y);qLf*B*07;?zEb3&uZjMy2T4Wdxj$c4x6r3>3E6IWftQYmB zwY6L;k5!ryub>N`7eVMLN99o;@?PH0ATI`M)p4uXEI0N`mOQwg3Y79)aAAAF0`stb z1$R<+zmMG|YLndL-QVbayb$R>A~LXQn!Ccj8#t_$k_^i(Daw#+6D7Xb;)#P_L0k!N z4)N3$H{M5bzP!v`8)t8ly;6~JsY^?$IM!qWSCcZT?hPa&T1CZf&D>((@^3Zb?~Ql6~3$1^jqM9O60+f4^Cho6-k&vRvwc< z%&)?=MPQVrA^Tz0LAZ8IBX5umc((%*D6t7gQ`RP2?~?;S%v}da`>ScLpHw6p+R#6F zuuQgj&Wlftj-j{Ebpthv`T-i??n097Te&~t+SSf8P7K8{jK3G73f1Z*wIv-o z+z#6jlQT(;6++bm1sIK=uLGBaFbf%WxhJ6HZ=D)Hp2{_YV6O$2R1p-DxTo}(rVf%b(l<}J2OUCrWdsg9Eje#&@|LUDZ%v6wGdf9u*yh; znSFnvhx!4{WWMO~lP)^wNtOzlN?&#wH&6i92_vev##!*B4PUy52>2exajjYk!*Z<7 zx>4ejshqVJ7Ie>?fjWR5iZF$Xz>*)q(W7{9t-UJsykc`9=6c3}XUH1g^>OKVTbDy9 zaT=X@{ZX<$rnR~;pZ87y_Xl*{dhb2vFf))Vqo)_7B(1mOy;`>#g_u}82?L&v&Cn^9 zZkgMQN_UGY1;iyoK>N89@tKrSHWp{f{6%5Oukh;q20uFMl-0S3dwoV6>I*E9`kbtk zTw%DzFnqY^J2*y_5=YKw!Gt2C3 zq6bkyFk)i7c+n^u$VtJAU=H!%E#%-q5QJPrQ3wiNL=tt)`hC@1o9WC>7;%!Wrn;)T z|N0-_|EQYTJ-(+j{M_Wey{jU3Nz{fHnwC|t9NV$Q8a#A*ITL@tuzdNOkNEuRwr|h< z`I^Y%6Qh?tKY1m$|MJ!|n(i0tG^x3yosXd(HFP9GGyKhHzW-zoj0^a8leguq=RY>` z^cX)I`m3;q&FE*|3-lxXDq2L5(}U4ZBzm^TmOdn%S${3N=@9KT>!YK~Iivk!V)3i5M^@rbQfkau&sOWRjpLFc z4z8_2*C7^4c|kt*$4;Z<9l&9DM#sZwb+OfGz9NbIH2%H)@!%JHAKeK(Cy-Qd*wv`j z%Jo_6>2g!j!$G;O=PTPsxeS#PrVtNteb`e$R-}l7;};4Ar{IKPUP&4_ATJtCYrI@9 z&sCa|R$ize^pvCWp6}$nyq`im?5)-+)-%=0aY+*g)JcSc8v=*W3!M~j7_L`qRNT99#u)CBPWstt~EBpmDu?#?v)dkI0Ksk(xB5B~{$(vWVG|%<88_ zjPszd+AeM!3KGcKmON!Zvz)>Yip>}w0MqZ#A#LEqnx;9N5VObdcn)7KQ1}YX*+dl{ zOBmpSDMh$oA7D;HR4g!06SktiiLM*hKblzY!)#w)9BDkk2+Yd)c%ksfdN1_-0ppiY z==u#rw}1qKnV6xk%TEklr@6+jLd^$ z<_ehb*OYFZeo~QaXhZ+xfiltNm=~WKy^YRL(+$w%{s7YePoE~yUeEmz)~RB5y)6N@mh2IF=Cw7Pam118hx_KeY$=_MnS z-1`@r2AU`(m>#+oBI~o?L(pNJQh4|sJ;aMs$sFq~I_OE33Ytn^wi~yh0Iu(&>(*c6 zEO^p}FI_|gd=KNeS0!B*$=$&JL0AR2dFTo=kq=nT#ye_8L$o~X?;LOIel{$Iqtkv%rr92@Q)12im>B)F|<6FZ#o(i^&6>o7R< zSdl>4w?YG6Z2iM%o$UM17tJE(7YJ^?i|p`X!YNp!89q1vJ;iBELY?{e0IRy`f;JM6vX4+v1p Eza4RxFaQ7m diff --git a/Gems/EMotionFX/Assets/Editor/Layouts/SimulatedObjects.layout b/Gems/EMotionFX/Assets/Editor/Layouts/SimulatedObjects.layout index 9deac32edb492ea4d405a1bceca49df4954e0511..a7879584a9601f005f1c5aeba8d04f3320c8c66c 100644 GIT binary patch literal 6901 zcmc&&U2IfE6h7PSpAdc&H5!R7k(g=>xxah&qERbiEh%i%+CYN}h26lGcDJ^>k?^32 zL?Z^GQ9<+teK5Xgf>G2&A9ye^A;cIHCHSJe7=L0!eL@iYzS%o_?=A~&Y3a^pX71cO z^PO|PIcI)$_1eL{?&0*%qZ=Q0TBV%2OWP8rk+2NQlnY3F`!>FxeMZDc$1*2kVSDrF zzFxMwkePx?)lr;R7FLfx*dp?s?u>CSy5;ZTtKq{0dEm?{B~O7z3a!uS{$onM(edS1 zQ9O~}!)$B3{*U(bQ%~Iw;)V9;?~DH~%h7G!Uu0O}e9%+YPxGPi`**)^>L1|fq{r8` zHJ-Ld+ioOb}GAW`t1Ev{e43{z3VK~cMRKfZQHXPNA@iGkoa9eJ#pMU z66OD`Wp5~XKkp6sp}eD|Wyhoa4(>lt#ouBnd*Rn74!y^IS}*FGp2+5V`Vs@#d?q`Y zSf9&h3Qx(L^I#jE>6>2CNqLsJF;Wh zVj-VMmx^P#e0EZru|AlV;o7F$qbq*(WmZ1RgH1^)E8_{YpB=R@+$=56LFU%D5DyC^?jQnZi>^GO9I& zdIx$W>i#V8#SoN0Yuhank7HXcApbH`WD}?^eh!e^7emecW#stxGeBO?5j}xJ&w_PllvNdSxA;sW!n)z?*C0DE3ZYawh`6|AlJDC_P4%n5|};u91pmM+&ghT`F|2K=um zBbcJC$~*a-gO_Gyvc@mzGi1z0NvW8VKqASIQAGxbyA5XCf)}4xn{h{#87@GQV8>UW zu7Y(mGZ-8@h(e{=H6jc&8!~-_fTk^+QA)f|xp)osRIyJ1-zE_51rWId2#8gY=UFfjvvwkBKfM9|0A1kNXr-tVXpMi10Z(uw6GvBj zm!&+*MQN(h2F7u`kCx5xLl{!w5Z=}LDPC^C%QY3Jt>axDW|!_tr5F*mQjRovoNIV! zY!dZ7#JE@~dI%z4VNgL=;n*ClXpX%K9p1(GuE1A1mjLiLyl4%TVkBVQXhB~j1{ftP zT}Ne5O-Tt8F@jYz3-Z(O+)+GjMSDHIW-vinJeMbE6INSJ;-yCPs`Ypx7+=6N1``OG zZMQ>iiApfh+S!Yx&5%sab5LlGwBKv4-# z*@$tiF9G$7h^RVKp%%5-w3)6-zoL&Y^qs(`LKDeyW5)Hv0~na&YPPvrg)`T};Mp88 zF7^kA<;xm}TG>#PQ`DFeQ_W%fBH(?ZP*Geh2jPON)+&(Iz7TdyL?z~BwXBtgWrM7k zMsWOJ-^+zX>@Vo>O;m?_8)9)l1sOw(D`wSn-4C=i8WC>a@){ZtgH#p&%d55!N3AqG zYj7_zRSQchXo|0Zio6D2;<5Gg%@2d@hDUTz~}%GoLe z0gETJ*!%!Is8r1G9}S#Yq?0w*3kDQ79@f>{4UZw*w+-b?T%&Q`K{Pt$C?wJ9D2sv7 z)P~0NkFa$PZNPaMxpG{lhDfd00c4jtL&X{o{>$yV3U-$&!-8#+#Z0m~NfwemM_&6J z2t0rn)3>$GF%md?k!x*@@5jpxp{+AmeE_5qH}q&4K%<_W`c%8{2iSQAou+SRxMfwY zCBUgSr?GK3;K|U=#uoHT?pA?)v6I1rt~TSLo~`<()cz;F^KdZ}TPqhO;MAK_+8RF= z+B)+&jUR)kNK%1c&rW@B>v$S=<}qSsb_Ulr;2cG+^<8eKQ9I{&-+@LsQ)VT@;>*vJ_?`1A*(1~gG^h#inuQ_5x^lHwW&8BsF4XWJT0_!-t Y4c;%&vwCCXjrZX^v&L2S3#q1|L}Cc7woP`n~y zQP8T0ulCtDUwrVvrxFl^A{E3pL46Q?6Kmr4otfE7I*FU?W(uBgX3osc`Tqa^{>wQh zC#M&t#?QXbn-?-hHe+apCY$?cL`k6cjk6Eg|EDP1R;d)K#mtGq z+P?hJFDG+Ti}}eJLw7CB)NRvr49kjBk$?u7t~E-vYG%P}tj8(7MW4@unRT*;k<%?b zn{(|r6$yD5ua+vA{92)YF;3|%8a90%Y&Yw;hHLAlW#nR2B;;YX?p5@+D@DS(c+<0X_gBOub7!Vzv3-7VswQn5(R?1cYKe*7N7n>PjV2pn|vDj8<(f#tawt9nlz+@YgN`U zYD!T(t>eCmFEWvThPa{$u0R`lT_lyl_NRvaOTWlEP;LBKKpwseYF_b?Q$O^NtceA! zZ6J@_1LVW#=b`&Pkquxul9Md{$c804kPp8AeZhMAKA?ZPKb>{p>A-Wqg$8s}93UT> zgezZzz8?emC3NgJM_$JB)tlUTrf=ecmUOswzy=>kTDZiN`+4Xi6lc-6d5pK0xG93+&GxOos!kh)xi{$(WY z1x3%8jN!K#P*wz0{HBKA>PYt*h+G8%a#iFl^fzQw?vHXL?PoL~9-s>X8&5gv1X@$q zG4pvsuyJ;GbQvnLY+Q9UTf;ogckyI${vxKdI7D=%-tpr)ajX@z5z*zqy9`$<#f&hO za-_+juMwe%QQS`v<5r~@A;^4%K?QAvV{*2l8L}n$8Rowd#LDmy0M_y1$F@?;1k{b> z2e_lWBEcwG>AE5d$|X%WqJS#uf&5uS?g~cBcs`9^i*S&KvG1U>sJ3+CPBSJ|J+24y zYj9)WK*$_oE;gwI8?7B&F15punMAI1NE}5;Nc^hA;S!XD)K!eX=q94K=o|+P4VY8{ zMNN#n4&&1A0ri^>Q4y|CMQxBaGgKK@j1i{36~@%JP~<_FxJj0KGj0wMz{IR5Z?jsp zJ(pzioI_U)JSKie=gZ3!(hjJxp0b>x%1TT(hr@RQ@k?LG!378luBufatJ_H=t12gD zTAr3AIlhPF_^)qwON+#x;PSgps~_))#d(!vOfgo>E_Xc%v}Z#^xGVV~9v}v-EB_zv zT0$&UX}H(mTBNHdlvL1^It~@jsQI`YROWIAMahifp~w6n^JP-vGd+=#4Ln`u)yHXdclO^!oz#_zJc2iuG^XlCe~=|caV*i zpM?YtkTJF0hA`aw7B*tj2AucNTia!7h?eGV`jXm1C3;W(-PTn}^@3uy4BZ2cS`gU7WSMYMFZEGLZ2SBPVg@fQek9(Az;jZ?`Pq6bZ ze6)8v+e=pKSOT0VpC&2@z#DBldn@QWu2z9*i5tNnyq&`!%GU6tH2epC{|z7YV{7Z6 z1e_?J($>_qwypj9G<6N4I+{xSC_BS*8&4e1~%wzTLyA3tzJxguSgjV28c^SJnP%Rd4cl+@_PNe*rXS By>S2l From 0f347c11bff9b1978a77c6f10a860f5e314d6ad7 Mon Sep 17 00:00:00 2001 From: SJ Date: Wed, 11 Aug 2021 16:08:21 -0700 Subject: [PATCH 141/205] Add header file needed for no unity builds (#3047) Signed-off-by: amzn-sj --- .../Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp index 148b1cbdfe..4099443913 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include From c173dee2bcf8c348babdb93b1ea9368b0027050b Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Wed, 11 Aug 2021 16:38:54 -0700 Subject: [PATCH 142/205] [redcode/crythread-2nd-pass] removed MultiThread.h along with external CryInterlocked* definitions Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Legacy/CryCommon/MultiThread.h | 277 -------------------- Code/Legacy/CryCommon/WinBase.cpp | 85 +----- Code/Legacy/CryCommon/crycommon_files.cmake | 1 - Code/Legacy/CryCommon/platform.h | 4 - Code/Legacy/CryCommon/platform_impl.cpp | 52 ---- Code/Legacy/CrySystem/Log.h | 1 - 6 files changed, 1 insertion(+), 419 deletions(-) delete mode 100644 Code/Legacy/CryCommon/MultiThread.h diff --git a/Code/Legacy/CryCommon/MultiThread.h b/Code/Legacy/CryCommon/MultiThread.h deleted file mode 100644 index c3aa892d14..0000000000 --- a/Code/Legacy/CryCommon/MultiThread.h +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#if defined(APPLE) || defined(LINUX) -#include -#endif - -#include - -#include "CryAssert.h" - -// Section dictionary -#if defined(AZ_RESTRICTED_PLATFORM) -#define MULTITHREAD_H_SECTION_TRAITS 1 -#define MULTITHREAD_H_SECTION_DEFINE_CRYINTERLOCKEXCHANGE 2 -#define MULTITHREAD_H_SECTION_IMPLEMENT_CRYSPINLOCK 3 -#define MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDADD 4 -#define MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDADDSIZE 5 -#define MULTITHREAD_H_SECTION_CRYINTERLOCKEDFLUSHSLIST_PT1 6 -#define MULTITHREAD_H_SECTION_CRYINTERLOCKEDFLUSHSLIST_PT2 7 -#define MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDCOMPAREEXCHANGE64 8 -#endif - -#define WRITE_LOCK_VAL (1 << 16) - -// Traits -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_TRAITS - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif - -void CrySpinLock(volatile int* pLock, int checkVal, int setVal); -void CryReleaseSpinLock (volatile int*, int); - -LONG CryInterlockedIncrement(int volatile* lpAddend); -LONG CryInterlockedDecrement(int volatile* lpAddend); -LONG CryInterlockedOr(LONG volatile* Destination, LONG Value); -LONG CryInterlockedExchangeAdd(LONG volatile* lpAddend, LONG Value); -LONG CryInterlockedCompareExchange(LONG volatile* dst, LONG exchange, LONG comperand); -void* CryInterlockedCompareExchangePointer(void* volatile* dst, void* exchange, void* comperand); -void* CryInterlockedExchangePointer (void* volatile* dst, void* exchange); - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_DEFINE_CRYINTERLOCKEXCHANGE - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif - -ILINE void CrySpinLock(volatile int* pLock, int checkVal, int setVal) -{ -#ifdef _CPU_X86 -# ifdef __GNUC__ - int val; - __asm__ __volatile__ ( - "0: mov %[checkVal], %%eax\n" - " lock cmpxchg %[setVal], (%[pLock])\n" - " jnz 0b" - : "=m" (*pLock) - : [pLock] "r" (pLock), "m" (*pLock), - [checkVal] "m" (checkVal), - [setVal] "r" (setVal) - : "eax", "cc", "memory" - ); -# else //!__GNUC__ - __asm - { - mov edx, setVal - mov ecx, pLock -Spin: - // Trick from Intel Optimizations guide -#ifdef _CPU_SSE - pause -#endif - mov eax, checkVal - lock cmpxchg [ecx], edx - jnz Spin - } -# endif //!__GNUC__ -#else // !_CPU_X86 -# if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_IMPLEMENT_CRYSPINLOCK - #include AZ_RESTRICTED_FILE(MultiThread_h) -# endif -# if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -# undef AZ_RESTRICTED_SECTION_IMPLEMENTED -# elif defined(APPLE) || defined(LINUX) - // register int val; - // __asm__ __volatile__ ( - // "0: mov %[checkVal], %%eax\n" - // " lock cmpxchg %[setVal], (%[pLock])\n" - // " jnz 0b" - // : "=m" (*pLock) - // : [pLock] "r" (pLock), "m" (*pLock), - // [checkVal] "m" (checkVal), - // [setVal] "r" (setVal) - // : "eax", "cc", "memory" - // ); - //while(CryInterlockedCompareExchange((volatile long*)pLock,setVal,checkVal)!=checkVal) ; - uint loops = 0; - while (__sync_val_compare_and_swap((volatile int32_t*)pLock, (int32_t)checkVal, (int32_t)setVal) != checkVal) - { -# if !defined (ANDROID) && !defined(IOS) - _mm_pause(); -# endif - - if (!(++loops & 0x7F)) - { - usleep(1); // give threads with other prio chance to run - } - else if (!(loops & 0x3F)) - { - sched_yield(); // give threads with same prio chance to run - } - } -# else - // NOTE: The code below will fail on 64bit architectures! - while (_InterlockedCompareExchange((volatile LONG*)pLock, setVal, checkVal) != checkVal) - { - _mm_pause(); - } -# endif -#endif -} - -ILINE void CryReleaseSpinLock(volatile int* pLock, int setVal) -{ - *pLock = setVal; -} - -////////////////////////////////////////////////////////////////////////// -ILINE void CryInterlockedAdd(volatile int* pVal, int iAdd) -{ -#ifdef _CPU_X86 -# ifdef __GNUC__ - __asm__ __volatile__ ( - " lock add %[iAdd], (%[pVal])\n" - : "=m" (*pVal) - : [pVal] "r" (pVal), "m" (*pVal), [iAdd] "r" (iAdd) - ); -# else - __asm - { - mov edx, pVal - mov eax, iAdd - lock add [edx], eax - } -# endif -#else - // NOTE: The code below will fail on 64bit architectures! -#if defined(_WIN64) - _InterlockedExchangeAdd((volatile LONG*)pVal, iAdd); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDADD - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(APPLE) || defined(LINUX) - CryInterlockedExchangeAdd((volatile LONG*)pVal, iAdd); -#elif defined(APPLE) - OSAtomicAdd32(iAdd, (volatile LONG*)pVal); -#else - InterlockedExchangeAdd((volatile LONG*)pVal, iAdd); -#endif - -#endif -} - -ILINE void CryInterlockedAddSize(volatile size_t* pVal, ptrdiff_t iAdd) -{ -#if defined(PLATFORM_64BIT) -#if defined(_WIN64) - _InterlockedExchangeAdd64((volatile __int64*)pVal, iAdd); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDADDSIZE - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) - InterlockedExchangeAdd64((volatile LONG64*)pVal, iAdd); -#elif defined(APPLE) || defined(LINUX) - (void)__sync_fetch_and_add((int64_t*)pVal, (int64_t)iAdd); -#else - int64 x, n; - do - { - x = (int64) * pVal; - n = x + iAdd; - } - while (CryInterlockedCompareExchange64((volatile int64*)pVal, n, x) != x); -#endif -#else - CryInterlockedAdd((volatile int*)pVal, (int)iAdd); -#endif -} - - - -////////////////////////////////////////////////////////////////////////// -ILINE void CryWriteLock(volatile int* rw) -{ - CrySpinLock(rw, 0, WRITE_LOCK_VAL); -} - -ILINE void CryReleaseWriteLock(volatile int* rw) -{ - CryInterlockedAdd(rw, -WRITE_LOCK_VAL); -} - -////////////////////////////////////////////////////////////////////////// -struct WriteLock -{ - ILINE WriteLock(volatile int& rw) { CryWriteLock(&rw); prw = &rw; } - ~WriteLock() { CryReleaseWriteLock(prw); } -private: - volatile int* prw; -}; - -////////////////////////////////////////////////////////////////////////// -struct WriteLockCond -{ - ILINE WriteLockCond(volatile int& rw, int bActive = 1) - { - if (bActive) - { - CrySpinLock(&rw, 0, iActive = WRITE_LOCK_VAL); - } - else - { - iActive = 0; - } - prw = &rw; - } - ILINE WriteLockCond() { prw = &(iActive = 0); } - ~WriteLockCond() - { - CryInterlockedAdd(prw, -iActive); - } - void SetActive(int bActive = 1) { iActive = -bActive & WRITE_LOCK_VAL; } - void Release() { CryInterlockedAdd(prw, -iActive); } - volatile int* prw; - int iActive; -}; - - -#if defined(LINUX) || defined(APPLE) -ILINE int64 CryInterlockedCompareExchange64(volatile int64* addr, int64 exchange, int64 comperand) -{ - return __sync_val_compare_and_swap(addr, comperand, exchange); - // This is OK, because long is signed int64 on Linux x86_64 - //return CryInterlockedCompareExchange((volatile long*)addr, (long)exchange, (long)comperand); -} -#else -ILINE int64 CryInterlockedCompareExchange64(volatile int64* addr, int64 exchange, int64 compare) -{ - // forward to system call -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDCOMPAREEXCHANGE64 - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - return _InterlockedCompareExchange64((volatile int64*)addr, exchange, compare); -#endif -} -#endif diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 15146fbac1..a11787fef0 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -1292,90 +1292,7 @@ short CryGetAsyncKeyState(int vKey) return 0; } -#if defined(LINUX) || defined(APPLE) || defined(DEFINE_CRY_INTERLOCKED_INCREMENT) -//[K01]: http://www.memoryhole.net/kyle/2007/05/atomic_incrementing.html -//http://forums.devx.com/archive/index.php/t-160558.html -////////////////////////////////////////////////////////////////////////// -DLL_EXPORT LONG CryInterlockedIncrement(LONG volatile* lpAddend) -{ - /*int r; - __asm__ __volatile__ ( - "lock ; xaddl %0, (%1) \n\t" - : "=r" (r) - : "r" (lpAddend), "0" (1) - : "memory" - ); - return (LONG) (r + 1); */// add, since we get the original value back. - return __sync_fetch_and_add(lpAddend, 1) + 1; -} - -////////////////////////////////////////////////////////////////////////// -DLL_EXPORT LONG CryInterlockedDecrement(LONG volatile* lpAddend) -{ - /*int r; - __asm__ __volatile__ ( - "lock ; xaddl %0, (%1) \n\t" - : "=r" (r) - : "r" (lpAddend), "0" (-1) - : "memory" - ); - return (LONG) (r - 1); */// subtract, since we get the original value back. - return __sync_fetch_and_sub(lpAddend, 1) - 1; -} - -////////////////////////////////////////////////////////////////////////// -DLL_EXPORT LONG CryInterlockedExchangeAdd(LONG volatile* lpAddend, LONG Value) -{ - /* LONG r; - __asm__ __volatile__ ( - #if defined(LINUX64) || defined(APPLE) // long is 64 bits on amd64. - "lock ; xaddq %0, (%1) \n\t" - #else - "lock ; xaddl %0, (%1) \n\t" - #endif - : "=r" (r) - : "r" (lpAddend), "0" (Value) - : "memory" - ); - return r;*/ - return __sync_fetch_and_add(lpAddend, Value); -} - -DLL_EXPORT LONG CryInterlockedOr(LONG volatile* Destination, LONG Value) -{ - return __sync_fetch_and_or(Destination, Value); -} - -DLL_EXPORT LONG CryInterlockedCompareExchange(LONG volatile* dst, LONG exchange, LONG comperand) -{ - return __sync_val_compare_and_swap(dst, comperand, exchange); - /*LONG r; - __asm__ __volatile__ ( - #if defined(LINUX64) || defined(APPLE) // long is 64 bits on amd64. - "lock ; cmpxchgq %2, (%1) \n\t" - #else - "lock ; cmpxchgl %2, (%1) \n\t" - #endif - : "=a" (r) - : "r" (dst), "r" (exchange), "0" (comperand) - : "memory" - ); - return r;*/ -} - - -DLL_EXPORT void* CryInterlockedCompareExchangePointer(void* volatile* dst, void* exchange, void* comperand) -{ - return __sync_val_compare_and_swap(dst, comperand, exchange); - //return (void*)CryInterlockedCompareExchange((long volatile*)dst, (long)exchange, (long)comperand); -} - -DLL_EXPORT void* CryInterlockedExchangePointer(void* volatile* dst, void* exchange) -{ - __sync_synchronize(); - return __sync_lock_test_and_set(dst, exchange); - //return (void*)CryInterlockedCompareExchange((long volatile*)dst, (long)exchange, (long)comperand); -} +#if defined(LINUX) || defined(APPLE) threadID CryGetCurrentThreadId() { diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index d9d4493632..4c1440c67d 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -96,7 +96,6 @@ set(FILES LegacyAllocator.h MetaUtils.h MiniQueue.h - MultiThread.h MultiThread_Containers.h NullAudioSystem.h PNoise3.h diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 9f6e8b212d..842325af9f 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -730,10 +730,6 @@ enum ETriState typedef int socklen_t; #endif - -// Include MultiThreading support. -#include "MultiThread.h" - // In RELEASE disable printf and fprintf #if defined(_RELEASE) && !defined(RELEASE_LOGGING) #if defined(AZ_RESTRICTED_PLATFORM) diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index e16b18bc06..becd88c0b5 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -308,58 +308,6 @@ short CryGetAsyncKeyState([[maybe_unused]] int vKey) #endif } -////////////////////////////////////////////////////////////////////////// -LONG CryInterlockedIncrement(int volatile* lpAddend) -{ - return InterlockedIncrement((volatile LONG*)lpAddend); -} - -////////////////////////////////////////////////////////////////////////// -LONG CryInterlockedDecrement(int volatile* lpAddend) -{ - return InterlockedDecrement((volatile LONG*)lpAddend); -} - -////////////////////////////////////////////////////////////////////////// -LONG CryInterlockedExchangeAdd(LONG volatile* lpAddend, LONG Value) -{ - return InterlockedExchangeAdd(lpAddend, Value); -} - -LONG CryInterlockedOr(LONG volatile* Destination, LONG Value) -{ - return InterlockedOr(Destination, Value); -} - -LONG CryInterlockedCompareExchange(LONG volatile* dst, LONG exchange, LONG comperand) -{ - return InterlockedCompareExchange(dst, exchange, comperand); -} - -void* CryInterlockedCompareExchangePointer(void* volatile* dst, void* exchange, void* comperand) -{ - return InterlockedCompareExchangePointer(dst, exchange, comperand); -} - -void* CryInterlockedExchangePointer(void* volatile* dst, void* exchange) -{ - return InterlockedExchangePointer(dst, exchange); -} - -void CryInterlockedAdd(volatile size_t* pVal, ptrdiff_t iAdd) -{ -#if defined (PLATFORM_64BIT) -#if !defined(NDEBUG) - size_t v = (size_t) -#endif - InterlockedAdd64((volatile int64*)pVal, iAdd); -#else - size_t v = (size_t)CryInterlockedExchangeAdd((volatile long*)pVal, (long)iAdd); - v += iAdd; -#endif - assert((iAdd == 0) || (iAdd < 0 && v < v - (size_t)iAdd) || (iAdd > 0 && v > v - (size_t)iAdd)); -} - ////////////////////////////////////////////////////////////////////////// uint32 CryGetFileAttributes(const char* lpFileName) { diff --git a/Code/Legacy/CrySystem/Log.h b/Code/Legacy/CrySystem/Log.h index 447186e613..085e05e714 100644 --- a/Code/Legacy/CrySystem/Log.h +++ b/Code/Legacy/CrySystem/Log.h @@ -10,7 +10,6 @@ #pragma once #include -#include #include ////////////////////////////////////////////////////////////////////// From c28026a02244666f2a35c19038272d6613f7a9cf Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 11 Aug 2021 10:35:13 -0700 Subject: [PATCH 143/205] [EMotionFX] Avoid using invalid Aabbs Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index 13927f3fd3..5a8fcda907 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -621,7 +621,7 @@ namespace EMotionFX } // Expand the bounding volume by a tolerance area in case set. - if (!AZ::IsClose(m_boundsExpandBy, 0.0f)) + if (!AZ::IsClose(m_boundsExpandBy, 0.0f) && m_aabb.IsValid()) { const AZ::Vector3 center = m_aabb.GetCenter(); const AZ::Vector3 halfExtents = m_aabb.GetExtents() * 0.5f; @@ -1416,8 +1416,12 @@ namespace EMotionFX *outResult = m_staticAabb; EMFX_SCALECODE( - outResult->SetMin(m_staticAabb.GetMin() * m_worldTransform.m_scale); - outResult->SetMax(m_staticAabb.GetMax() * m_worldTransform.m_scale);) + if (m_staticAabb.IsValid()) + { + outResult->SetMin(m_staticAabb.GetMin() * m_worldTransform.m_scale); + outResult->SetMax(m_staticAabb.GetMax() * m_worldTransform.m_scale); + } + ) outResult->Translate(m_worldTransform.m_position); } From 04e64e274f1b8cbd927fb3942cfcee55ecb14a7b Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Wed, 11 Aug 2021 16:53:41 -0700 Subject: [PATCH 144/205] Fix typo in copypasting... Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h index a63e782146..7e6bb3d7b4 100644 --- a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h +++ b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h @@ -27,8 +27,8 @@ namespace AZ MOCK_METHOD1(RegisterNotifier, NotifyEventHandler(NotifyCallback&&)); MOCK_METHOD1(RegisterPreMergeEvent, PreMergeEventHandler(const PreMergeEventCallback&)); MOCK_METHOD1(RegisterPreMergeEvent, PreMergeEventHandler(PreMergeEventCallback&&)); - MOCK_METHOD1(PostMergeEventHandler, PreMergeEventHandler(const PostMergeEventCallback&)); - MOCK_METHOD1(PostMergeEventHandler, PreMergeEventHandler(PostMergeEventCallback&&)); + MOCK_METHOD1(RegisterPostMergeEvent, PostMergeEventHandler(const PostMergeEventCallback&)); + MOCK_METHOD1(RegisterPostMergeEvent, PostMergeEventHandler(PostMergeEventCallback&&)); MOCK_CONST_METHOD2(Get, bool(bool&, AZStd::string_view)); MOCK_CONST_METHOD2(Get, bool(s64&, AZStd::string_view)); From 2b4bd100285d0637d1b240b2d74b2ba5cbaf66a0 Mon Sep 17 00:00:00 2001 From: lsemp3d <58790905+lsemp3d@users.noreply.github.com> Date: Wed, 11 Aug 2021 17:08:09 -0700 Subject: [PATCH 145/205] Updated path to icon that was emitting a warning Signed-off-by: lsemp3d <58790905+lsemp3d@users.noreply.github.com> --- Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp b/Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp index 5ec2637231..b80bba75c2 100644 --- a/Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp +++ b/Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp @@ -311,7 +311,7 @@ namespace ScriptCanvasEditor { if (AZStd::wildcard_match("*.scriptcanvas", fullSourceFileName)) { - return AzToolsFramework::AssetBrowser::SourceFileDetails("Icons/AssetBrowser/ScriptCanvas_16.png"); + return AzToolsFramework::AssetBrowser::SourceFileDetails("Editor/Icons/AssetBrowser/ScriptCanvas_16.png"); } // not one of our types. From d2c87fd21ffa3406b5f0c774d337d6b7564b4eb5 Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Wed, 11 Aug 2021 17:30:16 -0700 Subject: [PATCH 146/205] initial json serialization for editor sc properties Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- .../Code/Include/ScriptCanvas/Core/Datum.h | 3 + .../Serialization/DatumSerializer.cpp | 196 ++++++++++++++++++ .../Serialization/DatumSerializer.h | 37 ++++ .../RuntimeVariableSerializer.cpp | 28 +-- .../Serialization/RuntimeVariableSerializer.h | 4 +- .../Code/Source/SystemComponent.cpp | 12 +- .../Code/scriptcanvasgem_common_files.cmake | 6 +- 7 files changed, 265 insertions(+), 21 deletions(-) create mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.cpp create mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.h diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.h index 83db8fc242..4cbc25b500 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.h @@ -20,6 +20,7 @@ namespace AZ { class ReflectContext; + class DatumSerializer; } namespace ScriptCanvas @@ -33,6 +34,8 @@ namespace ScriptCanvas /// in the editor, regardless of their actual ScriptCanvas or BehaviorContext type. class Datum final { + friend class AZ::DatumSerializer; + public: AZ_TYPE_INFO(Datum, "{8B836FC0-98A8-4A81-8651-35C7CA125451}"); AZ_CLASS_ALLOCATOR(Datum, AZ::SystemAllocator, 0); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.cpp new file mode 100644 index 0000000000..207eb842fd --- /dev/null +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.cpp @@ -0,0 +1,196 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +using namespace ScriptCanvas; + +namespace AZ +{ + AZ_CLASS_ALLOCATOR_IMPL(DatumSerializer, SystemAllocator, 0); + + JsonSerializationResult::Result DatumSerializer::Load + ( void* outputValue + , [[maybe_unused]] const Uuid& outputValueTypeId + , const rapidjson::Value& inputValue + , JsonDeserializerContext& context) + { + namespace JSR = JsonSerializationResult; + + AZ_Assert(outputValueTypeId == azrtti_typeid(), "DatumSerializer Load against output typeID that was not Datum"); + AZ_Assert(outputValue, "DatumSerializer Load against null output"); + + JsonSerializationResult::ResultCode result(JSR::Tasks::ReadField); + auto outputDatum = reinterpret_cast(outputValue); + + bool isOverloadedStorage = false; + AZ_Assert(azrtti_typeidm_isOverloadedStorage)>() == azrtti_typeid() + , "overloaded storage type changed and won't load properly"); + result.Combine(ContinueLoadingFromJsonObjectField + ( &isOverloadedStorage + , azrtti_typeidm_isOverloadedStorage)>() + , inputValue + , "isOverloadedStorage" + , context)); + + ScriptCanvas::Data::Type scType; + AZ_Assert(azrtti_typeidm_type)>() == azrtti_typeid() + , "ScriptCanvas::Data::Type type changed and won't load properly"); + result.Combine(ContinueLoadingFromJsonObjectField + ( &scType + , azrtti_typeidm_type)>() + , inputValue + , "scriptCanvasType" + , context)); + + ScriptCanvas::Datum::eOriginality originality; + AZ_Assert(azrtti_typeidm_originality)>() == azrtti_typeid() + , "m_originality type changed and won't load properly"); + result.Combine(ContinueLoadingFromJsonObjectField + ( &originality + , azrtti_typeidm_originality)>() + , inputValue + , "originality" + , context)); + + AZStd::any storage; + { // datum storage begin + AZ::Uuid typeId = AZ::Uuid::CreateNull(); + + auto typeIdMember = inputValue.FindMember(JsonSerialization::TypeIdFieldIdentifier); + if (typeIdMember == inputValue.MemberEnd()) + { + return context.Report + ( JSR::Tasks::ReadField + , JSR::Outcomes::Missing + , AZStd::string::format("DatumSerializer::Load failed to load the %s member" + , JsonSerialization::TypeIdFieldIdentifier)); + } + + result.Combine(LoadTypeId(typeId, typeIdMember->value, context)); + if (typeId.IsNull()) + { + return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Catastrophic + , "DatumSerializer::Load failed to load the AZ TypeId of the value"); + } + + storage = context.GetSerializeContext()->CreateAny(typeId); + if (storage.empty() || storage.type() != typeId) + { + return context.Report(result, "DatumSerializer::Load failed to load a value matched the reported AZ TypeId. " + "The C++ declaration may have been deleted or changed."); + } + + result.Combine(ContinueLoadingFromJsonObjectField(AZStd::any_cast(&storage), typeId, inputValue, "value", context)); + } // datum storage end + + AZStd::string label; + AZ_Assert(azrtti_typeidm_datumLabel)>() == azrtti_typeid() + , "m_datumLabel type changed and won't load properly"); + result.Combine(ContinueLoadingFromJsonObjectField + ( &label + , azrtti_typeidm_datumLabel)>() + , inputValue + , "originality" + , context)); + + Datum copy(scType, originality, AZStd::any_cast(&storage), scType.GetAZType()); + copy.SetLabel(label); + *outputDatum = copy; + + return context.Report(result, result.GetProcessing() != JSR::Processing::Halted + ? "DatumSerializer Load finished loading Datum" + : "DatumSerializer Load failed to load Datum"); + } + + JsonSerializationResult::Result DatumSerializer::Store + ( rapidjson::Value& outputValue + , const void* inputValue + , const void* defaultValue + , [[maybe_unused]] const Uuid& valueTypeId + , JsonSerializerContext& context) + { + namespace JSR = JsonSerializationResult; + + AZ_Assert(valueTypeId == azrtti_typeid(), "DatumSerializer Store against value typeID that was not Datum"); + AZ_Assert(inputValue, "DatumSerializer Store against null inputValue pointer "); + + auto inputScriptDataPtr = reinterpret_cast(inputValue); + auto defaultScriptDataPtr = reinterpret_cast(defaultValue); + + if (defaultScriptDataPtr) + { + if (*inputScriptDataPtr == *defaultScriptDataPtr) + { + return context.Report + ( JSR::Tasks::WriteValue, JSR::Outcomes::DefaultsUsed, "DatumSerializer Store used defaults for Datum"); + } + } + + JSR::ResultCode result(JSR::Tasks::WriteValue); + outputValue.SetObject(); + + result.Combine(ContinueStoringToJsonObjectField + ( outputValue + , "isOverloadedStorage" + , &inputScriptDataPtr->m_isOverloadedStorage + , defaultScriptDataPtr ? &defaultScriptDataPtr->m_isOverloadedStorage : nullptr + , azrtti_typeidm_isOverloadedStorage)>() + , context)); + + result.Combine(ContinueStoringToJsonObjectField + ( outputValue + , "scriptCanvasType" + , &inputScriptDataPtr->GetType() + , defaultScriptDataPtr ? &defaultScriptDataPtr->GetType() : nullptr + , azrtti_typeidGetType())>() + , context)); + + result.Combine(ContinueStoringToJsonObjectField + ( outputValue + , "originality" + , &inputScriptDataPtr->m_originality + , defaultScriptDataPtr ? &defaultScriptDataPtr->m_originality : nullptr + , azrtti_typeidm_originality)>() + , context)); + + { // datum storage begin + { + rapidjson::Value typeValue; + result.Combine(StoreTypeId(typeValue, inputScriptDataPtr->GetType().GetAZType(), context)); + outputValue.AddMember + ( rapidjson::StringRef(JsonSerialization::TypeIdFieldIdentifier) + , AZStd::move(typeValue) + , context.GetJsonAllocator()); + } + + result.Combine(ContinueStoringToJsonObjectField + ( outputValue + , "value" + , inputScriptDataPtr->GetAsDanger() + , defaultScriptDataPtr ? defaultScriptDataPtr->GetAsDanger() : nullptr + , inputScriptDataPtr->GetType().GetAZType() + , context)); + } // datum storage end + + result.Combine(ContinueStoringToJsonObjectField + ( outputValue + , "label" + , &inputScriptDataPtr->m_datumLabel + , defaultScriptDataPtr ? &defaultScriptDataPtr->m_datumLabel : nullptr + , azrtti_typeidm_datumLabel)>() + , context)); + + return context.Report(result, result.GetProcessing() != JSR::Processing::Halted + ? "DatumSerializer Store finished saving Datum" + : "DatumSerializer Store failed to save Datum"); + } + +} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.h new file mode 100644 index 0000000000..003c5c0383 --- /dev/null +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include + +namespace AZ +{ + class DatumSerializer + : public BaseJsonSerializer + { + public: + AZ_RTTI(DatumSerializer, "{FBEBF833-465F-49F4-AFB1-CC9D3B25C16C}", BaseJsonSerializer); + AZ_CLASS_ALLOCATOR_DECL; + + private: + JsonSerializationResult::Result Load + ( void* outputValue + , const Uuid& outputValueTypeId + , const rapidjson::Value& inputValue + , JsonDeserializerContext& context) override; + + JsonSerializationResult::Result Store + ( rapidjson::Value& outputValue + , const void* inputValue + , const void* defaultValue + , const Uuid& valueTypeId, JsonSerializerContext& context) override; + }; +} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.cpp index 64cf665305..763206df38 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.cpp @@ -8,15 +8,15 @@ #include #include -#include +#include using namespace ScriptCanvas; namespace AZ { - AZ_CLASS_ALLOCATOR_IMPL(ScriptUserDataSerializer, SystemAllocator, 0); + AZ_CLASS_ALLOCATOR_IMPL(RuntimeVariableSerializer, SystemAllocator, 0); - JsonSerializationResult::Result ScriptUserDataSerializer::Load + JsonSerializationResult::Result RuntimeVariableSerializer::Load ( void* outputValue , [[maybe_unused]] const Uuid& outputValueTypeId , const rapidjson::Value& inputValue @@ -24,8 +24,8 @@ namespace AZ { namespace JSR = JsonSerializationResult; - AZ_Assert(outputValueTypeId == azrtti_typeid(), "ScriptUserDataSerializer Load against output typeID that was not RuntimeVariable"); - AZ_Assert(outputValue, "ScriptUserDataSerializer Load against null output"); + AZ_Assert(outputValueTypeId == azrtti_typeid(), "RuntimeVariableSerializer Load against output typeID that was not RuntimeVariable"); + AZ_Assert(outputValue, "RuntimeVariableSerializer Load against null output"); auto outputVariable = reinterpret_cast(outputValue); JsonSerializationResult::ResultCode result(JSR::Tasks::ReadField); @@ -34,28 +34,28 @@ namespace AZ auto typeIdMember = inputValue.FindMember(JsonSerialization::TypeIdFieldIdentifier); if (typeIdMember == inputValue.MemberEnd()) { - return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Missing, AZStd::string::format("ScriptUserDataSerializer::Load failed to load the %s member", JsonSerialization::TypeIdFieldIdentifier)); + return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Missing, AZStd::string::format("RuntimeVariableSerializer::Load failed to load the %s member", JsonSerialization::TypeIdFieldIdentifier)); } result.Combine(LoadTypeId(typeId, typeIdMember->value, context)); if (typeId.IsNull()) { - return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Catastrophic, "ScriptUserDataSerializer::Load failed to load the AZ TypeId of the value"); + return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Catastrophic, "RuntimeVariableSerializer::Load failed to load the AZ TypeId of the value"); } outputVariable->value = context.GetSerializeContext()->CreateAny(typeId); if (outputVariable->value.empty() || outputVariable->value.type() != typeId) { - return context.Report(result, "ScriptUserDataSerializer::Load failed to load a value matched the reported AZ TypeId. The C++ declaration may have been deleted or changed."); + return context.Report(result, "RuntimeVariableSerializer::Load failed to load a value matched the reported AZ TypeId. The C++ declaration may have been deleted or changed."); } result.Combine(ContinueLoadingFromJsonObjectField(AZStd::any_cast(&outputVariable->value), typeId, inputValue, "value", context)); return context.Report(result, result.GetProcessing() != JSR::Processing::Halted - ? "ScriptUserDataSerializer Load finished loading RuntimeVariable" - : "ScriptUserDataSerializer Load failed to load RuntimeVariable"); + ? "RuntimeVariableSerializer Load finished loading RuntimeVariable" + : "RuntimeVariableSerializer Load failed to load RuntimeVariable"); } - JsonSerializationResult::Result ScriptUserDataSerializer::Store + JsonSerializationResult::Result RuntimeVariableSerializer::Store ( rapidjson::Value& outputValue , const void* inputValue , const void* defaultValue @@ -79,7 +79,7 @@ namespace AZ if (inputDatum == defaultDatum) { - return context.Report(JSR::Tasks::WriteValue, JSR::Outcomes::DefaultsUsed, "ScriptUserDataSerializer Store used defaults for RuntimeVariable"); + return context.Report(JSR::Tasks::WriteValue, JSR::Outcomes::DefaultsUsed, "RuntimeVariableSerializer Store used defaults for RuntimeVariable"); } } @@ -95,8 +95,8 @@ namespace AZ result.Combine(ContinueStoringToJsonObjectField(outputValue, "value", AZStd::any_cast(inputAnyPtr), AZStd::any_cast(defaultAnyPtr), inputAnyPtr->type(), context)); return context.Report(result, result.GetProcessing() != JSR::Processing::Halted - ? "ScriptUserDataSerializer Store finished saving RuntimeVariable" - : "ScriptUserDataSerializer Store failed to save RuntimeVariable"); + ? "RuntimeVariableSerializer Store finished saving RuntimeVariable" + : "RuntimeVariableSerializer Store failed to save RuntimeVariable"); } } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.h index 720f9481f3..a55770c79f 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.h @@ -14,11 +14,11 @@ namespace AZ { - class ScriptUserDataSerializer + class RuntimeVariableSerializer : public BaseJsonSerializer { public: - AZ_RTTI(ScriptUserDataSerializer, "{7E5FC193-8CDB-4251-A68B-F337027381DF}", BaseJsonSerializer); + AZ_RTTI(RuntimeVariableSerializer, "{7E5FC193-8CDB-4251-A68B-F337027381DF}", BaseJsonSerializer); AZ_CLASS_ALLOCATOR_DECL; private: diff --git a/Gems/ScriptCanvas/Code/Source/SystemComponent.cpp b/Gems/ScriptCanvas/Code/Source/SystemComponent.cpp index 9efbb13639..0a82b8cf2a 100644 --- a/Gems/ScriptCanvas/Code/Source/SystemComponent.cpp +++ b/Gems/ScriptCanvas/Code/Source/SystemComponent.cpp @@ -23,7 +23,8 @@ #include #include #include -#include +#include +#include #include #include @@ -87,8 +88,13 @@ namespace ScriptCanvas if (AZ::JsonRegistrationContext* jsonContext = azrtti_cast(context)) { - jsonContext->Serializer() - ->HandlesType(); + jsonContext->Serializer() + ->HandlesType() + ; + + jsonContext->Serializer() + ->HandlesType() + ; } #if defined(SC_EXECUTION_TRACE_ENABLED) diff --git a/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake b/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake index 84ba39cc72..f1215dd580 100644 --- a/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake +++ b/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake @@ -539,8 +539,10 @@ set(FILES Include/ScriptCanvas/Profiler/Aggregator.cpp Include/ScriptCanvas/Profiler/DrillerEvents.h Include/ScriptCanvas/Profiler/DrillerEvents.cpp - Include/ScriptCanvas/Serialization/ScriptUserDataSerializer.h - Include/ScriptCanvas/Serialization/ScriptUserDataSerializer.cpp + Include/ScriptCanvas/Serialization/DatumSerializer.h + Include/ScriptCanvas/Serialization/DatumSerializer.cpp + Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.h + Include/ScriptCanvas/Serialization/RuntimeVariableSerializer.cpp Include/ScriptCanvas/Data/DataTrait.cpp Include/ScriptCanvas/Data/DataTrait.h Include/ScriptCanvas/Data/PropertyTraits.cpp From 6f4951234d458fafb07c2f7a3740c910cc98c498 Mon Sep 17 00:00:00 2001 From: abrmich Date: Wed, 11 Aug 2021 17:35:19 -0700 Subject: [PATCH 147/205] Fix for input not being reenabled after game mode Signed-off-by: abrmich --- Code/Editor/EditorViewportWidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index dd89d96dc3..cba82f7765 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -640,7 +640,7 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (m_renderViewport) { - m_renderViewport->GetControllerList()->SetEnabled(true); + m_renderViewport->SetInputProcessingEnabled(true); } break; From 8dd44075c85a98214dfa679e330de30cf6c5792f Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Wed, 11 Aug 2021 21:04:19 -0700 Subject: [PATCH 148/205] [redcode/crythread-2nd-pass] post merge include fixes Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Editor/GameEngine.h | 1 - Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp | 1 - .../Platform/Android/GridMate/Session/LANSession_Android.cpp | 1 + Code/Legacy/CryCommon/CryLibrary.h | 2 +- Code/Legacy/CryCommon/IFunctorBase.h | 2 -- Code/Legacy/CryCommon/IMaterial.h | 1 - Code/Legacy/CryCommon/smartptr.h | 1 - 7 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Code/Editor/GameEngine.h b/Code/Editor/GameEngine.h index 64fd20a9aa..4d183cc38e 100644 --- a/Code/Editor/GameEngine.h +++ b/Code/Editor/GameEngine.h @@ -20,7 +20,6 @@ #include "LogFile.h" #include "CryListenerSet.h" #include "Util/ModalWindowDismisser.h" -#include #endif class CStartupLogoDialog; diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp index f8f4711631..34514b8ef1 100644 --- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp +++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp @@ -9,7 +9,6 @@ #include "CryFile.h" #include "PerforceSourceControl.h" #include "PasswordDlg.h" -#include #include #include diff --git a/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp b/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp index 05fb56dfc1..3fa2a369a6 100644 --- a/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp +++ b/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp @@ -7,6 +7,7 @@ */ #include +#include namespace GridMate { diff --git a/Code/Legacy/CryCommon/CryLibrary.h b/Code/Legacy/CryCommon/CryLibrary.h index 787085af00..a034a2a04b 100644 --- a/Code/Legacy/CryCommon/CryLibrary.h +++ b/Code/Legacy/CryCommon/CryLibrary.h @@ -49,7 +49,7 @@ */ #include -#include +#include #include #define INJECT_ENVIRONMENT_FUNCTION "InjectEnvironment" diff --git a/Code/Legacy/CryCommon/IFunctorBase.h b/Code/Legacy/CryCommon/IFunctorBase.h index a64e811516..6fb3a5d981 100644 --- a/Code/Legacy/CryCommon/IFunctorBase.h +++ b/Code/Legacy/CryCommon/IFunctorBase.h @@ -14,8 +14,6 @@ #define CRYINCLUDE_CRYCOMMON_IFUNCTORBASE_H #pragma once -#include - #include // Base class for functor storage. diff --git a/Code/Legacy/CryCommon/IMaterial.h b/Code/Legacy/CryCommon/IMaterial.h index c484c10482..83f9140be7 100644 --- a/Code/Legacy/CryCommon/IMaterial.h +++ b/Code/Legacy/CryCommon/IMaterial.h @@ -37,7 +37,6 @@ struct IRenderMesh; #include #include #include -#include #ifdef MAX_SUB_MATERIALS // This checks that the values are in sync in the different files. diff --git a/Code/Legacy/CryCommon/smartptr.h b/Code/Legacy/CryCommon/smartptr.h index 0ff6a61b60..baf51d5030 100644 --- a/Code/Legacy/CryCommon/smartptr.h +++ b/Code/Legacy/CryCommon/smartptr.h @@ -13,7 +13,6 @@ #include #include -#include void CryFatalError(const char*, ...) PRINTF_PARAMS(1, 2); #if defined(APPLE) From 3fc0a197a0afa0206593aad40983e95f7917e13e Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Wed, 11 Aug 2021 21:32:02 -0700 Subject: [PATCH 149/205] [redcode/crythread-2nd-pass] removed re-implemented stubs of Windows synchapi.h functions and CrySimpleThread define in platform.h Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Legacy/CryCommon/Linux_Win32Wrapper.h | 55 ----------- Code/Legacy/CryCommon/WinBase.cpp | 104 --------------------- Code/Legacy/CryCommon/platform.h | 10 +- 3 files changed, 1 insertion(+), 168 deletions(-) diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 7b556b0f62..ffdf3fe998 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -413,67 +413,12 @@ inline void SetLastError(DWORD dwErrCode) { errno = dwErrCode; } ////////////////////////////////////////////////////////////////////////// extern threadID GetCurrentThreadId(); -////////////////////////////////////////////////////////////////////////// -extern HANDLE CreateEvent( - LPSECURITY_ATTRIBUTES lpEventAttributes, - BOOL bManualReset, - BOOL bInitialState, - LPCSTR lpName - ); - ////////////////////////////////////////////////////////////////////////// extern DWORD Sleep(DWORD dwMilliseconds); ////////////////////////////////////////////////////////////////////////// extern DWORD SleepEx(DWORD dwMilliseconds, BOOL bAlertable); -////////////////////////////////////////////////////////////////////////// -extern DWORD WaitForSingleObjectEx( - HANDLE hHandle, - DWORD dwMilliseconds, - BOOL bAlertable); - -////////////////////////////////////////////////////////////////////////// -extern DWORD WaitForMultipleObjectsEx( - DWORD nCount, - const HANDLE* lpHandles, - BOOL bWaitAll, - DWORD dwMilliseconds, - BOOL bAlertable); - -////////////////////////////////////////////////////////////////////////// -extern DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds); - -////////////////////////////////////////////////////////////////////////// -extern BOOL SetEvent(HANDLE hEvent); - -////////////////////////////////////////////////////////////////////////// -extern BOOL ResetEvent(HANDLE hEvent); - -////////////////////////////////////////////////////////////////////////// -extern HANDLE CreateMutex( - LPSECURITY_ATTRIBUTES lpMutexAttributes, - BOOL bInitialOwner, - LPCSTR lpName - ); - -////////////////////////////////////////////////////////////////////////// -extern BOOL ReleaseMutex(HANDLE hMutex); - -////////////////////////////////////////////////////////////////////////// -typedef DWORD (* PTHREAD_START_ROUTINE)(LPVOID lpThreadParameter); -typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; - -////////////////////////////////////////////////////////////////////////// -extern HANDLE CreateThread( - LPSECURITY_ATTRIBUTES lpThreadAttributes, - SIZE_T dwStackSize, - LPTHREAD_START_ROUTINE lpStartAddress, - LPVOID lpParameter, - DWORD dwCreationFlags, - LPDWORD lpThreadId - ); - extern BOOL GetComputerName(LPSTR lpBuffer, LPDWORD lpnSize); //required for CryOnline extern DWORD GetCurrentProcessId(void); diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 732920f890..ae646e9e1c 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -923,21 +923,6 @@ threadID GetCurrentThreadId() } #endif -////////////////////////////////////////////////////////////////////////// -HANDLE CreateEvent -( - LPSECURITY_ATTRIBUTES lpEventAttributes, - BOOL bManualReset, - BOOL bInitialState, - LPCSTR lpName -) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CreateEvent not implemented yet"); - return 0; -} - - ////////////////////////////////////////////////////////////////////////// DWORD Sleep(DWORD dwMilliseconds) { @@ -1003,95 +988,6 @@ DWORD SleepEx(DWORD dwMilliseconds, BOOL bAlertable) return 0; } -////////////////////////////////////////////////////////////////////////// -DWORD WaitForSingleObjectEx(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "WaitForSingleObjectEx not implemented yet"); - return 0; -} - -#if 0 -////////////////////////////////////////////////////////////////////////// -DWORD WaitForMultipleObjectsEx( - DWORD nCount, - const HANDLE* lpHandles, - BOOL bWaitAll, - DWORD dwMilliseconds, - BOOL bAlertable) -{ - //TODO: implement - return 0; -} -#endif - -////////////////////////////////////////////////////////////////////////// -DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "WaitForSingleObject not implemented yet"); - return 0; -} - -////////////////////////////////////////////////////////////////////////// -BOOL SetEvent(HANDLE hEvent) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "SetEvent not implemented yet"); - return TRUE; -} - -////////////////////////////////////////////////////////////////////////// -BOOL ResetEvent(HANDLE hEvent) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "ResetEvent not implemented yet"); - return TRUE; -} - -////////////////////////////////////////////////////////////////////////// -HANDLE CreateMutex -( - LPSECURITY_ATTRIBUTES lpMutexAttributes, - BOOL bInitialOwner, - LPCSTR lpName -) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CreateMutex not implemented yet"); - return 0; -} - -////////////////////////////////////////////////////////////////////////// -BOOL ReleaseMutex(HANDLE hMutex) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "ReleaseMutex not implemented yet"); - return TRUE; -} - -////////////////////////////////////////////////////////////////////////// - - -typedef DWORD (* PTHREAD_START_ROUTINE)(LPVOID lpThreadParameter); -typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; - -////////////////////////////////////////////////////////////////////////// -HANDLE CreateThread -( - LPSECURITY_ATTRIBUTES lpThreadAttributes, - SIZE_T dwStackSize, - LPTHREAD_START_ROUTINE lpStartAddress, - LPVOID lpParameter, - DWORD dwCreationFlags, - LPDWORD lpThreadId -) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CreateThread not implemented yet"); - return 0; -} - #if defined(LINUX) || defined(APPLE) BOOL GetComputerName(LPSTR lpBuffer, LPDWORD lpnSize) { diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 38c0ec7eb5..1b541a293e 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -142,14 +142,6 @@ #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(LINUX) || defined(APPLE) - #if !defined(_DEBUG) - #define SIMPLE_THREAD_STACK_SIZE_KB (256) - #else - #define SIMPLE_THREAD_STACK_SIZE_KB (256 * 4) - #endif -#else - #define SIMPLE_THREAD_STACK_SIZE_KB (32) #endif #include @@ -198,7 +190,7 @@ #elif defined(ANDROID) #include "AndroidSpecific.h" #elif defined(IOS) - #include "iOSSpecific.h" + #include "iOSSpecific.h" #endif #endif From 87922af706dc9c8cc3ee2188e5b8c2cd0a15d26b Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Thu, 12 Aug 2021 00:07:04 -0700 Subject: [PATCH 150/205] Jack remains in A-pose while it's animation is playing (#3038) * Removed a couple of legacy cgf/mtl and removed unused texture files. * Replaced Jack with the correct version (the previous version had different joint names than the animations used). * Increased the version in the actor group exporter to reprocess the actors due to PR #2957 Signed-off-by: Benjamin Jillich --- .../Objects/Characters/Jack/Jack.fbx | 4 +- .../Characters/Jack/Jack.fbx.assetinfo | 328 ++++++++++++++++++ .../Objects/Characters/Jack/Jack.mtl | 12 - .../Jack/attachments/arm_plates_lower_01.cgf | 3 - .../Jack/attachments/arm_plates_upper_01.cgf | 3 - .../Jack/attachments/back_pack_01.cgf | 3 - .../Jack/attachments/head_aerial_01.cgf | 3 - .../Jack/attachments/jack_matGroup.mtl | 14 - .../Jack/attachments/leg_plate_l_01.cgf | 3 - .../Jack/attachments/leg_plate_r_01.cgf | 3 - .../Characters/Jack/dummyPlane_mat_group.mtl | 8 - .../Characters/Jack/enemy_matGroup.mtl | 14 - .../Characters/Jack/enemy_runner_matGroup.mtl | 14 - .../Characters/Jack/enemy_tank_matGroup.mtl | 14 - .../Objects/Characters/Jack/jack_matGroup.mtl | 14 - .../Jack/textures/BrokenRobot_01_ddna.tif | 3 - .../BrokenRobot_01_ddna.tif.exportsettings | 1 - .../Jack/textures/BrokenRobot_White_diff.tif | 3 - .../BrokenRobot_White_diff.tif.exportsettings | 1 - .../Jack/textures/BrokenRobot_White_emis.tif | 3 - .../BrokenRobot_White_emis.tif.exportsettings | 1 - .../Jack/textures/BrokenRobot_black_diff.tif | 3 - .../Jack/textures/BrokenRobot_emis.tif | 3 - .../BrokenRobot_emis.tif.exportsettings | 1 - .../Jack/textures/BrokenRobot_green_diff.tif | 3 - .../BrokenRobot_green_diff.tif.exportsettings | 1 - .../Jack/textures/BrokenRobot_red_diff.tif | 3 - .../BrokenRobot_red_diff.tif.exportsettings | 1 - .../Jack/textures/BrokenRobot_spec.tif | 3 - .../BrokenRobot_spec.tif.exportsettings | 1 - .../Jack/textures/BrokenRobot_yellow_diff.tif | 3 - ...BrokenRobot_yellow_diff.tif.exportsettings | 1 - .../Jack/textures/BrokenRobot_yellow_emis.tif | 3 - ...BrokenRobot_yellow_emis.tif.exportsettings | 1 - .../Characters/Jack/textures/jack_ddna.tif | 3 - .../textures/jack_ddna.tif.exportsettings | 1 - .../Characters/Jack/textures/jack_diff.tif | 3 - .../textures/jack_diff.tif.exportsettings | 1 - .../Characters/Jack/textures/jack_emis.tif | 3 - .../textures/jack_emis.tif.exportsettings | 1 - .../Characters/Jack/textures/jack_spec.tif | 3 - .../textures/jack_spec.tif.exportsettings | 1 - .../Jack/textures/jack_spec_02_spec.tif | 3 - .../jack_spec_02_spec.tif.exportsettings | 1 - .../RCExt/Actor/ActorGroupExporter.cpp | 2 +- 45 files changed, 331 insertions(+), 170 deletions(-) create mode 100644 AutomatedTesting/Objects/Characters/Jack/Jack.fbx.assetinfo delete mode 100644 AutomatedTesting/Objects/Characters/Jack/Jack.mtl delete mode 100644 AutomatedTesting/Objects/Characters/Jack/attachments/arm_plates_lower_01.cgf delete mode 100644 AutomatedTesting/Objects/Characters/Jack/attachments/arm_plates_upper_01.cgf delete mode 100644 AutomatedTesting/Objects/Characters/Jack/attachments/back_pack_01.cgf delete mode 100644 AutomatedTesting/Objects/Characters/Jack/attachments/head_aerial_01.cgf delete mode 100644 AutomatedTesting/Objects/Characters/Jack/attachments/jack_matGroup.mtl delete mode 100644 AutomatedTesting/Objects/Characters/Jack/attachments/leg_plate_l_01.cgf delete mode 100644 AutomatedTesting/Objects/Characters/Jack/attachments/leg_plate_r_01.cgf delete mode 100644 AutomatedTesting/Objects/Characters/Jack/dummyPlane_mat_group.mtl delete mode 100644 AutomatedTesting/Objects/Characters/Jack/enemy_matGroup.mtl delete mode 100644 AutomatedTesting/Objects/Characters/Jack/enemy_runner_matGroup.mtl delete mode 100644 AutomatedTesting/Objects/Characters/Jack/enemy_tank_matGroup.mtl delete mode 100644 AutomatedTesting/Objects/Characters/Jack/jack_matGroup.mtl delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_01_ddna.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_01_ddna.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_diff.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_diff.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_emis.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_emis.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_black_diff.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_emis.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_emis.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_green_diff.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_green_diff.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_red_diff.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_red_diff.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_spec.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_spec.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_diff.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_diff.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_emis.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_emis.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_ddna.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_ddna.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_diff.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_diff.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_emis.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_emis.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_spec.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_spec.tif.exportsettings delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_spec_02_spec.tif delete mode 100644 AutomatedTesting/Objects/Characters/Jack/textures/jack_spec_02_spec.tif.exportsettings diff --git a/AutomatedTesting/Objects/Characters/Jack/Jack.fbx b/AutomatedTesting/Objects/Characters/Jack/Jack.fbx index bccd5cce24..2e55fdd1e7 100644 --- a/AutomatedTesting/Objects/Characters/Jack/Jack.fbx +++ b/AutomatedTesting/Objects/Characters/Jack/Jack.fbx @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ba9a2cd047a5ee696aaeed882869017a02fd4f5eeee91b6b2bfb830ad1e5ee15 -size 10927631 +oid sha256:c285cdf72ebe4c274f8d1fbab6ff558f9344d4fa62fb9d07cf11f7511ffaaac9 +size 2177072 diff --git a/AutomatedTesting/Objects/Characters/Jack/Jack.fbx.assetinfo b/AutomatedTesting/Objects/Characters/Jack/Jack.fbx.assetinfo new file mode 100644 index 0000000000..2de6d987d7 --- /dev/null +++ b/AutomatedTesting/Objects/Characters/Jack/Jack.fbx.assetinfo @@ -0,0 +1,328 @@ +{ + "values": [ + { + "$type": "ActorGroup", + "name": "Jack", + "selectedRootBone": "RootNode.jack_root", + "id": "{B7194F91-D8A1-5D5D-AC6D-DDEBC087D80D}", + "rules": { + "rules": [ + { + "$type": "MetaDataRule", + "metaData": "AdjustActor -actorID $(ACTORID) -name \"Jack\"\nActorSetCollisionMeshes -actorID $(ACTORID) -lod 0 -nodeList \"\"\nAdjustActor -actorID $(ACTORID) -nodesExcludedFromBounds \"\" -nodeAction \"select\"\nAdjustActor -actorID $(ACTORID) -nodeAction \"replace\" -attachmentNodes \"\"\nAdjustActor -actorID $(ACTORID) -motionExtractionNodeName \"jack_root\"\nAdjustActor -actorID $(ACTORID) -mirrorSetup \"\"\n" + } + ] + } + }, + { + "$type": "{5B03C8E6-8CEE-4DA0-A7FA-CD88689DD45B} MeshGroup", + "id": "{BF2CCF49-9BE0-5103-987A-84649A974991}", + "name": "Jack", + "NodeSelectionList": { + "unselectedNodes": [ + "RootNode", + "RootNode.jack_root", + "RootNode.jack_meshZUp", + "RootNode.jack_root.Bip01__pelvis", + "RootNode.jack_meshZUp.jack_meshZUp_1", + "RootNode.jack_meshZUp.jack_meshZUp_2", + "RootNode.jack_root.Bip01__pelvis.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg", + "RootNode.jack_root.Bip01__pelvis.r_upLeg", + "RootNode.jack_root.Bip01__pelvis.spine1", + "RootNode.jack_meshZUp.jack_meshZUp_1.Bitangent", + "RootNode.jack_meshZUp.jack_meshZUp_1.SkinWeight_", + "RootNode.jack_meshZUp.jack_meshZUp_1.transform", + "RootNode.jack_meshZUp.jack_meshZUp_1.Tangent", + "RootNode.jack_meshZUp.jack_meshZUp_1.map1", + "RootNode.jack_meshZUp.jack_meshZUp_1.jack", + "RootNode.jack_meshZUp.jack_meshZUp_2.Bitangent", + "RootNode.jack_meshZUp.jack_meshZUp_2.SkinWeight_", + "RootNode.jack_meshZUp.jack_meshZUp_2.transform", + "RootNode.jack_meshZUp.jack_meshZUp_2.Tangent", + "RootNode.jack_meshZUp.jack_meshZUp_2.map1", + "RootNode.jack_meshZUp.jack_meshZUp_2.jack", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_upLegRoll", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_upLegRoll", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg", + "RootNode.jack_root.Bip01__pelvis.spine1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_upLegRoll.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.l_ankle", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_upLegRoll.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.r_ankle", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.l_ankle.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.l_ankle.l_ball", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.r_ankle.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.r_ankle.r_ball", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.neck", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.l_ankle.l_ball.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.r_ankle.r_ball.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.neck.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.neck.head", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.neck.head.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_upArmRoll", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_upArmRoll", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_upArmRoll.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_loArmRoll", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_upArmRoll.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_loArmRoll", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_loArmRoll.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_handProp", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_loArmRoll.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_handProp", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.l_thumb2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.l_index2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.l_mid2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_handProp.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.r_thumb2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.r_index2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.r_mid2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_handProp.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.l_thumb2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.l_thumb2.l_thumb3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.l_index2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.l_index2.l_index3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.l_mid2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.l_mid2.l_mid3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.l_ring2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.l_pinky2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.r_thumb2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.r_thumb2.r_thumb3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.r_index2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.r_index2.r_index3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.r_mid2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.r_mid2.r_mid3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.r_ring2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.r_pinky2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.l_thumb2.l_thumb3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.l_index2.l_index3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.l_mid2.l_mid3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.l_ring2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.l_ring2.l_ring3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.l_pinky2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.l_pinky2.l_pinky3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.r_thumb2.r_thumb3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.r_index2.r_index3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.r_mid2.r_mid3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.r_ring2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.r_ring2.r_ring3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.r_pinky2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.r_pinky2.r_pinky3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.l_ring2.l_ring3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.l_pinky2.l_pinky3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.r_ring2.r_ring3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.r_pinky2.r_pinky3.transform" + ] + } + }, + { + "$type": "{07B356B7-3635-40B5-878A-FAC4EFD5AD86} MeshGroup", + "name": "Jack", + "nodeSelectionList": { + "selectedNodes": [ + "RootNode", + "RootNode.jack_root", + "RootNode.jack_meshZUp", + "RootNode.jack_root.Bip01__pelvis", + "RootNode.jack_meshZUp.jack_meshZUp_1", + "RootNode.jack_meshZUp.jack_meshZUp_2", + "RootNode.jack_root.Bip01__pelvis.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg", + "RootNode.jack_root.Bip01__pelvis.r_upLeg", + "RootNode.jack_root.Bip01__pelvis.spine1", + "RootNode.jack_meshZUp.jack_meshZUp_1.Bitangent", + "RootNode.jack_meshZUp.jack_meshZUp_1.SkinWeight_", + "RootNode.jack_meshZUp.jack_meshZUp_1.transform", + "RootNode.jack_meshZUp.jack_meshZUp_1.Tangent", + "RootNode.jack_meshZUp.jack_meshZUp_1.map1", + "RootNode.jack_meshZUp.jack_meshZUp_1.jack", + "RootNode.jack_meshZUp.jack_meshZUp_2.Bitangent", + "RootNode.jack_meshZUp.jack_meshZUp_2.SkinWeight_", + "RootNode.jack_meshZUp.jack_meshZUp_2.transform", + "RootNode.jack_meshZUp.jack_meshZUp_2.Tangent", + "RootNode.jack_meshZUp.jack_meshZUp_2.map1", + "RootNode.jack_meshZUp.jack_meshZUp_2.jack", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_upLegRoll", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_upLegRoll", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg", + "RootNode.jack_root.Bip01__pelvis.spine1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_upLegRoll.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.l_ankle", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_upLegRoll.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.r_ankle", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.l_ankle.transform", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.l_ankle.l_ball", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.r_ankle.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.r_ankle.r_ball", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.neck", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr", + "RootNode.jack_root.Bip01__pelvis.l_upLeg.l_loLeg.l_ankle.l_ball.transform", + "RootNode.jack_root.Bip01__pelvis.r_upLeg.r_loLeg.r_ankle.r_ball.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.neck.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.neck.head", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.neck.head.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_upArmRoll", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_upArmRoll", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_upArmRoll.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_loArmRoll", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_upArmRoll.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_loArmRoll", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_loArmRoll.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_handProp", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_loArmRoll.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_handProp", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.l_thumb2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.l_index2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.l_mid2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_handProp.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.r_thumb2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.r_index2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.r_mid2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_handProp.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.l_thumb2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.l_thumb2.l_thumb3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.l_index2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.l_index2.l_index3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.l_mid2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.l_mid2.l_mid3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.l_ring2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.l_pinky2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.r_thumb2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.r_thumb2.r_thumb3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.r_index2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.r_index2.r_index3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.r_mid2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.r_mid2.r_mid3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.r_ring2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.r_pinky2", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_thumb1.l_thumb2.l_thumb3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_index1.l_index2.l_index3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_mid1.l_mid2.l_mid3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.l_ring2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.l_ring2.l_ring3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.l_pinky2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.l_pinky2.l_pinky3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_thumb1.r_thumb2.r_thumb3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_index1.r_index2.r_index3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_mid1.r_mid2.r_mid3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.r_ring2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.r_ring2.r_ring3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.r_pinky2.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.r_pinky2.r_pinky3", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_ring1.l_ring2.l_ring3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.l_shldr.l_upArm.l_loArm.l_hand.l_metacarpal.l_pinky1.l_pinky2.l_pinky3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_ring1.r_ring2.r_ring3.transform", + "RootNode.jack_root.Bip01__pelvis.spine1.spine2.spine3.r_shldr.r_upArm.r_loArm.r_hand.r_metacarpal.r_pinky1.r_pinky2.r_pinky3.transform" + ] + }, + "rules": { + "rules": [ + { + "$type": "SkinRule" + }, + { + "$type": "MaterialRule" + } + ] + }, + "id": "{59B1DB76-5B27-5569-8DF6-55296FD0E5D8}" + } + ] +} \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/Jack.mtl b/AutomatedTesting/Objects/Characters/Jack/Jack.mtl deleted file mode 100644 index 2af23cc798..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/Jack.mtl +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/AutomatedTesting/Objects/Characters/Jack/attachments/arm_plates_lower_01.cgf b/AutomatedTesting/Objects/Characters/Jack/attachments/arm_plates_lower_01.cgf deleted file mode 100644 index a9530b6d1b..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/attachments/arm_plates_lower_01.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bb1c97394454a0a0c3b4aaf8380878aac3f7bedc9091ec920963932ad6ad2290 -size 30484 diff --git a/AutomatedTesting/Objects/Characters/Jack/attachments/arm_plates_upper_01.cgf b/AutomatedTesting/Objects/Characters/Jack/attachments/arm_plates_upper_01.cgf deleted file mode 100644 index 781ff1fe50..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/attachments/arm_plates_upper_01.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d090219fc20e7c1d9f0c187f976a7cb55e5b27b39e087aa8281ac794f314cb32 -size 22364 diff --git a/AutomatedTesting/Objects/Characters/Jack/attachments/back_pack_01.cgf b/AutomatedTesting/Objects/Characters/Jack/attachments/back_pack_01.cgf deleted file mode 100644 index 0e59a1393d..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/attachments/back_pack_01.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8fa78264ca46a2f201e24c3ba6a543e713bf9fd984df0a10f52b191d21077227 -size 106676 diff --git a/AutomatedTesting/Objects/Characters/Jack/attachments/head_aerial_01.cgf b/AutomatedTesting/Objects/Characters/Jack/attachments/head_aerial_01.cgf deleted file mode 100644 index cc54ba4b64..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/attachments/head_aerial_01.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ebf610eecec9a4da2d5c9260c48b81f6a04eaf7686d69850ad9f5d06fdbcf183 -size 12940 diff --git a/AutomatedTesting/Objects/Characters/Jack/attachments/jack_matGroup.mtl b/AutomatedTesting/Objects/Characters/Jack/attachments/jack_matGroup.mtl deleted file mode 100644 index ebade464ec..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/attachments/jack_matGroup.mtl +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/AutomatedTesting/Objects/Characters/Jack/attachments/leg_plate_l_01.cgf b/AutomatedTesting/Objects/Characters/Jack/attachments/leg_plate_l_01.cgf deleted file mode 100644 index 3ffabb1464..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/attachments/leg_plate_l_01.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:30afe8cf6e4aca846b07ef81747607afb47c0ff88283f363aca29ded9818c3db -size 8148 diff --git a/AutomatedTesting/Objects/Characters/Jack/attachments/leg_plate_r_01.cgf b/AutomatedTesting/Objects/Characters/Jack/attachments/leg_plate_r_01.cgf deleted file mode 100644 index e98083d030..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/attachments/leg_plate_r_01.cgf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dba25dd8b3840d01aefb69007919b07befc5365fff714493c87cf1eff644d5dc -size 8148 diff --git a/AutomatedTesting/Objects/Characters/Jack/dummyPlane_mat_group.mtl b/AutomatedTesting/Objects/Characters/Jack/dummyPlane_mat_group.mtl deleted file mode 100644 index 4545010b7e..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/dummyPlane_mat_group.mtl +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/AutomatedTesting/Objects/Characters/Jack/enemy_matGroup.mtl b/AutomatedTesting/Objects/Characters/Jack/enemy_matGroup.mtl deleted file mode 100644 index 523dac897f..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/enemy_matGroup.mtl +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/AutomatedTesting/Objects/Characters/Jack/enemy_runner_matGroup.mtl b/AutomatedTesting/Objects/Characters/Jack/enemy_runner_matGroup.mtl deleted file mode 100644 index 95c40eeb65..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/enemy_runner_matGroup.mtl +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/AutomatedTesting/Objects/Characters/Jack/enemy_tank_matGroup.mtl b/AutomatedTesting/Objects/Characters/Jack/enemy_tank_matGroup.mtl deleted file mode 100644 index e0f18e9f69..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/enemy_tank_matGroup.mtl +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/AutomatedTesting/Objects/Characters/Jack/jack_matGroup.mtl b/AutomatedTesting/Objects/Characters/Jack/jack_matGroup.mtl deleted file mode 100644 index 3927661f97..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/jack_matGroup.mtl +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_01_ddna.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_01_ddna.tif deleted file mode 100644 index 378e0ea6ed..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_01_ddna.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ca5c900fabf8b5c8c9313a0144886f4da3f812c82e8cffd652d9c61b9bb5b953 -size 4221960 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_01_ddna.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_01_ddna.tif.exportsettings deleted file mode 100644 index 10f3182ac9..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_01_ddna.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=NormalsWithSmoothness /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_diff.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_diff.tif deleted file mode 100644 index 5b4a3c3518..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_diff.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:80f40a78e4b21dd27f5ddf34337e7d0e2119b7cfa08f0eea38d4b1d63808821f -size 3178996 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_diff.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_diff.tif.exportsettings deleted file mode 100644 index 2d1dccbf99..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_diff.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_emis.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_emis.tif deleted file mode 100644 index a85ac62f6c..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_emis.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e5f5e327624e0f1fd35fac141019941b12ad0642c25853be9f7fd5b9b6f91bc5 -size 3168212 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_emis.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_emis.tif.exportsettings deleted file mode 100644 index 2d1dccbf99..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_White_emis.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_black_diff.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_black_diff.tif deleted file mode 100644 index c861056eea..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_black_diff.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:089e74ca9a41967038e16a9107099a73f8e93d39c487ff5bacdde18f418bf761 -size 3176732 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_emis.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_emis.tif deleted file mode 100644 index 6909252726..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_emis.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d45cd564d2b52575d1ad37b907a7d378871f05f6c9e5569ec73d7973d56599c9 -size 3167984 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_emis.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_emis.tif.exportsettings deleted file mode 100644 index 2d1dccbf99..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_emis.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_green_diff.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_green_diff.tif deleted file mode 100644 index 3254f98355..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_green_diff.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:83a872c07f7cbbcb868903429dd8d5a71e8c0b7b0e2cb16cb08b5cb26b02251c -size 3177492 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_green_diff.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_green_diff.tif.exportsettings deleted file mode 100644 index 2d1dccbf99..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_green_diff.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_red_diff.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_red_diff.tif deleted file mode 100644 index b00a8cd13b..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_red_diff.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:81c1bc9545a17232523fd97561013534221b3bf8927feefa52bdc757e294c2e2 -size 3179140 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_red_diff.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_red_diff.tif.exportsettings deleted file mode 100644 index 2d1dccbf99..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_red_diff.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_spec.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_spec.tif deleted file mode 100644 index 3e2fb9a003..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_spec.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:99f476a56205c80878be7472857a6430ce6dc40f2eb1558de4933a5b79fa2420 -size 814244 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_spec.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_spec.tif.exportsettings deleted file mode 100644 index aaaf14a9fe..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_spec.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Reflectance /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_diff.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_diff.tif deleted file mode 100644 index 2c44044576..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_diff.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:366959c8a31356669d47f58d07157171ed369b3e7549b3b65a8b8d153a1477a6 -size 3179956 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_diff.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_diff.tif.exportsettings deleted file mode 100644 index 2d1dccbf99..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_diff.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_emis.tif b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_emis.tif deleted file mode 100644 index 4dea311abb..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_emis.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e839924e03ba99459547df1cf5334de3bdad75b18e76176e430e343a979d9f05 -size 3168472 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_emis.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_emis.tif.exportsettings deleted file mode 100644 index 2d1dccbf99..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/BrokenRobot_yellow_emis.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_ddna.tif b/AutomatedTesting/Objects/Characters/Jack/textures/jack_ddna.tif deleted file mode 100644 index 57d61f505a..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_ddna.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:36f537bb5be89fccba1502e9e8f8dfffbf05ea8aa82ac439305e8c2502b01691 -size 16804800 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_ddna.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/jack_ddna.tif.exportsettings deleted file mode 100644 index a90d724812..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_ddna.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=NormalsWithSmoothness /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_diff.tif b/AutomatedTesting/Objects/Characters/Jack/textures/jack_diff.tif deleted file mode 100644 index a8f5db9a96..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_diff.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b0457cbbbe1fe7e52fdb9af7ee2bc32df96a453fe248738b35ffe0b8087a28c5 -size 12615988 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_diff.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/jack_diff.tif.exportsettings deleted file mode 100644 index f35416077f..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_diff.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /M=50,50,50,0,50,50 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_emis.tif b/AutomatedTesting/Objects/Characters/Jack/textures/jack_emis.tif deleted file mode 100644 index f5ee4b43b2..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_emis.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4ba741103d039bddf72d4834c92a5e069285e31b8be2e7f4e8103f9c5c81694f -size 3167864 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_emis.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/jack_emis.tif.exportsettings deleted file mode 100644 index 8177b5abe6..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_emis.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /M=50,50,0,50,50,50 /preset=Albedo /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec.tif b/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec.tif deleted file mode 100644 index 20fb2114c0..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4d7cb58f48e4df76214509fc01d5170fd38bc447d56af61f008c04a1653c2d20 -size 12614884 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec.tif.exportsettings deleted file mode 100644 index 7fbb585758..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /M=50,50,50,0,50,50 /preset=Reflectance /reduce=0 \ No newline at end of file diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec_02_spec.tif b/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec_02_spec.tif deleted file mode 100644 index 3334a5c39b..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec_02_spec.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:80a2c56bfcb8c98bf5a72ec9fdb5fcc6eae28ba1c3c26efad5c8a36e6105f1d0 -size 3173936 diff --git a/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec_02_spec.tif.exportsettings b/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec_02_spec.tif.exportsettings deleted file mode 100644 index aaaf14a9fe..0000000000 --- a/AutomatedTesting/Objects/Characters/Jack/textures/jack_spec_02_spec.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Reflectance /reduce=0 \ No newline at end of file diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp index a498ed2cb7..efd3d84aa0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp @@ -49,7 +49,7 @@ namespace EMotionFX if (serializeContext) { // Increasing the version number of the actor group exporter will make sure all actor products will be force re-generated. - serializeContext->Class()->Version(3); + serializeContext->Class()->Version(4); } } From f6e7760e85bc1fcd0cdfe3129315806ec14bb548 Mon Sep 17 00:00:00 2001 From: abrmich Date: Thu, 12 Aug 2021 00:06:13 -0700 Subject: [PATCH 151/205] Fix for checking environment variable existence Signed-off-by: abrmich --- .../Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp | 4 +++- .../Input/Devices/Mouse/InputDeviceMouse_Windows.cpp | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp index f3112ab89c..650dd14a1c 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp @@ -117,9 +117,11 @@ namespace AzFramework , m_hasFocus(false) , m_hasTextEntryStarted(false) { + static const char* s_keyboardCountEnvironmentVarName = "InputDeviceKeyboardInstanceCount"; + s_instanceCount = AZ::Environment::FindVariable(s_keyboardCountEnvironmentVarName); if (!s_instanceCount) { - s_instanceCount = AZ::Environment::CreateVariable("InputDeviceKeyboardInstanceCount", 1); + s_instanceCount = AZ::Environment::CreateVariable(s_keyboardCountEnvironmentVarName, 1); // Register for raw keyboard input RAWINPUTDEVICE rawInputDevice; diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Mouse/InputDeviceMouse_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Mouse/InputDeviceMouse_Windows.cpp index 464f49d620..d5d313eaab 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Mouse/InputDeviceMouse_Windows.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Mouse/InputDeviceMouse_Windows.cpp @@ -138,9 +138,11 @@ namespace AzFramework { memset(&m_lastClientRect, 0, sizeof(m_lastClientRect)); + static const char* s_mouseCountEnvironmentVarName = "InputDeviceMouseInstanceCount"; + s_instanceCount = AZ::Environment::FindVariable(s_mouseCountEnvironmentVarName); if (!s_instanceCount) { - s_instanceCount = AZ::Environment::CreateVariable("InputDeviceMouseInstanceCount", 1); + s_instanceCount = AZ::Environment::CreateVariable(s_mouseCountEnvironmentVarName, 1); // Register for raw mouse input RAWINPUTDEVICE rawInputDevice; From f4e8ecd35e07a9cebcaa9126e7f36f5ae1932a62 Mon Sep 17 00:00:00 2001 From: jonawals Date: Thu, 12 Aug 2021 10:21:33 +0100 Subject: [PATCH 152/205] TIAF script fixes (#3044) * Fix typo in MARS document key. Signed-off-by: John * Add diff support for commits on different branches. Signed-off-by: John * Restore archiving of historic data objects. Signed-off-by: John * Correctly handle commit diffs for PR builds. Signed-off-by: John * Comment out archiving of historic data objects. Signed-off-by: John * Fix python typo Signed-off-by: John * Remove comment pertaining to s3 bucket. Signed-off-by: John * Fix test selection efficiency for MARS. Signed-off-by: John --- scripts/build/TestImpactAnalysis/git_utils.py | 13 ++++++-- .../build/TestImpactAnalysis/mars_utils.py | 4 +-- scripts/build/TestImpactAnalysis/tiaf.py | 32 +++++++++++++------ .../tiaf_persistent_storage_s3.py | 6 ++++ 4 files changed, 41 insertions(+), 14 deletions(-) diff --git a/scripts/build/TestImpactAnalysis/git_utils.py b/scripts/build/TestImpactAnalysis/git_utils.py index 3561b337f3..ddc17ca146 100644 --- a/scripts/build/TestImpactAnalysis/git_utils.py +++ b/scripts/build/TestImpactAnalysis/git_utils.py @@ -21,12 +21,14 @@ class Repo: branch = self._repo.active_branch return branch.name - def create_diff_file(self, src_commit_hash: str, dst_commit_hash: str, output_path: pathlib.Path): + def create_diff_file(self, src_commit_hash: str, dst_commit_hash: str, output_path: pathlib.Path, multi_branch: bool): """ Attempts to create a diff from the src and dst commits and write to the specified output file. @param src_commit_hash: The hash for the source commit. @param dst_commit_hash: The hash for the destination commit. + @param multi_branch: The two commits are on different branches so view the changes on the + branch containing and up to dst_commit, starting at a common ancestor of both. @param output_path: The path to the file to write the diff to. """ @@ -39,8 +41,15 @@ class Repo: except EnvironmentError as e: raise RuntimeError(f"Could not create path for output file '{output_path}'") + args = ["git", "diff", "--name-status", f"--output={output_path}"] + if multi_branch: + args.append(f"{src_commit_hash}...{dst_commit_hash}") + else: + args.append(src_commit_hash) + args.append(dst_commit_hash) + # git diff will only write to the output file if both commit hashes are valid - subprocess.run(["git", "diff", "--name-status", f"--output={output_path}", src_commit_hash, dst_commit_hash]) + subprocess.run(args) if not output_path.is_file(): raise RuntimeError(f"Source commit '{src_commit_hash}' and/or destination commit '{dst_commit_hash}' are invalid") diff --git a/scripts/build/TestImpactAnalysis/mars_utils.py b/scripts/build/TestImpactAnalysis/mars_utils.py index 69374512a3..e2394ed6e1 100644 --- a/scripts/build/TestImpactAnalysis/mars_utils.py +++ b/scripts/build/TestImpactAnalysis/mars_utils.py @@ -15,7 +15,7 @@ logger = get_logger(__file__) MARS_JOB_KEY = "job" SRC_COMMIT_KEY = "src_commit" -DST_COMMIT_KEY = "src_commit" +DST_COMMIT_KEY = "dst_commit" COMMIT_DISTANCE_KEY = "commit_distance" SRC_BRANCH_KEY = "src_branch" DST_BRANCH_KEY = "dst_branch" @@ -318,7 +318,7 @@ def generate_mars_sequence(sequence_report: dict, mars_job: dict, change_list:di test_run_selection = {} test_run_selection[SELECTED_KEY] = generate_mars_test_run_selections(sequence_report[SELECTED_TEST_RUNS_KEY], sequence_report[SELECTED_TEST_RUN_REPORT_KEY], t0_timestamp) if sequence_report[SEQUENCE_TYPE_KEY] == IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY or sequence_report[SEQUENCE_TYPE_KEY] == SAFE_IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY: - total_test_runs = sequence_report[TOTAL_NUM_TEST_RUNS_KEY] + total_test_runs = sequence_report[TOTAL_NUM_TEST_RUNS_KEY] + len(sequence_report[DISCARDED_TEST_RUNS_KEY]) if total_test_runs > 0: test_run_selection[SELECTED_KEY][EFFICIENCY_KEY] = (1.0 - (test_run_selection[SELECTED_KEY][TOTAL_NUM_TEST_RUNS_KEY] / total_test_runs)) * 100 else: diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index 3c94c2b5f4..255a34759a 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -50,7 +50,7 @@ class TestImpact: logger.warning(f"Could not find TIAF binary at location {self._tiaf_bin}, TIAF will be turned off.") self._use_test_impact_analysis = False else: - logger.info(f"Runtime binary found at location {self._tiaf_bin}") + logger.info(f"Runtime binary found at location '{self._tiaf_bin}'") # Workspaces self._active_workspace = self._config["workspace"]["active"]["root"] @@ -71,21 +71,33 @@ class TestImpact: self._has_change_list = False self._change_list_path = None + self._src_commit = last_commit_hash # Check whether or not a previous commit hash exists (no hash is not a failure) - self._src_commit = last_commit_hash if self._src_commit: - if self._repo.is_descendent(self._src_commit, self._dst_commit) == False: - logger.info(f"Source commit '{self._src_commit}' and destination commit '{self._dst_commit}' are not related.") - return - self._commit_distance = self._repo.commit_distance(self._src_commit, self._dst_commit) - diff_path = pathlib.Path(pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{instance_id}.diff")) + if self._is_source_of_truth_branch: + # For branch builds, the dst commit must be descended from the src commit + if not self._repo.is_descendent(self._src_commit, self._dst_commit): + logger.error(f"Source commit '{self._src_commit}' and destination commit '{self._dst_commit}' must be related for branch builds.") + return + + # Calculate the distance (in commits) between the src and dst commits + self._commit_distance = self._repo.commit_distance(self._src_commit, self._dst_commit) + logger.info(f"The distance between '{self._src_commit}' and '{self._dst_commit}' commits is '{self._commit_distance}' commits.") + multi_branch = False + else: + # For pull request builds, the src and dst commits are on different branches so we need to ensure a common ancestor is used for the diff + multi_branch = True + try: - self._repo.create_diff_file(self._src_commit, self._dst_commit, diff_path) + # Attempt to generate a diff between the src and dst commits + logger.error(f"Source '{self._src_commit}' and destination '{self._dst_commit}' will be diff'd.") + diff_path = pathlib.Path(pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{instance_id}.diff")) + self._repo.create_diff_file(self._src_commit, self._dst_commit, diff_path, multi_branch) except RuntimeError as e: logger.error(e) return - + # A diff was generated, attempt to parse the diff and construct the change list logger.info(f"Generated diff between commits '{self._src_commit}' and '{self._dst_commit}': '{diff_path}'.") with open(diff_path, "r") as diff_data: @@ -189,7 +201,7 @@ class TestImpact: self._is_source_of_truth_branch = True self._source_of_truth_branch = self._src_branch else: - # PR builds use their destination as the source of truth and never update the coverage data for the source of truth + # Pull request builds use their destination as the source of truth and never update the coverage data for the source of truth self._is_source_of_truth_branch = False self._source_of_truth_branch = self._dst_branch diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py index 09b4df0564..24101c7cba 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py @@ -48,6 +48,12 @@ class PersistentStorageS3(PersistentStorage): for object in self._bucket.objects.filter(Prefix=self._historic_data_key): logger.info(f"Historic data found for branch '{branch}'.") + # Archive the existing object with the name of the existing last commit hash + #archive_key = f"{self._dir}/archive/{self._last_commit_hash}.{object_extension}" + #logger.info(f"Archiving existing historic data to '{archive_key}' in bucket '{self._bucket.name}'...") + #self._bucket.copy({"Bucket": self._bucket.name, "Key": self._historic_data_key}, archive_key) + #logger.info(f"Archiving complete.") + # Decode the historic data object into raw bytes logger.info(f"Attempting to decode historic data object...") response = object.get() From 268a7f547e25a38cf6086659c912145d5e36620f Mon Sep 17 00:00:00 2001 From: John Date: Thu, 12 Aug 2021 11:19:27 +0100 Subject: [PATCH 153/205] Add additional logging to s3 storage. Signed-off-by: John --- scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py index 18ea25091f..ec646ee484 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py @@ -49,6 +49,7 @@ class PersistentStorage(ABC): try: historic_data = json.loads(historic_data_json) self._last_commit_hash = historic_data["last_commit_hash"] + logger.info(f"Last commit hash '{self._last_commit_hash}' found.") # Create the active workspace directory where the coverage data file will be placed and unpack the coverage data so # it is accessible by the runtime @@ -105,7 +106,10 @@ class PersistentStorage(ABC): historic_data_json = self._pack_historic_data(last_commit_hash) if historic_data_json: + logger.info(f"Attempting to store historic data with new last commit hash '{self._last_commit_hash}'...") self._store_historic_data(historic_data_json) + logger.info("The historic data was successfully stored.") + else: logger.info("The historic data could not be successfully stored.") From 9601db55aa96a9185943d81e49a43135bf557e32 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 12 Aug 2021 11:19:48 +0100 Subject: [PATCH 154/205] Add sanity checking to last commit hash. Signed-off-by: John --- scripts/build/TestImpactAnalysis/tiaf.py | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index 255a34759a..a06a01cf38 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -61,17 +61,13 @@ class TestImpact: logger.error(f"The config does not contain the key {str(e)}.") return - def _attempt_to_generate_change_list(self, last_commit_hash, instance_id: str): + def _attempt_to_generate_change_list(self): """ Attempts to determine the change list bewteen now and the last tiaf run (if any). - - @param last_commit_hash: The commit hash of the last TIAF run. - @param instance_id: The unique id to derive the change list file name from. """ self._has_change_list = False self._change_list_path = None - self._src_commit = last_commit_hash # Check whether or not a previous commit hash exists (no hash is not a failure) if self._src_commit: @@ -92,7 +88,7 @@ class TestImpact: try: # Attempt to generate a diff between the src and dst commits logger.error(f"Source '{self._src_commit}' and destination '{self._dst_commit}' will be diff'd.") - diff_path = pathlib.Path(pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{instance_id}.diff")) + diff_path = pathlib.Path(pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{self._instance_id}.diff")) self._repo.create_diff_file(self._src_commit, self._dst_commit, diff_path, multi_branch) except RuntimeError as e: logger.error(e) @@ -124,7 +120,7 @@ class TestImpact: # Serialize the change list to the JSON format the test impact analysis runtime expects change_list_json = json.dumps(self._change_list, indent = 4) - change_list_path = pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{instance_id}.json") + change_list_path = pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{self._instance_id}.json") f = open(change_list_path, "w") f.write(change_list_json) f.close() @@ -215,7 +211,7 @@ class TestImpact: self._commit_distance = None # Generate a unique ID to be used as part of the file name for required runtime dynamic artifacts. - instance_id = uuid.uuid4().hex + self._instance_id = uuid.uuid4().hex if self._use_test_impact_analysis: logger.info("Test impact analysis is enabled.") @@ -232,7 +228,14 @@ class TestImpact: if persistent_storage: if persistent_storage.has_historic_data: logger.info("Historic data found.") - self._attempt_to_generate_change_list(persistent_storage.last_commit_hash, instance_id) + self._src_commit = persistent_storage.last_commit_hash + + # Perform some basic sanity checks on the commit hashes to ensure confidence in the integrity of of the environment + if self._src_commit == self._dst_commit: + logger.error(f"Source commit '{self._src_commit}' and destination commit '{self._dst_commit}', implying the integrity of the historic data is compromised.") + persistent_storage = None + else: + self._attempt_to_generate_change_list(self._instance_id) else: logger.info("No historic data found.") @@ -283,7 +286,7 @@ class TestImpact: logger.info(f"Test failure policy is set to '{test_failure_policy}'.") # Sequence report - report_file = pathlib.PurePath(self._temp_workspace).joinpath(f"report.{instance_id}.json") + report_file = pathlib.PurePath(self._temp_workspace).joinpath(f"report.{self._instance_id}.json") args.append(f"--report={report_file}") logger.info(f"Sequence report file is set to '{report_file}'.") From 199273b880a9266af7a5eeb1e93c76beb8bbf2c9 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 12 Aug 2021 12:00:51 +0100 Subject: [PATCH 155/205] Remove positional argument from change list generaiton. Signed-off-by: John --- scripts/build/TestImpactAnalysis/tiaf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index a06a01cf38..11ca24f830 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -235,7 +235,7 @@ class TestImpact: logger.error(f"Source commit '{self._src_commit}' and destination commit '{self._dst_commit}', implying the integrity of the historic data is compromised.") persistent_storage = None else: - self._attempt_to_generate_change_list(self._instance_id) + self._attempt_to_generate_change_list() else: logger.info("No historic data found.") From 83e56b6ab5d473ba0a912957d7f0a6b42bb644c3 Mon Sep 17 00:00:00 2001 From: AMZN-Alexandre Corcia Aguilera <82398284+aaguilea@users.noreply.github.com> Date: Thu, 12 Aug 2021 15:06:16 +0100 Subject: [PATCH 156/205] Remove new camera flag functions and legacy code paths (#3071) Signed-off-by: aaguilea --- .../EditorPreferencesPageViewportMovement.cpp | 50 +++------- Code/Editor/EditorViewportSettings.h | 4 - Code/Editor/EditorViewportWidget.cpp | 8 -- Code/Editor/GotoPositionDlg.cpp | 22 +---- .../SandboxIntegration.cpp | 98 +++++++------------ Code/Editor/ViewportTitleDlg.cpp | 17 +--- 6 files changed, 56 insertions(+), 143 deletions(-) diff --git a/Code/Editor/EditorPreferencesPageViewportMovement.cpp b/Code/Editor/EditorPreferencesPageViewportMovement.cpp index 1efe64488d..988b4954d1 100644 --- a/Code/Editor/EditorPreferencesPageViewportMovement.cpp +++ b/Code/Editor/EditorPreferencesPageViewportMovement.cpp @@ -68,45 +68,21 @@ QIcon& CEditorPreferencesPage_ViewportMovement::GetIcon() void CEditorPreferencesPage_ViewportMovement::OnApply() { - if (SandboxEditor::UsingNewCameraSystem()) - { - SandboxEditor::SetCameraTranslateSpeed(m_cameraMovementSettings.m_moveSpeed); - SandboxEditor::SetCameraRotateSpeed(m_cameraMovementSettings.m_rotateSpeed); - SandboxEditor::SetCameraBoostMultiplier(m_cameraMovementSettings.m_fastMoveSpeed); - SandboxEditor::SetCameraScrollSpeed(m_cameraMovementSettings.m_wheelZoomSpeed); - SandboxEditor::SetCameraOrbitYawRotationInverted(m_cameraMovementSettings.m_invertYRotation); - SandboxEditor::SetCameraPanInvertedX(m_cameraMovementSettings.m_invertPan); - SandboxEditor::SetCameraPanInvertedY(m_cameraMovementSettings.m_invertPan); - } - else - { - gSettings.cameraMoveSpeed = m_cameraMovementSettings.m_moveSpeed; - gSettings.cameraRotateSpeed = m_cameraMovementSettings.m_rotateSpeed; - gSettings.cameraFastMoveSpeed = m_cameraMovementSettings.m_fastMoveSpeed; - gSettings.wheelZoomSpeed = m_cameraMovementSettings.m_wheelZoomSpeed; - gSettings.invertYRotation = m_cameraMovementSettings.m_invertYRotation; - gSettings.invertPan = m_cameraMovementSettings.m_invertPan; - } + SandboxEditor::SetCameraTranslateSpeed(m_cameraMovementSettings.m_moveSpeed); + SandboxEditor::SetCameraRotateSpeed(m_cameraMovementSettings.m_rotateSpeed); + SandboxEditor::SetCameraBoostMultiplier(m_cameraMovementSettings.m_fastMoveSpeed); + SandboxEditor::SetCameraScrollSpeed(m_cameraMovementSettings.m_wheelZoomSpeed); + SandboxEditor::SetCameraOrbitYawRotationInverted(m_cameraMovementSettings.m_invertYRotation); + SandboxEditor::SetCameraPanInvertedX(m_cameraMovementSettings.m_invertPan); + SandboxEditor::SetCameraPanInvertedY(m_cameraMovementSettings.m_invertPan); } void CEditorPreferencesPage_ViewportMovement::InitializeSettings() { - if (SandboxEditor::UsingNewCameraSystem()) - { - m_cameraMovementSettings.m_moveSpeed = SandboxEditor::CameraTranslateSpeed(); - m_cameraMovementSettings.m_rotateSpeed = SandboxEditor::CameraRotateSpeed(); - m_cameraMovementSettings.m_fastMoveSpeed = SandboxEditor::CameraBoostMultiplier(); - m_cameraMovementSettings.m_wheelZoomSpeed = SandboxEditor::CameraScrollSpeed(); - m_cameraMovementSettings.m_invertYRotation = SandboxEditor::CameraOrbitYawRotationInverted(); - m_cameraMovementSettings.m_invertPan = SandboxEditor::CameraPanInvertedX() && SandboxEditor::CameraPanInvertedY(); - } - else - { - m_cameraMovementSettings.m_moveSpeed = gSettings.cameraMoveSpeed; - m_cameraMovementSettings.m_rotateSpeed = gSettings.cameraRotateSpeed; - m_cameraMovementSettings.m_fastMoveSpeed = gSettings.cameraFastMoveSpeed; - m_cameraMovementSettings.m_wheelZoomSpeed = gSettings.wheelZoomSpeed; - m_cameraMovementSettings.m_invertYRotation = gSettings.invertYRotation; - m_cameraMovementSettings.m_invertPan = gSettings.invertPan; - } + m_cameraMovementSettings.m_moveSpeed = SandboxEditor::CameraTranslateSpeed(); + m_cameraMovementSettings.m_rotateSpeed = SandboxEditor::CameraRotateSpeed(); + m_cameraMovementSettings.m_fastMoveSpeed = SandboxEditor::CameraBoostMultiplier(); + m_cameraMovementSettings.m_wheelZoomSpeed = SandboxEditor::CameraScrollSpeed(); + m_cameraMovementSettings.m_invertYRotation = SandboxEditor::CameraOrbitYawRotationInverted(); + m_cameraMovementSettings.m_invertPan = SandboxEditor::CameraPanInvertedX() && SandboxEditor::CameraPanInvertedY(); } diff --git a/Code/Editor/EditorViewportSettings.h b/Code/Editor/EditorViewportSettings.h index 1898cf642a..b1488c5528 100644 --- a/Code/Editor/EditorViewportSettings.h +++ b/Code/Editor/EditorViewportSettings.h @@ -118,8 +118,4 @@ namespace SandboxEditor SANDBOX_API AzFramework::InputChannelId CameraOrbitPanChannelId(); SANDBOX_API void SetCameraOrbitPanChannelId(AZStd::string_view cameraOrbitPanId); - - //! Return if the new editor camera system is enabled or not. - //! @note This is implemented in EditorViewportWidget.cpp - SANDBOX_API bool UsingNewCameraSystem(); } // namespace SandboxEditor diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 2ca3739033..96a7e77ecd 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -106,14 +106,6 @@ AZ_CVAR( bool, ed_visibility_logTiming, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Output the timing of the new IVisibilitySystem query"); AZ_CVAR(bool, ed_showCursorCameraLook, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Show the cursor when using free look with the new camera system"); -namespace SandboxEditor -{ - bool UsingNewCameraSystem() - { - return true; - } -} // namespace SandboxEditor - EditorViewportWidget* EditorViewportWidget::m_pPrimaryViewport = nullptr; #if AZ_TRAIT_OS_PLATFORM_APPLE diff --git a/Code/Editor/GotoPositionDlg.cpp b/Code/Editor/GotoPositionDlg.cpp index c1e64ed1a9..aec5f03fbd 100644 --- a/Code/Editor/GotoPositionDlg.cpp +++ b/Code/Editor/GotoPositionDlg.cpp @@ -108,24 +108,12 @@ void GotoPositionDialog::OnUpdateNumbers() void GotoPositionDialog::accept() { - if (SandboxEditor::UsingNewCameraSystem()) - { - SandboxEditor::InterpolateDefaultViewportCameraToTransform( - AZ::Vector3( - aznumeric_cast(m_ui->m_dymX->value()), aznumeric_cast(m_ui->m_dymY->value()), - aznumeric_cast(m_ui->m_dymZ->value())), - AZ::DegToRad(aznumeric_cast(m_ui->m_dymAnglePitch->value())), - AZ::DegToRad(aznumeric_cast(m_ui->m_dymAngleYaw->value()))); - } - else - { - SandboxEditor::SetDefaultViewportCameraPosition(AZ::Vector3( + SandboxEditor::InterpolateDefaultViewportCameraToTransform( + AZ::Vector3( aznumeric_cast(m_ui->m_dymX->value()), aznumeric_cast(m_ui->m_dymY->value()), - aznumeric_cast(m_ui->m_dymZ->value()))); - SandboxEditor::SetDefaultViewportCameraRotation( - AZ::DegToRad(aznumeric_cast(m_ui->m_dymAnglePitch->value())), - AZ::DegToRad(aznumeric_cast(m_ui->m_dymAngleYaw->value()))); - } + aznumeric_cast(m_ui->m_dymZ->value())), + AZ::DegToRad(aznumeric_cast(m_ui->m_dymAnglePitch->value())), + AZ::DegToRad(aznumeric_cast(m_ui->m_dymAngleYaw->value()))); QDialog::accept(); } diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 072625936b..2ed2a30f08 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -1704,74 +1704,44 @@ void SandboxIntegrationManager::GoToEntitiesInViewports(const AzToolsFramework:: return; } - if (SandboxEditor::UsingNewCameraSystem()) + const AZ::Aabb aabb = AZStd::accumulate( + AZStd::begin(entityIds), AZStd::end(entityIds), AZ::Aabb::CreateNull(), [](AZ::Aabb acc, const AZ::EntityId entityId) { + const AZ::Aabb aabb = AzFramework::CalculateEntityWorldBoundsUnion(AzToolsFramework::GetEntityById(entityId)); + acc.AddAabb(aabb); + return acc; + }); + + float radius; + AZ::Vector3 center; + aabb.GetAsSphere(center, radius); + + // minimum center size is 40cm + const float minSelectionRadius = 0.4f; + const float selectionSize = AZ::GetMax(minSelectionRadius, radius); + + auto viewportContextManager = AZ::Interface::Get(); + + const int viewCount = GetIEditor()->GetViewManager()->GetViewCount(); // legacy call + for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) { - const AZ::Aabb aabb = AZStd::accumulate( - AZStd::begin(entityIds), AZStd::end(entityIds), AZ::Aabb::CreateNull(), [](AZ::Aabb acc, const AZ::EntityId entityId) { - const AZ::Aabb aabb = AzFramework::CalculateEntityWorldBoundsUnion(AzToolsFramework::GetEntityById(entityId)); - acc.AddAabb(aabb); - return acc; - }); - - float radius; - AZ::Vector3 center; - aabb.GetAsSphere(center, radius); - - // minimum center size is 40cm - const float minSelectionRadius = 0.4f; - const float selectionSize = AZ::GetMax(minSelectionRadius, radius); - - auto viewportContextManager = AZ::Interface::Get(); - - const int viewCount = GetIEditor()->GetViewManager()->GetViewCount(); // legacy call - for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) + if (auto viewportContext = viewportContextManager->GetViewportContextById(viewIndex)) { - if (auto viewportContext = viewportContextManager->GetViewportContextById(viewIndex)) - { - const AZ::Transform cameraTransform = viewportContext->GetCameraTransform(); - const AZ::Vector3 forward = (center - cameraTransform.GetTranslation()).GetNormalized(); + const AZ::Transform cameraTransform = viewportContext->GetCameraTransform(); + const AZ::Vector3 forward = (center - cameraTransform.GetTranslation()).GetNormalized(); - // move camera 25% further back than required - const float centerScale = 1.25f; - // compute new camera transform - const float fov = AzFramework::RetrieveFov(viewportContext->GetCameraProjectionMatrix()); - const float fovScale = (1.0f / AZStd::tan(fov * 0.5f)); - const float distanceToLookAt = selectionSize * fovScale * centerScale; - const AZ::Transform nextCameraTransform = - AZ::Transform::CreateLookAt(aabb.GetCenter() - (forward * distanceToLookAt), aabb.GetCenter()); + // move camera 25% further back than required + const float centerScale = 1.25f; + // compute new camera transform + const float fov = AzFramework::RetrieveFov(viewportContext->GetCameraProjectionMatrix()); + const float fovScale = (1.0f / AZStd::tan(fov * 0.5f)); + const float distanceToLookAt = selectionSize * fovScale * centerScale; + const AZ::Transform nextCameraTransform = + AZ::Transform::CreateLookAt(aabb.GetCenter() - (forward * distanceToLookAt), aabb.GetCenter()); - AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( - viewportContext->GetId(), - &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, nextCameraTransform, - distanceToLookAt); - } - } - } - else - { - AABB selectionBounds; - selectionBounds.Reset(); - bool entitiesAvailableForGoTo = false; - - for (const AZ::EntityId& entityId : entityIds) - { - if (CollectEntityBoundingBoxesForZoom(entityId, selectionBounds)) - { - entitiesAvailableForGoTo = true; - } - } - - if (entitiesAvailableForGoTo) - { - int numViews = GetIEditor()->GetViewManager()->GetViewCount(); - for (int viewIndex = 0; viewIndex < numViews; ++viewIndex) - { - CViewport* viewport = GetIEditor()->GetViewManager()->GetView(viewIndex); - if (viewport) - { - viewport->CenterOnAABB(selectionBounds); - } - } + AtomToolsFramework::ModularViewportCameraControllerRequestBus::Event( + viewportContext->GetId(), + &AtomToolsFramework::ModularViewportCameraControllerRequestBus::Events::InterpolateToTransform, nextCameraTransform, + distanceToLookAt); } } } diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp index 530e11b01b..f5515b9c18 100644 --- a/Code/Editor/ViewportTitleDlg.cpp +++ b/Code/Editor/ViewportTitleDlg.cpp @@ -172,8 +172,7 @@ void CViewportTitleDlg::SetupCameraDropdownMenu() cameraSpeedActionWidget->setDefaultWidget(cameraSpeedContainer); // Save off the move speed here since setting up the combo box can cause it to update values in the background. - const float cameraMoveSpeed = SandboxEditor::UsingNewCameraSystem() ? SandboxEditor::CameraTranslateSpeed() : gSettings.cameraMoveSpeed; - + const float cameraMoveSpeed = SandboxEditor::CameraTranslateSpeed(); // Populate the presets in the ComboBox for (float presetValue : m_speedPresetValues) { @@ -947,21 +946,13 @@ void CViewportTitleDlg::OnSpeedComboBoxEnter() void CViewportTitleDlg::OnUpdateMoveSpeedText(const QString& text) { - if (SandboxEditor::UsingNewCameraSystem()) - { - SandboxEditor::SetCameraTranslateSpeed(aznumeric_cast(Round(text.toDouble(), m_speedStep))); - } - else - { - gSettings.cameraMoveSpeed = aznumeric_cast(Round(text.toDouble(), m_speedStep)); - } + SandboxEditor::SetCameraTranslateSpeed(aznumeric_cast(Round(text.toDouble(), m_speedStep))); } void CViewportTitleDlg::CheckForCameraSpeedUpdate() { - if (const float currentCameraMoveSpeed = - SandboxEditor::UsingNewCameraSystem() ? SandboxEditor::CameraTranslateSpeed() : gSettings.cameraMoveSpeed; - currentCameraMoveSpeed != m_prevMoveSpeed && !m_cameraSpeed->lineEdit()->hasFocus()) + const float currentCameraMoveSpeed = SandboxEditor::CameraTranslateSpeed(); + if (currentCameraMoveSpeed != m_prevMoveSpeed && !m_cameraSpeed->lineEdit()->hasFocus()) { m_prevMoveSpeed = currentCameraMoveSpeed; SetSpeedComboBox(currentCameraMoveSpeed); From 288d366c2ac6fdf5a2df626d4ab37c42b41ff010 Mon Sep 17 00:00:00 2001 From: AMZN-tpeng <82184807+AMZN-tpeng@users.noreply.github.com> Date: Thu, 12 Aug 2021 09:04:38 -0700 Subject: [PATCH 157/205] =?UTF-8?q?[Atom][RHI][Vulkan][Android]=20-=20Add?= =?UTF-8?q?=202D=20image=20array=20null=20descriptors=20fo=E2=80=A6=20(#27?= =?UTF-8?q?22)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [Atom][RHI][Vulkan][Android] - Add 2D image array null descriptors for devices without the null descriptor extension. Signed-off-by: Peng * [Atom][RHI][Vulkan][Android] - Fix spacing. Signed-off-by: Peng --- .../Code/Source/RHI/NullDescriptorManager.cpp | 46 ++++++++++++++++++- .../Code/Source/RHI/NullDescriptorManager.h | 5 ++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp index 1b3a533f34..316144f323 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.cpp @@ -117,6 +117,35 @@ namespace AZ m_imageNullDescriptor.m_images[static_cast(ImageTypes::MultiSampleReadOnly2D)].m_sampleCountFlag = VK_SAMPLE_COUNT_4_BIT; m_imageNullDescriptor.m_images[static_cast(ImageTypes::MultiSampleReadOnly2D)].m_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)] = {}; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)].m_name = "NULL_DESCRIPTOR_GENERAL_ARRAY_2D"; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)].m_sampleCountFlag = VK_SAMPLE_COUNT_1_BIT; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)].m_format = VK_FORMAT_R8G8B8A8_SRGB; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)].m_usageFlagBits =VkImageUsageFlagBits(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)].m_arrayLayers = 1; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)].m_imageCreateFlagBits = VkImageCreateFlagBits(0); + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)].m_layout = VK_IMAGE_LAYOUT_GENERAL; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralArray2D)].m_dimension = imageDimension; + + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)] = m_imageNullDescriptor.m_images[static_cast(NullDescriptorManager::ImageTypes::GeneralArray2D)]; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)].m_name = "NULL_DESCRIPTOR_READONLY_ARRAY_2D"; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)].m_sampleCountFlag = VK_SAMPLE_COUNT_1_BIT; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)].m_format = VK_FORMAT_R8G8B8A8_SRGB; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)].m_usageFlagBits = VkImageUsageFlagBits(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)].m_arrayLayers = 1; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)].m_imageCreateFlagBits = VkImageCreateFlagBits(0); + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)].m_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::ReadOnlyArray2D)].m_dimension = imageDimension; + + m_imageNullDescriptor.m_images[static_cast(ImageTypes::StorageArray2D)] = m_imageNullDescriptor.m_images[static_cast(NullDescriptorManager::ImageTypes::General2D)]; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::StorageArray2D)].m_name = "NULL_DESCRIPTOR_STORAGE_ARRAY_2D"; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::StorageArray2D)].m_sampleCountFlag = VK_SAMPLE_COUNT_1_BIT; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::StorageArray2D)].m_format = VK_FORMAT_R32G32B32A32_UINT; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::StorageArray2D)].m_usageFlagBits = VkImageUsageFlagBits(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT); + m_imageNullDescriptor.m_images[static_cast(ImageTypes::StorageArray2D)].m_arrayLayers = 1; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::StorageArray2D)].m_layout = VK_IMAGE_LAYOUT_GENERAL; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::StorageArray2D)].m_dimension = 256; + m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralCube)] = m_imageNullDescriptor.m_images[static_cast(NullDescriptorManager::ImageTypes::General2D)]; m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralCube)].m_name = "NULL_DESCRIPTOR_GENERAL_CUBE"; m_imageNullDescriptor.m_images[static_cast(ImageTypes::GeneralCube)].m_arrayLayers = 6; @@ -243,6 +272,10 @@ namespace AZ { imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_3D; } + else if (imageIndex >= static_cast(ImageTypes::GeneralArray2D) && imageIndex <= static_cast(ImageTypes::StorageArray2D)) + { + imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; + } result = vkCreateImageView(device.GetNativeDevice(), &imageViewCreateInfo, nullptr, &m_imageNullDescriptor.m_images[imageIndex].m_view); RETURN_RESULT_IF_UNSUCCESSFUL(ConvertResult(result)); @@ -366,7 +399,7 @@ namespace AZ VkDescriptorImageInfo NullDescriptorManager::GetDescriptorImageInfo(RHI::ShaderInputImageType imageType, bool storageImage) { - if (imageType == RHI::ShaderInputImageType::Image2D || imageType == RHI::ShaderInputImageType::Image2DArray) + if (imageType == RHI::ShaderInputImageType::Image2D) { if (storageImage) { @@ -377,6 +410,17 @@ namespace AZ return GetImage(ImageTypes::ReadOnly2D); } } + else if (imageType == RHI::ShaderInputImageType::Image2DArray) + { + if (storageImage) + { + return GetImage(ImageTypes::StorageArray2D); + } + else + { + return GetImage(ImageTypes::ReadOnlyArray2D); + } + } else if (imageType == RHI::ShaderInputImageType::Image2DMultisample) { if (storageImage) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.h b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.h index 52d12b97c4..e5c4dab22e 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.h +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/NullDescriptorManager.h @@ -30,6 +30,11 @@ namespace AZ MultiSampleGeneral2D, MultiSampleReadOnly2D, + // 2d image arrays + GeneralArray2D, + ReadOnlyArray2D, + StorageArray2D, + // cube images GeneralCube, ReadOnlyCube, From b5828e327ddf9bbec62c53a990e89b86173c6293 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 12 Aug 2021 11:15:55 -0500 Subject: [PATCH 158/205] Moved custom tree view dragging logic from Entity Outliner to common class so it could be re-used for the UI Editor tree view. Signed-off-by: Chris Galvan --- .../Components/Widgets/TreeView.cpp | 105 ++++++++++++++++++ .../Components/Widgets/TreeView.h | 45 ++++++++ .../UI/Outliner/EntityOutlinerTreeView.cpp | 84 +------------- .../UI/Outliner/EntityOutlinerTreeView.hxx | 9 +- Gems/LyShine/Code/Editor/HierarchyWidget.cpp | 4 +- Gems/LyShine/Code/Editor/HierarchyWidget.h | 4 +- 6 files changed, 165 insertions(+), 86 deletions(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.cpp index 3d0b78ece7..89639ff1d7 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.cpp @@ -8,6 +8,7 @@ #include +#include #include #include #include @@ -252,5 +253,109 @@ namespace AzQtComponents return qobject_cast(widget) && !qobject_cast(widget); } + StyledTreeView::StyledTreeView(QWidget* parent) + : QTreeView(parent) + { + } + + void StyledTreeView::startDrag(Qt::DropActions supportedActions) + { + if (!selectionModel()->selectedIndexes().empty()) + { + StartCustomDrag(selectionModel()->selectedIndexes(), supportedActions); + } + } + + void StyledTreeView::StartCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions) + { + StartCustomDragInternal(this, indexList, supportedActions); + } + + void StyledTreeView::StartCustomDragInternal(QAbstractItemView* itemView, const QModelIndexList& indexList, Qt::DropActions supportedActions) + { + QMimeData* mimeData = itemView->model()->mimeData(indexList); + if (mimeData) + { + QDrag* drag = new QDrag(itemView); + drag->setPixmap(QPixmap::fromImage(CreateDragImage(itemView, indexList))); + drag->setMimeData(mimeData); + + Qt::DropAction defDropAction = Qt::IgnoreAction; + if (itemView->defaultDropAction() != Qt::IgnoreAction && (supportedActions & itemView->defaultDropAction())) + { + defDropAction = itemView->defaultDropAction(); + } + else if (supportedActions & Qt::CopyAction && itemView->dragDropMode() != QAbstractItemView::InternalMove) + { + defDropAction = Qt::CopyAction; + } + + drag->exec(supportedActions, defDropAction); + } + } + + QImage StyledTreeView::CreateDragImage(QAbstractItemView* itemView, const QModelIndexList& indexList) + { + // Generate a drag image of the item icon and text, normally done internally, and inaccessible + QRect rect(0, 0, 0, 0); + for (const auto& index : indexList) + { + if (index.column() != 0) + { + continue; + } + + QRect itemRect = itemView->visualRect(index); + rect.setHeight(rect.height() + itemRect.height()); + rect.setWidth(AZStd::GetMax(rect.width(), itemRect.width())); + } + + QImage dragImage(rect.size(), QImage::Format_ARGB32_Premultiplied); + + QPainter dragPainter(&dragImage); + dragPainter.setCompositionMode(QPainter::CompositionMode_Source); + dragPainter.fillRect(dragImage.rect(), Qt::transparent); + dragPainter.setCompositionMode(QPainter::CompositionMode_SourceOver); + dragPainter.setOpacity(0.35f); + dragPainter.fillRect(rect, QColor("#222222")); + dragPainter.setOpacity(1.0f); + + int imageY = 0; + for (const auto& index : indexList) + { + if (index.column() != 0) + { + continue; + } + + QRect itemRect = itemView->visualRect(index); + dragPainter.drawPixmap(QPoint(0, imageY), + itemView->model()->data(index, Qt::DecorationRole).value().pixmap(QSize(16, 16))); + dragPainter.setPen( + itemView->model()->data(index, Qt::ForegroundRole).value().color()); + dragPainter.setFont( + itemView->font()); + dragPainter.drawText(QRect(20, imageY, rect.width() - 20, rect.height()), + itemView->model()->data(index, Qt::DisplayRole).value()); + imageY += itemRect.height(); + } + + dragPainter.end(); + return dragImage; + } + + StyledTreeWidget::StyledTreeWidget(QWidget* parent) + : QTreeWidget(parent) + { + } + + void StyledTreeWidget::startDrag(Qt::DropActions supportedActions) + { + if (!selectionModel()->selectedIndexes().empty()) + { + StyledTreeView::StartCustomDragInternal(this, selectionModel()->selectedIndexes(), supportedActions); + } + } + } // namespace AzQtComponents #include diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.h b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.h index 8fdcc24a8b..7510819e23 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.h +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.h @@ -9,8 +9,11 @@ #pragma once #if !defined(Q_MOC_RUN) +#include #include #include + +#include #endif namespace AzQtComponents @@ -68,4 +71,46 @@ namespace AzQtComponents void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const override; }; + //! For most of the custom QTreeView styling, we override in AzQtComponents::Style class, + //! but there are some cases (e.g. drag/drop) that can only be overriden by an actual + //! subclass of the QTreeView + class AZ_QT_COMPONENTS_API StyledTreeView + : public QTreeView + { + Q_OBJECT + + public: + AZ_CLASS_ALLOCATOR(StyledTreeView, AZ::SystemAllocator, 0); + + explicit StyledTreeView(QWidget* parent = nullptr); + + //! NOTE: QTreeWidget derives from QTreeView, but because we need a custom dervied class + //! of QTreeView, then we can't inherit our custom drag methods in our custom derived + //! class of QTreeWidget, so these functions are made static so they can be shared + static void StartCustomDragInternal(QAbstractItemView* itemView, const QModelIndexList& indexList, Qt::DropActions supportedActions); + static QImage CreateDragImage(QAbstractItemView* itemView, const QModelIndexList& indexList); + + protected: + void startDrag(Qt::DropActions supportedActions) override; + + virtual void StartCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions); + }; + + //! For most of the custom QTreeWidget styling, we override in AzQtComponents::Style class, + //! but there are some cases (e.g. drag/drop) that can only be overriden by an actual + //! subclass of the QTreeWidget. + class AZ_QT_COMPONENTS_API StyledTreeWidget + : public QTreeWidget + { + Q_OBJECT + + public: + AZ_CLASS_ALLOCATOR(StyledTreeWidget, AZ::SystemAllocator, 0); + + explicit StyledTreeWidget(QWidget* parent = nullptr); + + protected: + void startDrag(Qt::DropActions supportedActions) override; + }; + } // namespace AzQtComponents diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.cpp index eaee196c09..0549c600d3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.cpp @@ -27,7 +27,7 @@ namespace AzToolsFramework { EntityOutlinerTreeView::EntityOutlinerTreeView(QWidget* pParent) - : QTreeView(pParent) + : AzQtComponents::StyledTreeView(pParent) , m_queuedMouseEvent(nullptr) , m_draggingUnselectedItem(false) { @@ -144,16 +144,12 @@ namespace AzToolsFramework if (!selectionModel()->isSelected(index)) { - startCustomDrag({ index }, supportedActions); + StartCustomDrag({ index }, supportedActions); return; } } - if (!selectionModel()->selectedIndexes().empty()) - { - startCustomDrag(selectionModel()->selectedIndexes(), supportedActions); - return; - } + StyledTreeView::startDrag(supportedActions); } void EntityOutlinerTreeView::dragMoveEvent(QDragMoveEvent* event) @@ -243,14 +239,14 @@ namespace AzToolsFramework QTreeView::mousePressEvent(&mousePressedEvent); } - void EntityOutlinerTreeView::startCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions) + void EntityOutlinerTreeView::StartCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions) { m_draggingUnselectedItem = true; //sort by container entity depth and order in hierarchy for proper drag image and drop order QModelIndexList indexListSorted = indexList; AZStd::unordered_map> locations; - for (auto index : indexListSorted) + for (const auto& index : indexListSorted) { AZ::EntityId entityId(index.data(EntityOutlinerListModel::EntityIdRole).value()); AzToolsFramework::GetEntityLocationInHierarchy(entityId, locations[entityId]); @@ -263,76 +259,8 @@ namespace AzToolsFramework return AZStd::lexicographical_compare(locationsE1.begin(), locationsE1.end(), locationsE2.begin(), locationsE2.end()); }); - //get the data for the unselected item(s) - QMimeData* mimeData = model()->mimeData(indexListSorted); - if (mimeData) - { - //initiate drag/drop for the item - QDrag* drag = new QDrag(this); - drag->setPixmap(QPixmap::fromImage(createDragImage(indexListSorted))); - drag->setMimeData(mimeData); - Qt::DropAction defDropAction = Qt::IgnoreAction; - if (defaultDropAction() != Qt::IgnoreAction && (supportedActions & defaultDropAction())) - { - defDropAction = defaultDropAction(); - } - else if (supportedActions & Qt::CopyAction && dragDropMode() != QAbstractItemView::InternalMove) - { - defDropAction = Qt::CopyAction; - } - drag->exec(supportedActions, defDropAction); - } + StyledTreeView::StartCustomDrag(indexListSorted, supportedActions); } - - QImage EntityOutlinerTreeView::createDragImage(const QModelIndexList& indexList) - { - //generate a drag image of the item icon and text, normally done internally, and inaccessible - QRect rect(0, 0, 0, 0); - for (auto index : indexList) - { - if (index.column() != 0) - { - continue; - } - QRect itemRect = visualRect(index); - rect.setHeight(rect.height() + itemRect.height()); - rect.setWidth(AZStd::GetMax(rect.width(), itemRect.width())); - } - - QImage dragImage(rect.size(), QImage::Format_ARGB32_Premultiplied); - - QPainter dragPainter(&dragImage); - dragPainter.setCompositionMode(QPainter::CompositionMode_Source); - dragPainter.fillRect(dragImage.rect(), Qt::transparent); - dragPainter.setCompositionMode(QPainter::CompositionMode_SourceOver); - dragPainter.setOpacity(0.35f); - dragPainter.fillRect(rect, QColor("#222222")); - dragPainter.setOpacity(1.0f); - - int imageY = 0; - for (auto index : indexList) - { - if (index.column() != 0) - { - continue; - } - - QRect itemRect = visualRect(index); - dragPainter.drawPixmap(QPoint(0, imageY), - model()->data(index, Qt::DecorationRole).value().pixmap(QSize(16, 16))); - dragPainter.setPen( - model()->data(index, Qt::ForegroundRole).value().color()); - dragPainter.setFont( - font()); - dragPainter.drawText(QRect(20, imageY, rect.width() - 20, rect.height()), - model()->data(index, Qt::DisplayRole).value()); - imageY += itemRect.height(); - } - - dragPainter.end(); - return dragImage; - } - } #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.hxx index 89471de228..66cd082407 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.hxx @@ -14,7 +14,8 @@ #include #include -#include + +#include #endif #pragma once @@ -33,7 +34,7 @@ namespace AzToolsFramework //! allow for dragging and dropping of entities from the outliner into the property editor //! of other entities. If the selection updates instantly, this would never be possible. class EntityOutlinerTreeView - : public QTreeView + : public AzQtComponents::StyledTreeView { Q_OBJECT; public: @@ -68,9 +69,7 @@ namespace AzToolsFramework void processQueuedMousePressedEvent(QMouseEvent* event); - void startCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions); - - QImage createDragImage(const QModelIndexList& indexList); + void StartCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions) override; void PaintBranchBackground(QPainter* painter, const QRect& rect, const QModelIndex& index) const; diff --git a/Gems/LyShine/Code/Editor/HierarchyWidget.cpp b/Gems/LyShine/Code/Editor/HierarchyWidget.cpp index 0b56382237..30cb7e51dc 100644 --- a/Gems/LyShine/Code/Editor/HierarchyWidget.cpp +++ b/Gems/LyShine/Code/Editor/HierarchyWidget.cpp @@ -21,7 +21,7 @@ #include HierarchyWidget::HierarchyWidget(EditorWindow* editorWindow) - : QTreeWidget() + : AzQtComponents::StyledTreeWidget() , m_isDeleting(false) , m_editorWindow(editorWindow) , m_entityItemMap() @@ -391,7 +391,7 @@ void HierarchyWidget::startDrag(Qt::DropActions supportedActions) // Remember the current selection so that we can revert back to it when the items are dragged back into the hierarchy m_dragSelection = selectedItems(); - QTreeView::startDrag(supportedActions); + AzQtComponents::StyledTreeWidget::startDrag(supportedActions); } void HierarchyWidget::dragEnterEvent(QDragEnterEvent* event) diff --git a/Gems/LyShine/Code/Editor/HierarchyWidget.h b/Gems/LyShine/Code/Editor/HierarchyWidget.h index 525aaa8a3a..324eda207b 100644 --- a/Gems/LyShine/Code/Editor/HierarchyWidget.h +++ b/Gems/LyShine/Code/Editor/HierarchyWidget.h @@ -10,6 +10,8 @@ #if !defined(Q_MOC_RUN) #include "EditorCommon.h" +#include + #include #include @@ -19,7 +21,7 @@ class QMimeData; class HierarchyWidget - : public QTreeWidget + : public AzQtComponents::StyledTreeWidget , private AzToolsFramework::EditorPickModeNotificationBus::Handler , private AzToolsFramework::EntityHighlightMessages::Bus::Handler { From 117bd0e680d6af8b4f6df98e0d9030f12fb62be3 Mon Sep 17 00:00:00 2001 From: jackalbe <23512001+jackalbe@users.noreply.github.com> Date: Thu, 12 Aug 2021 11:19:15 -0500 Subject: [PATCH 159/205] {LYN-2336} Fix: Python Console script help opens empty (#3060) * {LYN-2336} Fix: Python Console script help opens empty Fixes: Python Console: Script Help opens empty in AutomatedTesting project This fixes the missing Python symbols in the Editor This also fixes the PYI files to write out for the AutomatedTesting project Signed-off-by: Jackson <23512001+jackalbe@users.noreply.github.com> * Fixing proper symbol log execution times Signed-off-by: Jackson <23512001+jackalbe@users.noreply.github.com> * annotating input values with const Signed-off-by: Jackson <23512001+jackalbe@users.noreply.github.com> --- .../Code/Source/PythonLogSymbolsComponent.cpp | 25 ++++++++--- .../Code/Source/PythonLogSymbolsComponent.h | 19 ++++++--- .../Code/Source/PythonProxyBus.cpp | 2 +- .../Code/Source/PythonProxyObject.cpp | 8 ++-- .../Code/Source/PythonReflectionComponent.cpp | 8 ++-- .../Code/Source/PythonSymbolsBus.h | 36 +++++++++++++--- .../Code/Source/PythonSystemComponent.cpp | 42 +++++++++++++++++-- .../Code/Source/PythonSystemComponent.h | 3 ++ 8 files changed, 113 insertions(+), 30 deletions(-) diff --git a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp index 221e1fdcea..d39ca83000 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp @@ -90,6 +90,11 @@ namespace EditorPythonBindings PythonSymbolEventBus::Handler::BusConnect(); EditorPythonBindingsNotificationBus::Handler::BusConnect(); AZ::Interface::Register(this); + + if (PythonSymbolEventBus::GetTotalNumOfEventHandlers() > 1) + { + OnPostInitialize(); + } } void PythonLogSymbolsComponent::Deactivate() @@ -111,6 +116,7 @@ namespace EditorPythonBindings m_basePath = pythonSymbolsPath; } EditorPythonBindingsNotificationBus::Handler::BusDisconnect(); + PythonSymbolEventBus::ExecuteQueuedEvents(); } void PythonLogSymbolsComponent::WriteMethod(AZ::IO::HandleType handle, AZStd::string_view methodName, const AZ::BehaviorMethod& behaviorMethod, const AZ::BehaviorClass* behaviorClass) @@ -206,12 +212,12 @@ namespace EditorPythonBindings AZ::IO::FileIOBase::GetInstance()->Write(handle, buffer.c_str(), buffer.size()); } - void PythonLogSymbolsComponent::LogClass(AZStd::string_view moduleName, AZ::BehaviorClass* behaviorClass) + void PythonLogSymbolsComponent::LogClass(const AZStd::string moduleName, const AZ::BehaviorClass* behaviorClass) { LogClassWithName(moduleName, behaviorClass, behaviorClass->m_name.c_str()); } - void PythonLogSymbolsComponent::LogClassWithName(AZStd::string_view moduleName, AZ::BehaviorClass* behaviorClass, AZStd::string_view className) + void PythonLogSymbolsComponent::LogClassWithName(const AZStd::string moduleName, const AZ::BehaviorClass* behaviorClass, const AZStd::string className) { Internal::FileHandle fileHandle(OpenModuleAt(moduleName)); if (fileHandle.IsValid()) @@ -255,7 +261,11 @@ namespace EditorPythonBindings } } - void PythonLogSymbolsComponent::LogClassMethod(AZStd::string_view moduleName, AZStd::string_view globalMethodName, AZ::BehaviorClass* behaviorClass, AZ::BehaviorMethod* behaviorMethod) + void PythonLogSymbolsComponent::LogClassMethod( + const AZStd::string moduleName, + const AZStd::string globalMethodName, + const AZ::BehaviorClass* behaviorClass, + const AZ::BehaviorMethod* behaviorMethod) { AZ_UNUSED(behaviorClass); Internal::FileHandle fileHandle(OpenModuleAt(moduleName)); @@ -265,7 +275,7 @@ namespace EditorPythonBindings } } - void PythonLogSymbolsComponent::LogBus(AZStd::string_view moduleName, AZStd::string_view busName, AZ::BehaviorEBus* behaviorEBus) + void PythonLogSymbolsComponent::LogBus(const AZStd::string moduleName, const AZStd::string busName, const AZ::BehaviorEBus* behaviorEBus) { if (behaviorEBus->m_events.empty()) { @@ -404,7 +414,7 @@ namespace EditorPythonBindings } } - void PythonLogSymbolsComponent::LogGlobalMethod(AZStd::string_view moduleName, AZStd::string_view methodName, AZ::BehaviorMethod* behaviorMethod) + void PythonLogSymbolsComponent::LogGlobalMethod(const AZStd::string moduleName, const AZStd::string methodName, const AZ::BehaviorMethod* behaviorMethod) { Internal::FileHandle fileHandle(OpenModuleAt(moduleName)); if (fileHandle.IsValid()) @@ -428,7 +438,10 @@ namespace EditorPythonBindings } } - void PythonLogSymbolsComponent::LogGlobalProperty(AZStd::string_view moduleName, AZStd::string_view propertyName, AZ::BehaviorProperty* behaviorProperty) + void PythonLogSymbolsComponent::LogGlobalProperty( + const AZStd::string moduleName, + const AZStd::string propertyName, + const AZ::BehaviorProperty* behaviorProperty) { if (!behaviorProperty->m_getter || !behaviorProperty->m_getter->GetResult()) { diff --git a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h index 54285198cf..5fbd1c3f37 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h +++ b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h @@ -51,12 +51,19 @@ namespace EditorPythonBindings //////////////////////////////////////////////////////////////////////// // PythonSymbolEventBus::Handler - void LogClass(AZStd::string_view moduleName, AZ::BehaviorClass* behaviorClass) override; - void LogClassWithName(AZStd::string_view moduleName, AZ::BehaviorClass* behaviorClass, AZStd::string_view className) override; - void LogClassMethod(AZStd::string_view moduleName, AZStd::string_view globalMethodName, AZ::BehaviorClass* behaviorClass, AZ::BehaviorMethod* behaviorMethod) override; - void LogBus(AZStd::string_view moduleName, AZStd::string_view busName, AZ::BehaviorEBus* behaviorEBus) override; - void LogGlobalMethod(AZStd::string_view moduleName, AZStd::string_view methodName, AZ::BehaviorMethod* behaviorMethod) override; - void LogGlobalProperty(AZStd::string_view moduleName, AZStd::string_view propertyName, AZ::BehaviorProperty* behaviorProperty) override; + void LogClass(const AZStd::string moduleName, const AZ::BehaviorClass* behaviorClass) override; + void LogClassWithName(const AZStd::string moduleName, const AZ::BehaviorClass* behaviorClass, const AZStd::string className) override; + void LogClassMethod( + const AZStd::string moduleName, + const AZStd::string globalMethodName, + const AZ::BehaviorClass* behaviorClass, + const AZ::BehaviorMethod* behaviorMethod) override; + void LogBus(const AZStd::string moduleName, const AZStd::string busName, const AZ::BehaviorEBus* behaviorEBus) override; + void LogGlobalMethod(const AZStd::string moduleName, const AZStd::string methodName, const AZ::BehaviorMethod* behaviorMethod) override; + void LogGlobalProperty( + const AZStd::string moduleName, + const AZStd::string propertyName, + const AZ::BehaviorProperty* behaviorProperty) override; void Finalize() override; AZStd::string FetchPythonTypeName(const AZ::BehaviorParameter& param) override; diff --git a/Gems/EditorPythonBindings/Code/Source/PythonProxyBus.cpp b/Gems/EditorPythonBindings/Code/Source/PythonProxyBus.cpp index 89f8248202..e640778bbe 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonProxyBus.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonProxyBus.cpp @@ -394,7 +394,7 @@ namespace EditorPythonBindings // log the bus symbol AZStd::string subModuleName = pybind11::cast(thisBusModule.attr("__name__")); - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::LogBus, subModuleName, ebusName, behaviorEBus); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::LogBus, subModuleName, ebusName, behaviorEBus); } } diff --git a/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.cpp b/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.cpp index de8009830b..706ca48156 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.cpp @@ -756,7 +756,7 @@ namespace EditorPythonBindings } AZStd::string subModuleName = pybind11::cast(subModule.attr("__name__")); - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::LogClassMethod, subModuleName, globalMethodName, behaviorClass, behaviorMethod); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::LogClassMethod, subModuleName, globalMethodName, behaviorClass, behaviorMethod); } else { @@ -782,7 +782,7 @@ namespace EditorPythonBindings pybind11::setattr(subModule, constantPropertyName.c_str(), constantValue); AZStd::string subModuleName = pybind11::cast(subModule.attr("__name__")); - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::LogGlobalProperty, subModuleName, constantPropertyName, behaviorProperty); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::LogGlobalProperty, subModuleName, constantPropertyName, behaviorProperty); } } @@ -809,11 +809,11 @@ namespace EditorPythonBindings { return ConstructPythonProxyObjectByTypename(behaviorClassName, pythonArgs); }); - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::LogClassWithName, subModuleName, behaviorClass, properSyntax); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::LogClassWithName, subModuleName, behaviorClass, properSyntax); } else { - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::LogClass, subModuleName, behaviorClass); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::LogClass, subModuleName, behaviorClass); } } } diff --git a/Gems/EditorPythonBindings/Code/Source/PythonReflectionComponent.cpp b/Gems/EditorPythonBindings/Code/Source/PythonReflectionComponent.cpp index 0404e81380..38e00e73ed 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonReflectionComponent.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonReflectionComponent.cpp @@ -153,7 +153,7 @@ namespace EditorPythonBindings StaticPropertyHolderMapEntry& entry = iter->second; entry.second->AddProperty(propertyName, behaviorProperty); } - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::LogGlobalProperty, scopeName, propertyName, behaviorProperty); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::LogGlobalProperty, scopeName, propertyName, behaviorProperty); } pybind11::module DetermineScope(pybind11::module scope, const AZStd::string& fullName) @@ -302,7 +302,7 @@ namespace EditorPythonBindings // log global method symbol AZStd::string subModuleName = pybind11::cast(targetModule.attr("__name__")); - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::LogGlobalMethod, subModuleName, methodName, behaviorMethod); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::LogGlobalMethod, subModuleName, methodName, behaviorMethod); } } @@ -325,7 +325,7 @@ namespace EditorPythonBindings // log global property symbol AZStd::string subModuleName = pybind11::cast(globalsModule.attr("__name__")); - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::LogGlobalProperty, subModuleName, propertyName, behaviorProperty); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::LogGlobalProperty, subModuleName, propertyName, behaviorProperty); if (behaviorProperty->m_getter && behaviorProperty->m_setter) { @@ -377,7 +377,7 @@ namespace EditorPythonBindings PythonProxyBusManagement::CreateSubmodule(parentModule); Internal::RegisterPaths(parentModule); - PythonSymbolEventBus::Broadcast(&PythonSymbolEventBus::Events::Finalize); + PythonSymbolEventBus::QueueBroadcast(&PythonSymbolEventBus::Events::Finalize); } } } diff --git a/Gems/EditorPythonBindings/Code/Source/PythonSymbolsBus.h b/Gems/EditorPythonBindings/Code/Source/PythonSymbolsBus.h index 242225e87a..9c6d3bab37 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonSymbolsBus.h +++ b/Gems/EditorPythonBindings/Code/Source/PythonSymbolsBus.h @@ -9,6 +9,14 @@ #include +namespace AZ +{ + class BehaviorClass; + class BehaviorMethod; + class BehaviorEBus; + class BehaviorProperty; +} + namespace EditorPythonBindings { //! An interface to track exported Python symbols @@ -16,23 +24,39 @@ namespace EditorPythonBindings : public AZ::EBusTraits { public: + // the symbols will be written out in the future + static const bool EnableEventQueue = true; + //! logs a behavior class type - virtual void LogClass(AZStd::string_view moduleName, AZ::BehaviorClass* behaviorClass) = 0; + virtual void LogClass(const AZStd::string moduleName, const AZ::BehaviorClass* behaviorClass) = 0; //! logs a behavior class type with an override to its name - virtual void LogClassWithName(AZStd::string_view moduleName, AZ::BehaviorClass* behaviorClass, AZStd::string_view className) = 0; + virtual void LogClassWithName( + const AZStd::string moduleName, + const AZ::BehaviorClass* behaviorClass, + const AZStd::string className) = 0; //! logs a static class method with a specified global method name - virtual void LogClassMethod(AZStd::string_view moduleName, AZStd::string_view globalMethodName, AZ::BehaviorClass* behaviorClass, AZ::BehaviorMethod* behaviorMethod) = 0; + virtual void LogClassMethod( + const AZStd::string moduleName, + const AZStd::string globalMethodName, + const AZ::BehaviorClass* behaviorClass, + const AZ::BehaviorMethod* behaviorMethod) = 0; //! logs a behavior bus with a specified bus name - virtual void LogBus(AZStd::string_view moduleName, AZStd::string_view busName, AZ::BehaviorEBus* behaviorEBus) = 0; + virtual void LogBus(const AZStd::string moduleName, const AZStd::string busName, const AZ::BehaviorEBus* behaviorEBus) = 0; //! logs a global method from the behavior context registry with a specified method name - virtual void LogGlobalMethod(AZStd::string_view moduleName, AZStd::string_view methodName, AZ::BehaviorMethod* behaviorMethod) = 0; + virtual void LogGlobalMethod( + const AZStd::string moduleName, + const AZStd::string methodName, + const AZ::BehaviorMethod* behaviorMethod) = 0; //! logs a global property, enum, or constant from the behavior context registry with a specified property name - virtual void LogGlobalProperty(AZStd::string_view moduleName, AZStd::string_view propertyName, AZ::BehaviorProperty* behaviorProperty) = 0; + virtual void LogGlobalProperty( + const AZStd::string moduleName, + const AZStd::string propertyName, + const AZ::BehaviorProperty* behaviorProperty) = 0; //! signals the end of the logging of symbols virtual void Finalize() = 0; diff --git a/Gems/EditorPythonBindings/Code/Source/PythonSystemComponent.cpp b/Gems/EditorPythonBindings/Code/Source/PythonSystemComponent.cpp index 32411e9417..8df196e7cb 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonSystemComponent.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonSystemComponent.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -25,6 +26,7 @@ #include #include #include +#include #include #include @@ -39,7 +41,7 @@ namespace Platform { - // Implemented in each different platform's implentation files, as it differs per platform. + // Implemented in each different platform's implementation files, as it differs per platform. bool InsertPythonBinaryLibraryPaths(AZStd::unordered_set& paths, const char* pythonPackage, const char* engineRoot); AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot); } @@ -225,6 +227,37 @@ namespace RedirectOutput namespace EditorPythonBindings { + // A stand in bus to capture the log symbol queue events + // so that when/if the PythonLogSymbolsComponent becomes + // active it can write out the python symbols to disk + class PythonSystemComponent::SymbolLogHelper final + : public PythonSymbolEventBus::Handler + { + public: + SymbolLogHelper() + { + PythonSymbolEventBus::Handler::BusConnect(); + } + + ~SymbolLogHelper() + { + PythonSymbolEventBus::ExecuteQueuedEvents(); + PythonSymbolEventBus::Handler::BusDisconnect(); + } + + void LogClass(const AZStd::string, const AZ::BehaviorClass*) override {} + void LogClassWithName(const AZStd::string, const AZ::BehaviorClass*, const AZStd::string) override {} + void LogClassMethod( + const AZStd::string, + const AZStd::string, + const AZ::BehaviorClass*, + const AZ::BehaviorMethod*) override {} + void LogBus(const AZStd::string, const AZStd::string, const AZ::BehaviorEBus*) override {} + void LogGlobalMethod(const AZStd::string, const AZStd::string, const AZ::BehaviorMethod*) override {} + void LogGlobalProperty(const AZStd::string, const AZStd::string, const AZ::BehaviorProperty*) override {} + void Finalize() override {} + }; + void PythonSystemComponent::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serialize = azrtti_cast(context)) @@ -471,8 +504,6 @@ namespace EditorPythonBindings } } - - bool PythonSystemComponent::StartPythonInterpreter(const PythonPathStack& pythonPathStack) { AZStd::unordered_set pyPackageSites(pythonPathStack.begin(), pythonPathStack.end()); @@ -520,6 +551,11 @@ namespace EditorPythonBindings AZStd::lock_guard lock(m_lock); pybind11::gil_scoped_acquire acquire; + if (EditorPythonBindings::PythonSymbolEventBus::GetTotalNumOfEventHandlers() == 0) + { + m_symbolLogHelper = AZStd::make_shared(); + } + // print Python version using AZ logging const int verRet = PyRun_SimpleStringFlags("import sys \nprint (sys.version) \n", nullptr); AZ_Error("python", verRet == 0, "Error trying to fetch the version number in Python!"); diff --git a/Gems/EditorPythonBindings/Code/Source/PythonSystemComponent.h b/Gems/EditorPythonBindings/Code/Source/PythonSystemComponent.h index 679da3ccab..48ac27a036 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonSystemComponent.h +++ b/Gems/EditorPythonBindings/Code/Source/PythonSystemComponent.h @@ -59,10 +59,13 @@ namespace EditorPythonBindings //////////////////////////////////////////////////////////////////////// private: + class SymbolLogHelper; + // handle multiple Python initializers and threads AZStd::atomic_int m_initalizeWaiterCount {0}; AZStd::semaphore m_initalizeWaiter; AZStd::recursive_mutex m_lock; + AZStd::shared_ptr m_symbolLogHelper; enum class Result { From 538276c99366112e1c8a3d5f585bd70b50abe39d Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Thu, 12 Aug 2021 09:32:23 -0700 Subject: [PATCH 160/205] Allow project path changing and auto-completion (#3057) * Allow project path changing and auto-complete Signed-off-by: AMZN-alexpete <26804013+AMZN-alexpete@users.noreply.github.com> * Improved error message regarding the absolute path requirement Signed-off-by: AMZN-alexpete <26804013+AMZN-alexpete@users.noreply.github.com> --- .../Source/NewProjectSettingsScreen.cpp | 31 ++++++++++++++++++- .../Source/NewProjectSettingsScreen.h | 7 +++++ .../Source/ProjectSettingsScreen.cpp | 31 ++++++++++++------- .../Source/ProjectSettingsScreen.h | 7 +++-- .../Source/UpdateProjectSettingsScreen.cpp | 5 +-- 5 files changed, 64 insertions(+), 17 deletions(-) diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp index a9086a0c2b..4febb65782 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.cpp @@ -39,7 +39,7 @@ namespace O3DE::ProjectManager NewProjectSettingsScreen::NewProjectSettingsScreen(QWidget* parent) : ProjectSettingsScreen(parent) { - const QString defaultName{ "NewProject" }; + const QString defaultName = GetDefaultProjectName(); const QString defaultPath = QDir::toNativeSeparators(GetDefaultProjectPath() + "/" + defaultName); m_projectName->lineEdit()->setText(defaultName); @@ -162,6 +162,17 @@ namespace O3DE::ProjectManager return defaultPath; } + QString NewProjectSettingsScreen::GetDefaultProjectName() + { + return "NewProject"; + } + + QString NewProjectSettingsScreen::GetProjectAutoPath() + { + const QString projectName = m_projectName->lineEdit()->text(); + return QDir::toNativeSeparators(GetDefaultProjectPath() + "/" + projectName); + } + ProjectManagerScreen NewProjectSettingsScreen::GetScreenEnum() { return ProjectManagerScreen::NewProjectSettings; @@ -260,4 +271,22 @@ namespace O3DE::ProjectManager m_projectTemplateButtonGroup->blockSignals(false); } } + void NewProjectSettingsScreen::OnProjectNameUpdated() + { + if (ValidateProjectName() && !m_userChangedProjectPath) + { + m_projectPath->setText(GetProjectAutoPath()); + } + } + + void NewProjectSettingsScreen::OnProjectPathUpdated() + { + const QString defaultPath = QDir::toNativeSeparators(GetDefaultProjectPath() + "/" + GetDefaultProjectName()); + const QString autoPath = GetProjectAutoPath(); + const QString path = m_projectPath->lineEdit()->text(); + m_userChangedProjectPath = path != defaultPath && path != autoPath; + + ValidateProjectPath(); + } + } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h index ebe40de05c..42c47cb1ff 100644 --- a/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/NewProjectSettingsScreen.h @@ -40,8 +40,14 @@ namespace O3DE::ProjectManager signals: void OnTemplateSelectionChanged(int oldIndex, int newIndex); + protected: + void OnProjectNameUpdated() override; + void OnProjectPathUpdated() override; + private: + QString GetDefaultProjectName(); QString GetDefaultProjectPath(); + QString GetProjectAutoPath(); QFrame* CreateTemplateDetails(int margin); void UpdateTemplateDetails(const ProjectTemplateInfo& templateInfo); @@ -51,6 +57,7 @@ namespace O3DE::ProjectManager TagContainerWidget* m_templateIncludedGems; QVector m_templates; int m_selectedTemplateIndex = -1; + bool m_userChangedProjectPath = false; inline constexpr static int s_spacerSize = 20; inline constexpr static int s_templateDetailsContentMargin = 20; diff --git a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp index 4c79117d96..88ae3d6319 100644 --- a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.cpp @@ -40,12 +40,11 @@ namespace O3DE::ProjectManager m_verticalLayout->setAlignment(Qt::AlignTop); m_projectName = new FormLineEditWidget(tr("Project name"), "", this); - connect(m_projectName->lineEdit(), &QLineEdit::textChanged, this, &ProjectSettingsScreen::ValidateProjectName); + connect(m_projectName->lineEdit(), &QLineEdit::textChanged, this, &ProjectSettingsScreen::OnProjectNameUpdated); m_verticalLayout->addWidget(m_projectName); m_projectPath = new FormFolderBrowseEditWidget(tr("Project Location"), "", this); - m_projectPath->lineEdit()->setReadOnly(true); - connect(m_projectPath->lineEdit(), &QLineEdit::textChanged, this, &ProjectSettingsScreen::Validate); + connect(m_projectPath->lineEdit(), &QLineEdit::textChanged, this, &ProjectSettingsScreen::OnProjectPathUpdated); m_verticalLayout->addWidget(m_projectPath); projectSettingsFrame->setLayout(m_verticalLayout); @@ -110,28 +109,36 @@ namespace O3DE::ProjectManager m_projectName->setErrorLabelVisible(!projectNameIsValid); return projectNameIsValid; } + bool ProjectSettingsScreen::ValidateProjectPath() { bool projectPathIsValid = true; - if (m_projectPath->lineEdit()->text().isEmpty()) + QDir path(m_projectPath->lineEdit()->text()); + if (!path.isAbsolute()) { projectPathIsValid = false; - m_projectPath->setErrorLabelText(tr("Please provide a valid location.")); + m_projectPath->setErrorLabelText(tr("Please provide an absolute path for the project location.")); } - else + else if (path.exists() && !path.isEmpty()) { - QDir path(m_projectPath->lineEdit()->text()); - if (path.exists() && !path.isEmpty()) - { - projectPathIsValid = false; - m_projectPath->setErrorLabelText(tr("This folder exists and isn't empty. Please choose a different location.")); - } + projectPathIsValid = false; + m_projectPath->setErrorLabelText(tr("This folder exists and isn't empty. Please choose a different location.")); } m_projectPath->setErrorLabelVisible(!projectPathIsValid); return projectPathIsValid; } + void ProjectSettingsScreen::OnProjectNameUpdated() + { + ValidateProjectName(); + } + + void ProjectSettingsScreen::OnProjectPathUpdated() + { + Validate(); + } + bool ProjectSettingsScreen::Validate() { return ValidateProjectName() && ValidateProjectPath(); diff --git a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.h b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.h index b2544660e8..752e286ce1 100644 --- a/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.h +++ b/Code/Tools/ProjectManager/Source/ProjectSettingsScreen.h @@ -33,10 +33,13 @@ namespace O3DE::ProjectManager virtual bool Validate(); protected slots: - virtual bool ValidateProjectName(); - virtual bool ValidateProjectPath(); + virtual void OnProjectNameUpdated(); + virtual void OnProjectPathUpdated(); protected: + bool ValidateProjectName(); + virtual bool ValidateProjectPath(); + QString GetDefaultProjectPath(); QHBoxLayout* m_horizontalLayout; diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp index 8e9337bcae..6f7f7e1bed 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectSettingsScreen.cpp @@ -108,10 +108,11 @@ namespace O3DE::ProjectManager bool UpdateProjectSettingsScreen::ValidateProjectPath() { bool projectPathIsValid = true; - if (m_projectPath->lineEdit()->text().isEmpty()) + QDir path(m_projectPath->lineEdit()->text()); + if (!path.isAbsolute()) { projectPathIsValid = false; - m_projectPath->setErrorLabelText(tr("Please provide a valid location.")); + m_projectPath->setErrorLabelText(tr("Please provide an absolute path for the project location.")); } m_projectPath->setErrorLabelVisible(!projectPathIsValid); From 2063e7f2dd205d156df30bbc0eba25f9cd70768a Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 12 Aug 2021 11:43:23 -0500 Subject: [PATCH 161/205] Added missing header include. Signed-off-by: Chris Galvan --- .../AzQtComponents/Components/Widgets/TreeView.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.cpp index 89639ff1d7..e4d10a321d 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/TreeView.cpp @@ -13,6 +13,8 @@ #include #include +#include + #include #include #include From 6d5d042e4054b3b601b2f4131d2ba69be1f48748 Mon Sep 17 00:00:00 2001 From: Junbo Liang <68558268+junbo75@users.noreply.github.com> Date: Thu, 12 Aug 2021 10:05:13 -0700 Subject: [PATCH 162/205] Set the default region for the Resource Mapping Tool when no region is configured via AWS CLI (#2856) Ensure a valid region is always present when generating resource mapping files. --- .../controller/view_edit_controller.py | 11 +++++++++++ .../Code/Tools/ResourceMappingTool/model/constants.py | 1 + .../model/notification_label_text.py | 8 ++++++++ .../unit/controller/test_view_edit_controller.py | 3 ++- 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/controller/view_edit_controller.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/controller/view_edit_controller.py index 7e058e6a4e..54d0a29fea 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/controller/view_edit_controller.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/controller/view_edit_controller.py @@ -105,6 +105,8 @@ class ViewEditController(QObject): def _create_new_config_file(self) -> None: configuration: Configuration = self._configuration_manager.configuration + self._set_default_region(configuration) + try: new_config_file_path: str = file_utils.join_path( configuration.config_directory, constants.RESOURCE_MAPPING_DEFAULT_CONFIG_FILE_NAME) @@ -117,6 +119,15 @@ class ViewEditController(QObject): self._rescan_config_directory() + def _set_default_region(self, configuration: Configuration): + default_region = configuration.region + if not default_region or default_region == 'aws-global': + self.set_notification_frame_text_sender.emit( + notification_label_text.VIEW_EDIT_PAGE_CREATE_NEW_CONFIG_FILE_NO_DEFAULT_REGION_MESSAGE) + logger.warning(notification_label_text.VIEW_EDIT_PAGE_CREATE_NEW_CONFIG_FILE_NO_DEFAULT_REGION_MESSAGE) + + configuration.region = constants.RESOURCE_MAPPING_DEFAULT_CONFIG_FILE_REGION + def _delete_table_row(self) -> None: indices: List[QModelIndex] = self._table_view.selectedIndexes() self._proxy_model.remove_resources(indices) diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/model/constants.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/model/constants.py index 857925499b..94846fc6b5 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/model/constants.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/model/constants.py @@ -24,6 +24,7 @@ AWS_RESOURCE_REGIONS: List[str] = ["us-east-2", "us-east-1", "us-west-1", "us-we # Default client&server config file name RESOURCE_MAPPING_CONFIG_FILE_NAME_SUFFIX: str = "_aws_resource_mappings.json" RESOURCE_MAPPING_DEFAULT_CONFIG_FILE_NAME: str = "default" + RESOURCE_MAPPING_CONFIG_FILE_NAME_SUFFIX +RESOURCE_MAPPING_DEFAULT_CONFIG_FILE_REGION: str = "us-east-1" # View related constants SEARCH_TYPED_RESOURCES_VERSION: str = "Import AWS Resources" diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/model/notification_label_text.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/model/notification_label_text.py index 4fbff42aba..ecd6d8282c 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/model/notification_label_text.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/model/notification_label_text.py @@ -5,6 +5,8 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ +from model import constants + NOTIFICATION_LOADING_MESSAGE: str = "Loading..." ERROR_PAGE_OK_TEXT: str = "OK" @@ -21,6 +23,12 @@ VIEW_EDIT_PAGE_RESCAN_TEXT: str = "Rescan" VIEW_EDIT_PAGE_CONFIG_FILES_PLACEHOLDER_TEXT: str = "Found {} config files" VIEW_EDIT_PAGE_SEARCH_PLACEHOLDER_TEXT: str = "Search by Key Name, Type, Name/ID, Account ID or Region" VIEW_EDIT_PAGE_IMPORT_RESOURCES_PLACEHOLDER_TEXT: str = "Import Additional Resources" +VIEW_EDIT_PAGE_CREATE_NEW_CONFIG_FILE_NO_DEFAULT_REGION_MESSAGE: str = \ + f"Resource mapping file {constants.RESOURCE_MAPPING_DEFAULT_CONFIG_FILE_NAME} is created"\ + f" with {constants.RESOURCE_MAPPING_DEFAULT_CONFIG_FILE_REGION} as the default region. "\ + f"See "\ + f"documentation "\ + f"for configuring the AWS credentials and default region." VIEW_EDIT_PAGE_SELECT_CONFIG_FILE_MESSAGE: str = "Please select the Config file you would like to view and modify..." VIEW_EDIT_PAGE_NO_CONFIG_FILE_FOUND_MESSAGE: str = \ diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/controller/test_view_edit_controller.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/controller/test_view_edit_controller.py index d76ae12940..f854d2cd68 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/controller/test_view_edit_controller.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/controller/test_view_edit_controller.py @@ -482,6 +482,7 @@ class TestViewEditController(TestCase): mock_json_utils.create_empty_resource_mapping_file.assert_called_once() mock_file_utils.find_files_with_suffix_under_directory.assert_called_once() self._mocked_view_edit_page.set_config_files.assert_called_with(expected_config_files) + self._test_view_edit_controller.set_notification_frame_text_sender.emit.assert_called_once() @patch("controller.view_edit_controller.file_utils") @patch("controller.view_edit_controller.json_utils") @@ -496,7 +497,7 @@ class TestViewEditController(TestCase): mock_file_utils.join_path.assert_called_once() mock_json_utils.create_empty_resource_mapping_file.assert_called_once() mock_file_utils.find_files_with_suffix_under_directory.assert_not_called() - self._test_view_edit_controller.set_notification_frame_text_sender.emit.assert_called_once() + assert len(self._test_view_edit_controller.set_notification_frame_text_sender.emit.mock_calls) == 2 @patch("controller.view_edit_controller.file_utils") def test_page_rescan_button_post_notification_when_find_files_throw_exception( From 4ceff99ba149547f82b50521e5fae0fef2442d83 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 12 Aug 2021 12:10:13 -0500 Subject: [PATCH 163/205] Prevent EMFX notifications from being modal, which was blocking input while visible. Signed-off-by: Chris Galvan --- .../EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp index 0b277c6195..a186d94c49 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp @@ -28,7 +28,7 @@ namespace EMStudio setWindowTitle("Notification"); // window, no border, no focus, stays on top - setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus); + setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus | Qt::WindowStaysOnTopHint); // enable the translucent background setAttribute(Qt::WA_TranslucentBackground); From fe21b89d8eeca6529e92b0ca852d47593f1632c5 Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Thu, 12 Aug 2021 10:24:16 -0700 Subject: [PATCH 164/205] working support for editor property json serialization Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- .../EditorScriptCanvasComponent.cpp | 9 +++---- .../Framework/ScriptCanvasGraphUtilities.inl | 2 +- .../Execution/RuntimeComponent.cpp | 4 ++-- .../ScriptCanvas/Execution/RuntimeComponent.h | 2 +- .../Serialization/DatumSerializer.cpp | 24 +++---------------- 5 files changed, 10 insertions(+), 31 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Editor/Components/EditorScriptCanvasComponent.cpp b/Gems/ScriptCanvas/Code/Editor/Components/EditorScriptCanvasComponent.cpp index dbc525e8e1..2708f95f92 100644 --- a/Gems/ScriptCanvas/Code/Editor/Components/EditorScriptCanvasComponent.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Components/EditorScriptCanvasComponent.cpp @@ -322,11 +322,9 @@ namespace ScriptCanvasEditor return; } - auto& variableOverrides = parseOutcome.GetValue(); - if (!m_variableOverrides.IsEmpty()) { - variableOverrides.CopyPreviousOverriddenValues(m_variableOverrides); + parseOutcome.GetValue().CopyPreviousOverriddenValues(m_variableOverrides); } m_variableOverrides = parseOutcome.TakeValue(); @@ -351,8 +349,7 @@ namespace ScriptCanvasEditor } auto runtimeComponent = gameEntity->CreateComponent(); - auto runtimeOverrides = ConvertToRuntime(m_variableOverrides); - runtimeComponent->SetRuntimeDataOverrides(runtimeOverrides); + runtimeComponent->TakeRuntimeDataOverrides(ConvertToRuntime(m_variableOverrides)); } void EditorScriptCanvasComponent::OnCatalogAssetAdded(const AZ::Data::AssetId& assetId) @@ -518,8 +515,8 @@ namespace ScriptCanvasEditor [[maybe_unused]] AZ::Entity* scriptCanvasEntity = assetData->GetScriptCanvasEntity(); AZ_Assert(scriptCanvasEntity, "This graph must have a valid entity"); BuildGameEntityData(); - AzToolsFramework::ToolsApplicationNotificationBus::Broadcast(&AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree_NewContent); UpdateName(); + AzToolsFramework::ToolsApplicationNotificationBus::Broadcast(&AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree_NewContent); } } diff --git a/Gems/ScriptCanvas/Code/Editor/Framework/ScriptCanvasGraphUtilities.inl b/Gems/ScriptCanvas/Code/Editor/Framework/ScriptCanvasGraphUtilities.inl index 4b22864b6e..05541196f7 100644 --- a/Gems/ScriptCanvas/Code/Editor/Framework/ScriptCanvasGraphUtilities.inl +++ b/Gems/ScriptCanvas/Code/Editor/Framework/ScriptCanvasGraphUtilities.inl @@ -283,7 +283,7 @@ namespace ScriptCanvasEditor loadResult.m_runtimeAsset.Get()->GetData().m_debugMap = luaAssetResult.m_debugMap; loadResult.m_runtimeComponent = loadResult.m_entity->CreateComponent(); CopyAssetEntityIdsToOverrides(runtimeDataOverrides); - loadResult.m_runtimeComponent->SetRuntimeDataOverrides(runtimeDataOverrides); + loadResult.m_runtimeComponent->TakeRuntimeDataOverrides(AZStd::move(runtimeDataOverrides)); Execution::Context::InitializeActivationData(loadResult.m_runtimeAsset->GetData()); Execution::InitializeInterpretedStatics(loadResult.m_runtimeAsset->GetData()); } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp index 2d3fd355e2..ac19028fd5 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp @@ -93,9 +93,9 @@ namespace ScriptCanvas return m_runtimeOverrides; } - void RuntimeComponent::SetRuntimeDataOverrides(const RuntimeDataOverrides& overrideData) + void RuntimeComponent::TakeRuntimeDataOverrides(RuntimeDataOverrides&& overrideData) { - m_runtimeOverrides = overrideData; + m_runtimeOverrides = AZStd::move(overrideData); m_runtimeOverrides.EnforcePreloadBehavior(); } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h index 38ff219d4c..8650433b0a 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h @@ -54,7 +54,7 @@ namespace ScriptCanvas const RuntimeDataOverrides& GetRuntimeDataOverrides() const; - void SetRuntimeDataOverrides(const RuntimeDataOverrides& overrideData); + void TakeRuntimeDataOverrides(RuntimeDataOverrides&& overrideData); protected: static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.cpp index 207eb842fd..44ca1730a8 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Serialization/DatumSerializer.cpp @@ -50,16 +50,6 @@ namespace AZ , "scriptCanvasType" , context)); - ScriptCanvas::Datum::eOriginality originality; - AZ_Assert(azrtti_typeidm_originality)>() == azrtti_typeid() - , "m_originality type changed and won't load properly"); - result.Combine(ContinueLoadingFromJsonObjectField - ( &originality - , azrtti_typeidm_originality)>() - , inputValue - , "originality" - , context)); - AZStd::any storage; { // datum storage begin AZ::Uuid typeId = AZ::Uuid::CreateNull(); @@ -98,10 +88,10 @@ namespace AZ ( &label , azrtti_typeidm_datumLabel)>() , inputValue - , "originality" + , "label" , context)); - Datum copy(scType, originality, AZStd::any_cast(&storage), scType.GetAZType()); + Datum copy(scType, Datum::eOriginality::Original, AZStd::any_cast(&storage), scType.GetAZType()); copy.SetLabel(label); *outputDatum = copy; @@ -152,15 +142,7 @@ namespace AZ , defaultScriptDataPtr ? &defaultScriptDataPtr->GetType() : nullptr , azrtti_typeidGetType())>() , context)); - - result.Combine(ContinueStoringToJsonObjectField - ( outputValue - , "originality" - , &inputScriptDataPtr->m_originality - , defaultScriptDataPtr ? &defaultScriptDataPtr->m_originality : nullptr - , azrtti_typeidm_originality)>() - , context)); - + { // datum storage begin { rapidjson::Value typeValue; From bbe6ff7b905e1d6b02fd2bfd00d2aa9252bc60d8 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Thu, 12 Aug 2021 10:55:32 -0700 Subject: [PATCH 165/205] [redcode/crythread-2nd-pass] re-add LARGE_INTEGER definition to AppleSpecific.h Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Legacy/CryCommon/AppleSpecific.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index c572250b26..ec7cd8306e 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -458,6 +458,21 @@ typedef HANDLE HMENU; #endif //__cplusplus +typedef union _LARGE_INTEGER +{ + struct + { + DWORD LowPart; + LONG HighPart; + }; + struct + { + DWORD LowPart; + LONG HighPart; + } u; + long long QuadPart; +} LARGE_INTEGER; + extern bool QueryPerformanceCounter(LARGE_INTEGER*); extern bool QueryPerformanceFrequency(LARGE_INTEGER* frequency); From 9579826b5c9cbfe2dfd89074964111dff761c555 Mon Sep 17 00:00:00 2001 From: Vincent Liu <5900509+onecent1101@users.noreply.github.com> Date: Thu, 12 Aug 2021 10:56:51 -0700 Subject: [PATCH 166/205] [SPEC-7971] Update gem module name to match cmake target name (#3055) Fixes for module names so they match cmake target name --- .../Code/AWSGameLiftClient/Source/AWSGameLiftClientModule.cpp | 2 +- .../Code/AWSGameLiftServer/Source/AWSGameLiftServerModule.cpp | 2 +- Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugModule.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/AWSGameLiftClientModule.cpp b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/AWSGameLiftClientModule.cpp index 4155aaca80..8a9ea5003a 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/AWSGameLiftClientModule.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/AWSGameLiftClientModule.cpp @@ -42,4 +42,4 @@ namespace AWSGameLift }; }// namespace AWSGameLift -AZ_DECLARE_MODULE_CLASS(Gem_AWSGameLift_Client, AWSGameLift::AWSGameLiftClientModule) +AZ_DECLARE_MODULE_CLASS(Gem_AWSGameLift_Clients, AWSGameLift::AWSGameLiftClientModule) diff --git a/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/AWSGameLiftServerModule.cpp b/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/AWSGameLiftServerModule.cpp index dfdf541049..9feacafec5 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/AWSGameLiftServerModule.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/AWSGameLiftServerModule.cpp @@ -42,4 +42,4 @@ namespace AWSGameLift }; }// namespace AWSGameLift -AZ_DECLARE_MODULE_CLASS(Gem_AWSGameLift_Server, AWSGameLift::AWSGameLiftServerModule) +AZ_DECLARE_MODULE_CLASS(Gem_AWSGameLift_Servers, AWSGameLift::AWSGameLiftServerModule) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugModule.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugModule.cpp index b320959dd7..bb80ffad29 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugModule.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugModule.cpp @@ -28,4 +28,4 @@ namespace Multiplayer } } -AZ_DECLARE_MODULE_CLASS(Gem_Multiplayer_Imgui, Multiplayer::MultiplayerDebugModule); +AZ_DECLARE_MODULE_CLASS(Gem_Multiplayer_Debug, Multiplayer::MultiplayerDebugModule); From 28c477997d9e97564424c6afbeccaa915b2bf8b1 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Thu, 12 Aug 2021 10:58:41 -0700 Subject: [PATCH 167/205] [redcode/crythread-2nd-pass] fixed missing iOS include Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- .../GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp b/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp index 05fb56dfc1..3fa2a369a6 100644 --- a/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp +++ b/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp @@ -7,6 +7,7 @@ */ #include +#include namespace GridMate { From 72e99dd52b83272f0b57fd48015ead570cdb7dcb Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Thu, 12 Aug 2021 11:02:44 -0700 Subject: [PATCH 168/205] [redcode/crythread-2nd-pass] removed platform.h include hack linked to CryThread.h for apple platforms in ILog.h and ISystem.h Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Legacy/CryCommon/ILog.h | 7 ------- Code/Legacy/CryCommon/ISystem.h | 7 ------- 2 files changed, 14 deletions(-) diff --git a/Code/Legacy/CryCommon/ILog.h b/Code/Legacy/CryCommon/ILog.h index e71e1f036d..23257ea59b 100644 --- a/Code/Legacy/CryCommon/ILog.h +++ b/Code/Legacy/CryCommon/ILog.h @@ -6,13 +6,6 @@ * */ - -// In Mac, including ILog without including platform.h first fails because platform.h -// includes CryThread.h which includes CryThread_pthreads.h which uses ILog. -// So plaform.h needs the contents of ILog.h. -// By including platform.h outside of the guard, we give platform.h the right include order -#include - #ifndef CRYINCLUDE_CRYCOMMON_ILOG_H #define CRYINCLUDE_CRYCOMMON_ILOG_H #pragma once diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index e0996fc927..ff72c2e60f 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -6,13 +6,6 @@ * */ - -// In Mac, including ISystem without including platform.h first fails because platform.h -// includes CryThread.h which includes CryThread_pthreads.h which uses ISystem (gEnv). -// So plaform.h needs the contents of ISystem.h. -// By including platform.h outside of the guard, we give platform.h the right include order -#include // Needed for LARGE_INTEGER (for consoles). - #ifndef CRYINCLUDE_CRYCOMMON_ISYSTEM_H #define CRYINCLUDE_CRYCOMMON_ISYSTEM_H #pragma once From c9df7c69a45289f0d8512853d184e52e609a855f Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 12 Aug 2021 13:20:55 -0500 Subject: [PATCH 169/205] Updated slice entity outliner to use new consolidated StyledTreeView as well. Signed-off-by: Chris Galvan --- .../UI/Outliner/OutlinerTreeView.cpp | 83 ++----------------- .../UI/Outliner/OutlinerTreeView.hxx | 9 +- 2 files changed, 10 insertions(+), 82 deletions(-) diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.cpp index 017f59cdc3..158e45d6e2 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.cpp @@ -20,7 +20,7 @@ #include OutlinerTreeView::OutlinerTreeView(QWidget* pParent) - : QTreeView(pParent) + : AzQtComponents::StyledTreeView(pParent) , m_queuedMouseEvent(nullptr) , m_draggingUnselectedItem(false) { @@ -135,16 +135,12 @@ void OutlinerTreeView::startDrag(Qt::DropActions supportedActions) if (!selectionModel()->isSelected(index)) { - startCustomDrag({ index }, supportedActions); + StartCustomDrag({ index }, supportedActions); return; } } - if (!selectionModel()->selectedIndexes().empty()) - { - startCustomDrag(selectionModel()->selectedIndexes(), supportedActions); - return; - } + StyledTreeView::startDrag(supportedActions); } void OutlinerTreeView::dragMoveEvent(QDragMoveEvent* event) @@ -336,14 +332,14 @@ void OutlinerTreeView::processQueuedMousePressedEvent(QMouseEvent* event) QTreeView::mousePressEvent(&mousePressedEvent); } -void OutlinerTreeView::startCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions) +void OutlinerTreeView::StartCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions) { m_draggingUnselectedItem = true; //sort by container entity depth and order in hierarchy for proper drag image and drop order QModelIndexList indexListSorted = indexList; AZStd::unordered_map> locations; - for (auto index : indexListSorted) + for (const auto& index : indexListSorted) { AZ::EntityId entityId(index.data(OutlinerListModel::EntityIdRole).value()); AzToolsFramework::GetEntityLocationInHierarchy(entityId, locations[entityId]); @@ -356,74 +352,7 @@ void OutlinerTreeView::startCustomDrag(const QModelIndexList& indexList, Qt::Dro return AZStd::lexicographical_compare(locationsE1.begin(), locationsE1.end(), locationsE2.begin(), locationsE2.end()); }); - //get the data for the unselected item(s) - QMimeData* mimeData = model()->mimeData(indexListSorted); - if (mimeData) - { - //initiate drag/drop for the item - QDrag* drag = new QDrag(this); - drag->setPixmap(QPixmap::fromImage(createDragImage(indexListSorted))); - drag->setMimeData(mimeData); - Qt::DropAction defDropAction = Qt::IgnoreAction; - if (defaultDropAction() != Qt::IgnoreAction && (supportedActions & defaultDropAction())) - { - defDropAction = defaultDropAction(); - } - else if (supportedActions & Qt::CopyAction && dragDropMode() != QAbstractItemView::InternalMove) - { - defDropAction = Qt::CopyAction; - } - drag->exec(supportedActions, defDropAction); - } -} - -QImage OutlinerTreeView::createDragImage(const QModelIndexList& indexList) -{ - //generate a drag image of the item icon and text, normally done internally, and inaccessible - QRect rect(0, 0, 0, 0); - for (auto index : indexList) - { - if (index.column() != 0) - { - continue; - } - QRect itemRect = visualRect(index); - rect.setHeight(rect.height() + itemRect.height()); - rect.setWidth(AZStd::GetMax(rect.width(), itemRect.width())); - } - - QImage dragImage(rect.size(), QImage::Format_ARGB32_Premultiplied); - - QPainter dragPainter(&dragImage); - dragPainter.setCompositionMode(QPainter::CompositionMode_Source); - dragPainter.fillRect(dragImage.rect(), Qt::transparent); - dragPainter.setCompositionMode(QPainter::CompositionMode_SourceOver); - dragPainter.setOpacity(0.35f); - dragPainter.fillRect(rect, QColor("#222222")); - dragPainter.setOpacity(1.0f); - - int imageY = 0; - for (auto index : indexList) - { - if (index.column() != 0) - { - continue; - } - - QRect itemRect = visualRect(index); - dragPainter.drawPixmap(QPoint(0, imageY), - model()->data(index, Qt::DecorationRole).value().pixmap(QSize(16, 16))); - dragPainter.setPen( - model()->data(index, Qt::ForegroundRole).value().color()); - dragPainter.setFont( - font()); - dragPainter.drawText(QRect(20, imageY, rect.width() - 20, rect.height()), - model()->data(index, Qt::DisplayRole).value()); - imageY += itemRect.height(); - } - - dragPainter.end(); - return dragImage; + StyledTreeView::StartCustomDrag(indexListSorted, supportedActions); } #include diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.hxx b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.hxx index fe7a494be4..b597b70092 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.hxx +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.hxx @@ -15,7 +15,8 @@ #include #include -#include + +#include #endif #pragma once @@ -31,7 +32,7 @@ class OutlinerTreeViewModel; //! allow for dragging and dropping of entities from the outliner into the property editor //! of other entities. If the selection updates instantly, this would never be possible. class OutlinerTreeView - : public QTreeView + : public AzQtComponents::StyledTreeView { Q_OBJECT; public: @@ -66,9 +67,7 @@ private: void processQueuedMousePressedEvent(QMouseEvent* event); - void startCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions); - - QImage createDragImage(const QModelIndexList& indexList); + void StartCustomDrag(const QModelIndexList& indexList, Qt::DropActions supportedActions) override; void DrawLayerUI(QPainter* painter, const QRect& rect, const QModelIndex& index) const; From c2b8542bbd0e4e71fa9d77877607ff9c76e152b4 Mon Sep 17 00:00:00 2001 From: moudgils <47460854+moudgils@users.noreply.github.com> Date: Thu, 12 Aug 2021 12:07:46 -0700 Subject: [PATCH 170/205] Support for refresh rate and sync interval (#2989) * Add support for querying the refresh rate and sync interval --- .../AzFramework/Windowing/NativeWindow.cpp | 27 +++++++++++++++++++ .../AzFramework/Windowing/NativeWindow.h | 3 +++ .../AzFramework/Windowing/WindowBus.h | 9 +++++++ .../Windowing/NativeWindow_Android.cpp | 7 ++++- .../Windowing/NativeWindow_Linux.cpp | 6 +++++ .../AzFramework/Windowing/NativeWindow_Mac.mm | 18 +++++++++++++ .../Windowing/NativeWindow_Windows.cpp | 20 ++++++++++++++ .../AzFramework/Windowing/NativeWindow_ios.mm | 9 ++++++- Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h | 1 - .../Windows/RHI/NsightAftermath_Windows.cpp | 2 +- .../Source/Platform/Mac/RHI/Conversions_Mac.h | 2 ++ .../Source/Platform/iOS/RHI/Conversions_iOS.h | 2 ++ .../Atom/RHI/Metal/Code/Source/RHI/Device.cpp | 1 - .../RHI/Metal/Code/Source/RHI/SwapChain.cpp | 18 ++++++------- .../RHI/Metal/Code/Source/RHI/SwapChain.h | 2 +- .../Code/Source/RPI.Public/WindowContext.cpp | 19 ++++--------- .../Viewport/RenderViewportWidget.h | 2 ++ .../Source/Viewport/RenderViewportWidget.cpp | 10 +++++++ 18 files changed, 128 insertions(+), 30 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Windowing/NativeWindow.cpp b/Code/Framework/AzFramework/AzFramework/Windowing/NativeWindow.cpp index df1549cc31..c89d12a8ae 100644 --- a/Code/Framework/AzFramework/AzFramework/Windowing/NativeWindow.cpp +++ b/Code/Framework/AzFramework/AzFramework/Windowing/NativeWindow.cpp @@ -10,6 +10,17 @@ #include +void OnVsyncIntervalChanged(uint32_t const& interval) +{ + AzFramework::WindowNotificationBus::Broadcast( + &AzFramework::WindowNotificationBus::Events::OnVsyncIntervalChanged, AZ::GetClamp(interval, 0u, 4u)); +} + +// NOTE: On change, broadcasts the new requested vsync interval to all windows. +// The value of the vsync interval is constrained between 0 and 4 +// Vsync intervals greater than 1 are not currently supported on the Vulkan RHI (see #2061 for discussion) +AZ_CVAR(uint32_t, vsync_interval, 1, OnVsyncIntervalChanged, AZ::ConsoleFunctorFlags::Null, "Set swapchain vsync interval"); + namespace AzFramework { ////////////////////////////////////////////////////////////////////////// @@ -122,6 +133,16 @@ namespace AzFramework return m_pimpl->GetDpiScaleFactor(); } + uint32_t NativeWindow::GetDisplayRefreshRate() const + { + return m_pimpl->GetDisplayRefreshRate(); + } + + uint32_t NativeWindow::GetSyncInterval() const + { + return vsync_interval; + } + /*static*/ bool NativeWindow::GetFullScreenStateOfDefaultWindow() { NativeWindowHandle defaultWindowHandle = nullptr; @@ -240,4 +261,10 @@ namespace AzFramework return 1.0f; } + uint32_t NativeWindow::Implementation::GetDisplayRefreshRate() const + { + // Default to 60 + return 60; + } + } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Windowing/NativeWindow.h b/Code/Framework/AzFramework/AzFramework/Windowing/NativeWindow.h index 52157d920f..7479b0d1e1 100644 --- a/Code/Framework/AzFramework/AzFramework/Windowing/NativeWindow.h +++ b/Code/Framework/AzFramework/AzFramework/Windowing/NativeWindow.h @@ -130,6 +130,8 @@ namespace AzFramework bool CanToggleFullScreenState() const override; void ToggleFullScreenState() override; float GetDpiScaleFactor() const override; + uint32_t GetSyncInterval() const override; + uint32_t GetDisplayRefreshRate() const override; //! Get the full screen state of the default window. //! \return True if the default window is currently in full screen, false otherwise. @@ -172,6 +174,7 @@ namespace AzFramework virtual void SetFullScreenState(bool fullScreenState); virtual bool CanToggleFullScreenState() const; virtual float GetDpiScaleFactor() const; + virtual uint32_t GetDisplayRefreshRate() const; protected: uint32_t m_width = 0; diff --git a/Code/Framework/AzFramework/AzFramework/Windowing/WindowBus.h b/Code/Framework/AzFramework/AzFramework/Windowing/WindowBus.h index 776cd43787..d3bd0ce82c 100644 --- a/Code/Framework/AzFramework/AzFramework/Windowing/WindowBus.h +++ b/Code/Framework/AzFramework/AzFramework/Windowing/WindowBus.h @@ -74,6 +74,12 @@ namespace AzFramework //! to a "standard" value of 96, the default for Windows in a DPI unaware setting. This can //! be used to scale user interface elements to ensure legibility on high density displays. virtual float GetDpiScaleFactor() const = 0; + + //! Returns the sync interval which tells the drivers the number of v-blanks to synchronize with + virtual uint32_t GetSyncInterval() const = 0; + + //! Returns the refresh rate of the main display + virtual uint32_t GetDisplayRefreshRate() const = 0; }; using WindowRequestBus = AZ::EBus; @@ -101,6 +107,9 @@ namespace AzFramework //! This is called when vsync interval is changed. virtual void OnVsyncIntervalChanged(uint32_t interval) { AZ_UNUSED(interval); }; + + //! This is called if the main display's refresh rate changes + virtual void OnRefreshRateChanged([[maybe_unused]] uint32_t refreshRate) {} }; using WindowNotificationBus = AZ::EBus; diff --git a/Code/Framework/AzFramework/Platform/Android/AzFramework/Windowing/NativeWindow_Android.cpp b/Code/Framework/AzFramework/Platform/Android/AzFramework/Windowing/NativeWindow_Android.cpp index 8da63e9a5e..e655435011 100644 --- a/Code/Framework/AzFramework/Platform/Android/AzFramework/Windowing/NativeWindow_Android.cpp +++ b/Code/Framework/AzFramework/Platform/Android/AzFramework/Windowing/NativeWindow_Android.cpp @@ -25,7 +25,7 @@ namespace AzFramework const WindowGeometry& geometry, const WindowStyleMasks& styleMasks) override; NativeWindowHandle GetWindowHandle() const override; - + uint32_t GetDisplayRefreshRate() const override; private: ANativeWindow* m_nativeWindow = nullptr; }; @@ -55,4 +55,9 @@ namespace AzFramework return reinterpret_cast(m_nativeWindow); } + uint32_t NativeWindowImpl_Android::GetDisplayRefreshRate() const + { + // Using 60 for now until proper support is added + return 60; + } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/Platform/Linux/AzFramework/Windowing/NativeWindow_Linux.cpp b/Code/Framework/AzFramework/Platform/Linux/AzFramework/Windowing/NativeWindow_Linux.cpp index 5d738f8bdd..0ab1281eda 100644 --- a/Code/Framework/AzFramework/Platform/Linux/AzFramework/Windowing/NativeWindow_Linux.cpp +++ b/Code/Framework/AzFramework/Platform/Linux/AzFramework/Windowing/NativeWindow_Linux.cpp @@ -23,6 +23,7 @@ namespace AzFramework const WindowGeometry& geometry, const WindowStyleMasks& styleMasks) override; NativeWindowHandle GetWindowHandle() const override; + uint32_t GetDisplayRefreshRate() const override; }; NativeWindow::Implementation* NativeWindow::Implementation::Create() @@ -44,4 +45,9 @@ namespace AzFramework return nullptr; } + uint32_t NativeWindowImpl_Linux::GetDisplayRefreshRate() const + { + //Using 60 for now until proper support is added + return 60; + } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm index 6e6b801e79..2f9e3ab934 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm @@ -34,12 +34,14 @@ namespace AzFramework bool GetFullScreenState() const override; void SetFullScreenState(bool fullScreenState) override; bool CanToggleFullScreenState() const override { return true; } + uint32_t GetMainDisplayRefreshRate() const override; private: static NSWindowStyleMask ConvertToNSWindowStyleMask(const WindowStyleMasks& styleMasks); NSWindow* m_nativeWindow; NSString* m_windowTitle; + uint32_t m_mainDisplayRefreshRate = 0; }; NativeWindow::Implementation* NativeWindow::Implementation::Create() @@ -76,6 +78,17 @@ namespace AzFramework // Make the window active [m_nativeWindow makeKeyAndOrderFront:nil]; m_nativeWindow.title = m_windowTitle; + + CGDirectDisplayID display = CGMainDisplayID(); + CGDisplayModeRef currentMode = CGDisplayCopyDisplayMode(display); + m_mainDisplayRefreshRate = CGDisplayModeGetRefreshRate(currentMode); + + // Assume 60hz if 0 is returned. + // This can happen on OSX. In future we can hopefully use maximumFramesPerSecond which wont have this issue + if (m_mainDisplayRefreshRate == 0) + { + m_mainDisplayRefreshRate = 60; + } } NativeWindowHandle NativeWindowImpl_Darwin::GetWindowHandle() const @@ -128,4 +141,9 @@ namespace AzFramework const NSWindowStyleMask defaultMask = NSWindowStyleMaskResizable | NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable; return nativeMask ? nativeMask : defaultMask; } + + uint32_t NativeWindowImpl_Darwin::GetMainDisplayRefreshRate() const + { + return m_mainDisplayRefreshRate; + } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp index 22a293891c..2c1d97dcf6 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Windowing/NativeWindow_Windows.cpp @@ -37,6 +37,7 @@ namespace AzFramework void SetFullScreenState(bool fullScreenState) override; bool CanToggleFullScreenState() const override { return true; } float GetDpiScaleFactor() const override; + uint32_t GetDisplayRefreshRate() const override; private: static DWORD ConvertToWin32WindowStyleMask(const WindowStyleMasks& styleMasks); @@ -56,6 +57,7 @@ namespace AzFramework using GetDpiForWindowType = UINT(HWND hwnd); GetDpiForWindowType* m_getDpiFunction = nullptr; + uint32_t m_mainDisplayRefreshRate = 0; }; const wchar_t* NativeWindowImpl_Win32::s_defaultClassName = L"O3DEWin32Class"; @@ -144,6 +146,10 @@ namespace AzFramework { SetWindowLongPtr(m_win32Handle, GWLP_USERDATA, reinterpret_cast(this)); } + + DEVMODE DisplayConfig; + EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &DisplayConfig); + m_mainDisplayRefreshRate = DisplayConfig.dmDisplayFrequency; } void NativeWindowImpl_Win32::Activate() @@ -263,6 +269,15 @@ namespace AzFramework WindowNotificationBus::Event(nativeWindowImpl->GetWindowHandle(), &WindowNotificationBus::Events::OnDpiScaleFactorChanged, newScaleFactor); break; } + case WM_WINDOWPOSCHANGED: + { + DEVMODE DisplayConfig; + EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &DisplayConfig); + uint32_t refreshRate = DisplayConfig.dmDisplayFrequency; + WindowNotificationBus::Event( + nativeWindowImpl->GetWindowHandle(), &WindowNotificationBus::Events::OnRefreshRateChanged, refreshRate); + break; + } default: return DefWindowProc(hWnd, message, wParam, lParam); break; @@ -367,6 +382,11 @@ namespace AzFramework return aznumeric_cast(dotsPerInch) / aznumeric_cast(defaultDotsPerInch); } + uint32_t NativeWindowImpl_Win32::GetDisplayRefreshRate() const + { + return m_mainDisplayRefreshRate; + } + void NativeWindowImpl_Win32::EnterBorderlessWindowFullScreen() { if (m_isInBorderlessWindowFullScreenState) diff --git a/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm b/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm index b14db37d23..3c829ec055 100644 --- a/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm +++ b/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm @@ -27,9 +27,11 @@ namespace AzFramework const WindowGeometry& geometry, const WindowStyleMasks& styleMasks) override; NativeWindowHandle GetWindowHandle() const override; - + uint32_t GetMainDisplayRefreshRate() const override; + private: UIWindow* m_nativeWindow; + uint32_t m_mainDisplayRefreshRate = 0; }; NativeWindow::Implementation* NativeWindow::Implementation::Create() @@ -56,6 +58,7 @@ namespace AzFramework m_width = geometry.m_width; m_height = geometry.m_height; + m_mainDisplayRefreshRate = [[UIScreen mainScreen] maximumFramesPerSecond]; } NativeWindowHandle NativeWindowImpl_Ios::GetWindowHandle() const @@ -63,5 +66,9 @@ namespace AzFramework return m_nativeWindow; } + uint32_t NativeWindowImpl_Ios::GetMainDisplayRefreshRate() const + { + return m_mainDisplayRefreshRate; + } } // namespace AzFramework diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h index 4232658980..e7ad98c074 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h @@ -125,7 +125,6 @@ namespace AZ Format GetNearestSupportedFormat(Format requestedFormat, FormatCapabilities requestedCapabilities) const; //! Small API to support getting supported/working swapchain formats for a window. - //! [GFX TODO]ATOM-1125] [RHI] Device::GetValidSwapChainImageFormats() //! Returns the set of supported formats for swapchain images. virtual AZStd::vector GetValidSwapChainImageFormats(const WindowHandle& windowHandle) const; diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/NsightAftermath_Windows.cpp b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/NsightAftermath_Windows.cpp index 4ee35b7675..199efbb139 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/NsightAftermath_Windows.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/NsightAftermath_Windows.cpp @@ -85,7 +85,7 @@ namespace Aftermath #if defined(USE_NSIGHT_AFTERMATH) AZStd::vector cntxtHandles = static_cast(crashTracker)->GetContextHandles(); GFSDK_Aftermath_ContextData* outContextData = new GFSDK_Aftermath_ContextData[cntxtHandles.size()]; - GFSDK_Aftermath_Result result = GFSDK_Aftermath_GetData(cntxtHandles.size(), cntxtHandles.data(), outContextData); + GFSDK_Aftermath_Result result = GFSDK_Aftermath_GetData(static_cast(cntxtHandles.size()), cntxtHandles.data(), outContextData); AssertOnError(result); for (int i = 0; i < cntxtHandles.size(); i++) { diff --git a/Gems/Atom/RHI/Metal/Code/Source/Platform/Mac/RHI/Conversions_Mac.h b/Gems/Atom/RHI/Metal/Code/Source/Platform/Mac/RHI/Conversions_Mac.h index cb1f48cfea..a4dc13a6f1 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/Platform/Mac/RHI/Conversions_Mac.h +++ b/Gems/Atom/RHI/Metal/Code/Source/Platform/Mac/RHI/Conversions_Mac.h @@ -5,6 +5,8 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ +#pragma once + namespace AZ { namespace Metal diff --git a/Gems/Atom/RHI/Metal/Code/Source/Platform/iOS/RHI/Conversions_iOS.h b/Gems/Atom/RHI/Metal/Code/Source/Platform/iOS/RHI/Conversions_iOS.h index cb1f48cfea..a4dc13a6f1 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/Platform/iOS/RHI/Conversions_iOS.h +++ b/Gems/Atom/RHI/Metal/Code/Source/Platform/iOS/RHI/Conversions_iOS.h @@ -5,6 +5,8 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ +#pragma once + namespace AZ { namespace Metal diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp index dbd2204e93..5591bcc843 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp @@ -77,7 +77,6 @@ namespace AZ m_samplerCache = [[NSCache alloc]init]; [m_samplerCache setName:@"SamplerCache"]; - return RHI::ResultCode::Success; } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp index 638f9bd184..df0961564d 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp @@ -74,21 +74,16 @@ namespace AZ AddSubView(); } - m_refreshRate = Platform::GetRefreshRate(); - - //Assume 60hz if 0 is returned. - //Internal OSX displays have 'flexible' refresh rates, with a max of 60Hz - but report 0hz - if (m_refreshRate < 0.1f) - { - m_refreshRate = 60.0f; - } - m_drawables.resize(descriptor.m_dimensions.m_imageCount); if (nativeDimensions) { *nativeDimensions = descriptor.m_dimensions; } + + AzFramework::WindowRequestBus::EventResult( + m_refreshRate, m_nativeWindow, &AzFramework::WindowRequestBus::Events::GetDisplayRefreshRate); + return RHI::ResultCode::Success; } @@ -160,7 +155,10 @@ namespace AZ const uint32_t currentImageIndex = GetCurrentImageIndex(); //Preset the drawable - Platform::PresentInternal(m_mtlCommandBuffer, m_drawables[currentImageIndex], GetDescriptor().m_verticalSyncInterval, m_refreshRate); + Platform::PresentInternal( + m_mtlCommandBuffer, + m_drawables[currentImageIndex], GetDescriptor().m_verticalSyncInterval, + m_refreshRate); [m_drawables[currentImageIndex] release]; m_drawables[currentImageIndex] = nil; diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.h index 571f12faf8..51dfe9258b 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.h @@ -53,7 +53,7 @@ namespace AZ id m_mtlDevice = nil; NativeWindowType* m_nativeWindow = nullptr; AZStd::vector> m_drawables; - float m_refreshRate = 0.0f; + uint32_t m_refreshRate = 0; }; } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/WindowContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/WindowContext.cpp index 7c269b86d4..9720a88176 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/WindowContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/WindowContext.cpp @@ -17,19 +17,6 @@ #include #include - -void OnVsyncIntervalChanged(uint32_t const& interval) -{ - AzFramework::WindowNotificationBus::Broadcast( - &AzFramework::WindowNotificationBus::Events::OnVsyncIntervalChanged, - AZ::GetClamp(interval, 0u, 4u)); -} - -// NOTE: On change, broadcasts the new requested vsync interval to all windows. -// The value of the vsync interval is constrained between 0 and 4 -// Vsync intervals greater than 1 are not currently supported on the Vulkan RHI (see #2061 for discussion) -AZ_CVAR(uint32_t, rpi_vsync_interval, 1, OnVsyncIntervalChanged, AZ::ConsoleFunctorFlags::Null, "Set swapchain vsync interval"); - namespace AZ { namespace RPI @@ -158,9 +145,13 @@ namespace AZ const RHI::WindowHandle windowHandle = RHI::WindowHandle(reinterpret_cast(m_windowHandle)); + uint32_t syncInterval = 1; + AzFramework::WindowRequestBus::EventResult( + syncInterval, m_windowHandle, &AzFramework::WindowRequestBus::Events::GetSyncInterval); + RHI::SwapChainDescriptor descriptor; descriptor.m_window = windowHandle; - descriptor.m_verticalSyncInterval = rpi_vsync_interval; + descriptor.m_verticalSyncInterval = syncInterval; descriptor.m_dimensions.m_imageWidth = width; descriptor.m_dimensions.m_imageHeight = height; descriptor.m_dimensions.m_imageCount = 3; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h index cd670f3048..bb26e116af 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -121,6 +121,8 @@ namespace AtomToolsFramework bool CanToggleFullScreenState() const override; void ToggleFullScreenState() override; float GetDpiScaleFactor() const override; + uint32_t GetSyncInterval() const override; + uint32_t GetDisplayRefreshRate() const; protected: // AzFramework::InputChannelEventListener ... diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index 5167e3d3f6..bf356d2b99 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -465,4 +465,14 @@ namespace AtomToolsFramework { return aznumeric_cast(devicePixelRatioF()); } + + uint32_t RenderViewportWidget::GetDisplayRefreshRate() const + { + return 60; + } + + uint32_t RenderViewportWidget::GetSyncInterval() const + { + return 1; + } } //namespace AtomToolsFramework From cc3d2e9969cfc2f3ba00ebeaa9405d1d1886b37c Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Thu, 12 Aug 2021 12:40:03 -0700 Subject: [PATCH 171/205] [redcode/crythread-2nd-pass] replaced instances of AZStd::lock_guard<> with AZStd::scoped_lock as per feedback Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Editor/CryEdit.cpp | 3 +-- Code/Editor/GameExporter.cpp | 2 +- Code/Editor/IEditorImpl.cpp | 6 +++--- .../PerforcePlugin/PerforceSourceControl.cpp | 2 +- Code/Legacy/CryCommon/CryAssert_Linux.h | 2 +- Code/Legacy/CrySystem/DebugCallStack.cpp | 6 +++--- Code/Legacy/CrySystem/Log.cpp | 8 ++++---- .../RemoteConsole/Core/RemoteConsoleCore.cpp | 17 +++++++++-------- 8 files changed, 23 insertions(+), 23 deletions(-) diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index 25a6313efe..8444f81317 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -938,10 +938,9 @@ void CCryEditApp::ShowSplashScreen(CCryEditApp* app) QObject::connect(splashScreen, &QObject::destroyed, splashScreen, [=] { - g_splashScreenStateLock.lock(); + AZStd::scoped_lock lock(g_splashScreenStateLock); g_pInitializeUIInfo = nullptr; g_splashScreen = nullptr; - g_splashScreenStateLock.unlock(); }); } diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp index 3cd64f9fed..415103e10d 100644 --- a/Code/Editor/GameExporter.cpp +++ b/Code/Editor/GameExporter.cpp @@ -136,7 +136,7 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE m_settings.SetHiQuality(); } - AZStd::lock_guard autoLock(CGameEngine::GetPakModifyMutex()); + AZStd::scoped_lock autoLock(CGameEngine::GetPakModifyMutex()); // Close this pak file. if (!CloseLevelPack(m_levelPak, true)) diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp index 7800c7943e..1459139f66 100644 --- a/Code/Editor/IEditorImpl.cpp +++ b/Code/Editor/IEditorImpl.cpp @@ -252,7 +252,7 @@ void CEditorImpl::Uninitialize() void CEditorImpl::UnloadPlugins() { - AZStd::lock_guard lock(m_pluginMutex); + AZStd::scoped_lock lock(m_pluginMutex); // Flush core buses. We're about to unload DLLs and need to ensure we don't have module-owned functions left behind. AZ::Data::AssetBus::ExecuteQueuedEvents(); @@ -273,7 +273,7 @@ void CEditorImpl::UnloadPlugins() void CEditorImpl::LoadPlugins() { - AZStd::lock_guard lock(m_pluginMutex); + AZStd::scoped_lock lock(m_pluginMutex); static const QString editor_plugins_folder("EditorPlugins"); @@ -1460,7 +1460,7 @@ void CEditorImpl::UnregisterNotifyListener(IEditorNotifyListener* listener) ISourceControl* CEditorImpl::GetSourceControl() { - AZStd::lock_guard lock(m_pluginMutex); + AZStd::scoped_lock lock(m_pluginMutex); if (m_pSourceControl) { diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp index 34514b8ef1..10c43c3d1b 100644 --- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp +++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp @@ -56,7 +56,7 @@ void CPerforceSourceControl::ShowSettings() void CPerforceSourceControl::SetSourceControlState(SourceControlState state) { - AZStd::lock_guard lock(g_cPerforceValues); + AZStd::scoped_lock lock(g_cPerforceValues); switch (state) { diff --git a/Code/Legacy/CryCommon/CryAssert_Linux.h b/Code/Legacy/CryCommon/CryAssert_Linux.h index 355194caba..112c60a80c 100644 --- a/Code/Legacy/CryCommon/CryAssert_Linux.h +++ b/Code/Legacy/CryCommon/CryAssert_Linux.h @@ -80,7 +80,7 @@ bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, b if (!gEnv->bNoAssertDialog && !gEnv->bIgnoreAllAsserts) { - AZStd::lock_guard lk (lock); + AZStd::scoped_lock lk(lock); snprintf(gs_command_str, max_len, "xterm -geometry 100x20 -n 'Assert Dialog [Linux Launcher]' -T 'Assert Dialog [Linux Launcher]' -e 'BinLinux/assert_term \"%s\" \"%s\" %d \"%s\"; echo \"$?\" > .assert_return'", szCondition, (file_len > 60) ? szFile + (file_len - 61) : szFile, line, gs_szMessage); int ret = system(gs_command_str); diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp index 640afe8da1..cdfc5de21e 100644 --- a/Code/Legacy/CrySystem/DebugCallStack.cpp +++ b/Code/Legacy/CrySystem/DebugCallStack.cpp @@ -154,13 +154,13 @@ void DebugCallStack::SetUserDialogEnable(const bool bUserDialogEnable) DWORD g_idDebugThreads[10]; const char* g_nameDebugThreads[10]; int g_nDebugThreads = 0; -AZStd::spin_mutex g_lockThreadDumpList = 0; +AZStd::spin_mutex g_lockThreadDumpList; void MarkThisThreadForDebugging(const char* name) { EBUS_EVENT(AZ::Debug::EventTraceDrillerSetupBus, SetThreadName, AZStd::this_thread::get_id(), name); - AZStd::lock_guard lock(g_lockThreadDumpList); + AZStd::scoped_lock lock(g_lockThreadDumpList); DWORD id = GetCurrentThreadId(); if (g_nDebugThreads == sizeof(g_idDebugThreads) / sizeof(g_idDebugThreads[0])) { @@ -180,7 +180,7 @@ void MarkThisThreadForDebugging(const char* name) void UnmarkThisThreadFromDebugging() { - AZStd::lock_guard lock(g_lockThreadDumpList); + AZStd::scoped_lock lock(g_lockThreadDumpList); DWORD id = GetCurrentThreadId(); for (int i = g_nDebugThreads - 1; i >= 0; i--) { diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp index 2417c58d4f..d248274b1d 100644 --- a/Code/Legacy/CrySystem/Log.cpp +++ b/Code/Legacy/CrySystem/Log.cpp @@ -810,13 +810,13 @@ void CLog::PushAssetScopeName(const char* sAssetType, const char* sName) SAssetScopeInfo as; as.sType = sAssetType; as.sName = sName; - AZStd::lock_guard scope_lock(m_assetScopeQueueLock); + AZStd::scoped_lock scope_lock(m_assetScopeQueueLock); m_assetScopeQueue.push_back(as); } void CLog::PopAssetScopeName() { - AZStd::lock_guard scope_lock(m_assetScopeQueueLock); + AZStd::scoped_lock scope_lock(m_assetScopeQueueLock); assert(!m_assetScopeQueue.empty()); if (!m_assetScopeQueue.empty()) { @@ -827,7 +827,7 @@ void CLog::PopAssetScopeName() ////////////////////////////////////////////////////////////////////////// const char* CLog::GetAssetScopeString() { - AZStd::lock_guard scope_lock(m_assetScopeQueueLock); + AZStd::scoped_lock scope_lock(m_assetScopeQueueLock); m_assetScopeString.clear(); for (size_t i = 0; i < m_assetScopeQueue.size(); i++) @@ -1450,7 +1450,7 @@ void CLog::Update() { if (!m_threadSafeMsgQueue.empty()) { - AZStd::lock_guard lock(m_threadSafeMsgQueue.get_lock()); // Get the lock and hold onto it until we clear the entire queue (prevents other threads adding more things in while we clear it) + AZStd::scoped_lock lock(m_threadSafeMsgQueue.get_lock()); // Get the lock and hold onto it until we clear the entire queue (prevents other threads adding more things in while we clear it) // Must be called from main thread SLogMsg msg; while (m_threadSafeMsgQueue.try_pop(msg)) diff --git a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp index b59f697467..5a137d1664 100644 --- a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp +++ b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp @@ -133,19 +133,20 @@ void SRemoteServer::StopServer() AZ::AzSock::CloseSocket(m_socket); m_socket = SOCKET_ERROR; { - AZStd::lock_guard lock(m_mutex); + AZStd::scoped_lock lock(m_mutex); for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it) { it->pClient->StopClient(); } } AZStd::unique_lock lock(m_mutex); - m_stopCondition.wait(lock, [this] { return m_clients.empty(); });} + m_stopCondition.wait(lock, [this] { return m_clients.empty(); }); +} ///////////////////////////////////////////////////////////////////////////////////////////// void SRemoteServer::ClientDone(SRemoteClient* pClient) { - AZStd::lock_guard lock(m_mutex); + AZStd::scoped_lock lock(m_mutex); for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it) { if (it->pClient == pClient) @@ -253,7 +254,7 @@ void SRemoteServer::Run() continue; } - AZStd::lock_guard lock(m_mutex); + AZStd::scoped_lock lock(m_mutex); SRemoteClient* pClient = new SRemoteClient(this); m_clients.push_back(SRemoteClientInfo(pClient)); pClient->StartClient(sClient); @@ -266,7 +267,7 @@ void SRemoteServer::Run() ///////////////////////////////////////////////////////////////////////////////////////////// void SRemoteServer::AddEvent(IRemoteEvent* pEvent) { - AZStd::lock_guard lock(m_mutex); + AZStd::scoped_lock lock(m_mutex); for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it) { it->pEvents->push_back(pEvent->Clone()); @@ -277,7 +278,7 @@ void SRemoteServer::AddEvent(IRemoteEvent* pEvent) ///////////////////////////////////////////////////////////////////////////////////////////// void SRemoteServer::GetEvents(TEventBuffer& buffer) { - AZStd::lock_guard lock(m_mutex); + AZStd::scoped_lock lock(m_mutex); buffer = m_eventBuffer; m_eventBuffer.clear(); } @@ -287,7 +288,7 @@ bool SRemoteServer::WriteBuffer(SRemoteClient* pClient, char* buffer, int& size { IRemoteEvent* pEvent = nullptr; { - AZStd::lock_guard lock(m_mutex); + AZStd::scoped_lock lock(m_mutex); for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it) { if (it->pClient == pClient) @@ -330,7 +331,7 @@ bool SRemoteServer::ReadBuffer(const char* buffer, int data) { if (event->GetType() != eCET_Noop) { - AZStd::lock_guard lock(m_mutex); + AZStd::scoped_lock lock(m_mutex); m_eventBuffer.push_back(event); } else From ff659fbbb6eff884139641d78fad738e3d19386d Mon Sep 17 00:00:00 2001 From: jonawals Date: Thu, 12 Aug 2021 20:48:23 +0100 Subject: [PATCH 172/205] Tiaf bucket top level fix (#3085) * Revert to regular run when invalid commits used. * Cirrect s3 logging of last commit hash storage * Add s3 top level url and build number script params. * Use existing REPOSITORY_NAME env var. Signed-off-by: John --- .../build/Platform/Windows/build_config.json | 2 +- scripts/build/TestImpactAnalysis/git_utils.py | 6 ++++ .../build/TestImpactAnalysis/mars_utils.py | 14 ++++++---- scripts/build/TestImpactAnalysis/tiaf.py | 17 +++++++---- .../build/TestImpactAnalysis/tiaf_driver.py | 28 +++++++++++++++++-- .../tiaf_persistent_storage.py | 2 +- .../tiaf_persistent_storage_s3.py | 6 ++-- 7 files changed, 57 insertions(+), 18 deletions(-) diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index 4c275a49cf..0268412aea 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -89,7 +89,7 @@ "CONFIGURATION": "profile", "SCRIPT_PATH": "scripts/build/TestImpactAnalysis/tiaf_driver.py", "SCRIPT_PARAMETERS": - "--config=\"!OUTPUT_DIRECTORY!/bin/TestImpactFramework/profile/Persistent/tiaf.json\" --src-branch=!BRANCH_NAME! --dst-branch=!CHANGE_TARGET! --commit=!CHANGE_ID! --s3-bucket=!TEST_IMPACT_S3_BUCKET! --mars-index-prefix=jonawals --suite=main --test-failure-policy=continue" + "--config=\"!OUTPUT_DIRECTORY!/bin/TestImpactFramework/profile/Persistent/tiaf.json\" --src-branch=!BRANCH_NAME! --dst-branch=!CHANGE_TARGET! --commit=!CHANGE_ID! --s3-bucket=!TEST_IMPACT_S3_BUCKET! --mars-index-prefix=jonawals --s3-top-level-dir=!REPOSITORY_NAME! --build-number=!BUILD_NUMBER! --suite=main --test-failure-policy=continue" } }, "debug_vs2019": { diff --git a/scripts/build/TestImpactAnalysis/git_utils.py b/scripts/build/TestImpactAnalysis/git_utils.py index ddc17ca146..61380ecb74 100644 --- a/scripts/build/TestImpactAnalysis/git_utils.py +++ b/scripts/build/TestImpactAnalysis/git_utils.py @@ -14,6 +14,7 @@ import pathlib class Repo: def __init__(self, repo_path: str): self._repo = git.Repo(repo_path) + self._remote_url = self._repo.remotes[0].config_reader.get("url") # Returns the current branch @property @@ -21,6 +22,11 @@ class Repo: branch = self._repo.active_branch return branch.name + # Returns the remote URL + @property + def remote_url(self): + return self._remote_url + def create_diff_file(self, src_commit_hash: str, dst_commit_hash: str, output_path: pathlib.Path, multi_branch: bool): """ Attempts to create a diff from the src and dst commits and write to the specified output file. diff --git a/scripts/build/TestImpactAnalysis/mars_utils.py b/scripts/build/TestImpactAnalysis/mars_utils.py index e2394ed6e1..8fa1f123c7 100644 --- a/scripts/build/TestImpactAnalysis/mars_utils.py +++ b/scripts/build/TestImpactAnalysis/mars_utils.py @@ -14,6 +14,7 @@ from tiaf_logger import get_logger logger = get_logger(__file__) MARS_JOB_KEY = "job" +BUILD_NUMBER_KEY = "build_number" SRC_COMMIT_KEY = "src_commit" DST_COMMIT_KEY = "dst_commit" COMMIT_DISTANCE_KEY = "commit_distance" @@ -175,12 +176,14 @@ def get_duration_in_seconds(duration_in_milliseconds: int): return duration_in_milliseconds * 0.001 -def generate_mars_job(tiaf_result, driver_args): +def generate_mars_job(tiaf_result, driver_args, build_number: int): """ Generates a MARS job document using the job meta-data used to drive the TIAF sequence. - @param tiaf_result: The result object generated by the TIAF script. - @param driver_args: The arguments specified to the driver script. + @param tiaf_result: The result object generated by the TIAF script. + @param driver_args: The arguments specified to the driver script. + @param driver_args: The arguments specified to the driver script. + @param build_number: The build number this job corresponds to. @return: The MARS job document with the job meta-data. """ @@ -203,6 +206,7 @@ def generate_mars_job(tiaf_result, driver_args): ]} mars_job[DRIVER_ARGS_KEY] = driver_args + mars_job[BUILD_NUMBER_KEY] = build_number return mars_job def generate_test_run_list(test_runs): @@ -418,7 +422,7 @@ def generate_mars_test_targets(sequence_report: dict, mars_job: dict, t0_timesta return mars_test_targets -def transmit_report_to_mars(mars_index_prefix: str, tiaf_result: dict, driver_args: list): +def transmit_report_to_mars(mars_index_prefix: str, tiaf_result: dict, driver_args: list, build_number: int): """ Transforms the TIAF result into the appropriate MARS documents and transmits them to MARS. @@ -434,7 +438,7 @@ def transmit_report_to_mars(mars_index_prefix: str, tiaf_result: dict, driver_ar t0_timestamp = datetime.datetime.now().timestamp() # Generate and transmit the MARS job document - mars_job = generate_mars_job(tiaf_result, driver_args) + mars_job = generate_mars_job(tiaf_result, driver_args, build_number) filebeat.send_event(mars_job, f"{mars_index_prefix}.tiaf.job") if tiaf_result[REPORT_KEY]: diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index 11ca24f830..6a43ad3c70 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -161,7 +161,7 @@ class TestImpact: result["change_list"] = self._change_list return result - def run(self, commit: str, src_branch: str, dst_branch: str, s3_bucket: str, suite: str, test_failure_policy: str, safe_mode: bool, test_timeout: int, global_timeout: int): + def run(self, commit: str, src_branch: str, dst_branch: str, s3_bucket: str, s3_top_level_dir: str, suite: str, test_failure_policy: str, safe_mode: bool, test_timeout: int, global_timeout: int): """ Determins the type of sequence to run based on the commit, source branch and test branch before running the sequence with the specified values. @@ -170,6 +170,7 @@ class TestImpact: @param src_branch: If not equal to dst_branch, the branch that is being built. @param dst_branch: If not equal to src_branch, the destination branch for the PR being built. @param s3_bucket: Location of S3 bucket to use for persistent storage, otherwise local disk storage will be used. + @param s3_top_level_dir: Top level directory to use in the S3 bucket. @param suite: Test suite to run. @param test_failure_policy: Test failure policy for regular and test impact sequences (ignored when seeding). @param safe_mode: Flag to run impact analysis tests in safe mode (ignored when seeding). @@ -218,7 +219,7 @@ class TestImpact: try: # Persistent storage location if s3_bucket: - persistent_storage = PersistentStorageS3(self._config, suite, s3_bucket, self._source_of_truth_branch) + persistent_storage = PersistentStorageS3(self._config, suite, s3_bucket, s3_top_level_dir, self._source_of_truth_branch) else: persistent_storage = PersistentStorageLocal(self._config, suite) except SystemError as e: @@ -226,14 +227,20 @@ class TestImpact: persistent_storage = None if persistent_storage: + # Flag to signify whether or not this is a re-run (multiple runs of the same commit) + # Right now, we don't fully support re-runs but in the future we will have an extra subfolder for each commit hash with the + # last run hash that was used for the first run for the commit so we can retreive the same reference point for building the + # change list to ensure each subsequent run is using the same data but for the time being, just perform a regular run + is_rerun = False if persistent_storage.has_historic_data: logger.info("Historic data found.") self._src_commit = persistent_storage.last_commit_hash - # Perform some basic sanity checks on the commit hashes to ensure confidence in the integrity of of the environment + # Perform some basic sanity checks on the commit hashes to ensure confidence in the integrity of the environment if self._src_commit == self._dst_commit: - logger.error(f"Source commit '{self._src_commit}' and destination commit '{self._dst_commit}', implying the integrity of the historic data is compromised.") + logger.info(f"Source commit '{self._src_commit}' and destination commit '{self._dst_commit}', implying this is a re-run. A regular sequence will instead be performed.") persistent_storage = None + is_rerun = True else: self._attempt_to_generate_change_list() else: @@ -261,7 +268,7 @@ class TestImpact: args.append(f"--changelist={self._change_list_path}") logger.info(f"Change list is set to '{self._change_list_path}'.") else: - if self._is_source_of_truth_branch: + if self._is_source_of_truth_branch and not is_rerun: # Use seed sequence (instrumented all tests) for coverage updating branches so we can generate the coverage bed for future sequences sequence_type = "seed" # We always continue after test failures when seeding to ensure we capture the coverage for all test targets diff --git a/scripts/build/TestImpactAnalysis/tiaf_driver.py b/scripts/build/TestImpactAnalysis/tiaf_driver.py index 5ad16abaa0..ad49d98102 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_driver.py +++ b/scripts/build/TestImpactAnalysis/tiaf_driver.py @@ -11,6 +11,7 @@ import mars_utils import sys import pathlib import traceback +import re from tiaf import TestImpact from tiaf_logger import get_logger @@ -66,13 +67,20 @@ def parse_args(): required=True ) - # S3 bucket + # S3 bucket name parser.add_argument( '--s3-bucket', help="Location of S3 bucket to use for persistent storage, otherwise local disk storage will be used", required=False ) + # S3 bucket top level directory + parser.add_argument( + '--s3-top-level-dir', + help="The top level directory to use in the S3 bucket", + required=False + ) + # MARS index prefix parser.add_argument( '--mars-index-prefix', @@ -80,6 +88,13 @@ def parse_args(): required=False ) + # Build number + parser.add_argument( + '--build-number', + help="The build number this run of TIAF corresponds to", + required=True + ) + # Test suite parser.add_argument( '--suite', @@ -127,12 +142,19 @@ if __name__ == "__main__": try: args = parse_args() + + s3_top_level_dir = None + if args.s3_top_level_dir: + s3_top_level_dir = args.s3_top_level_dir + else: + s3_top_level_dir = "tiaf" + tiaf = TestImpact(args.config) - tiaf_result = tiaf.run(args.commit, args.src_branch, args.dst_branch, args.s3_bucket, args.suite, args.test_failure_policy, args.safe_mode, args.test_timeout, args.global_timeout) + tiaf_result = tiaf.run(args.commit, args.src_branch, args.dst_branch, args.s3_bucket, s3_top_level_dir, args.suite, args.test_failure_policy, args.safe_mode, args.test_timeout, args.global_timeout) if args.mars_index_prefix: logger.info("Transmitting report to MARS...") - mars_utils.transmit_report_to_mars(args.mars_index_prefix, tiaf_result, sys.argv) + mars_utils.transmit_report_to_mars(args.mars_index_prefix, tiaf_result, sys.argv, args.build_number) logger.info("Complete!") # Non-gating will be removed from this script and handled at the job level in SPEC-7413 diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py index ec646ee484..1ee3ac7e8c 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py @@ -106,7 +106,7 @@ class PersistentStorage(ABC): historic_data_json = self._pack_historic_data(last_commit_hash) if historic_data_json: - logger.info(f"Attempting to store historic data with new last commit hash '{self._last_commit_hash}'...") + logger.info(f"Attempting to store historic data with new last commit hash '{last_commit_hash}'...") self._store_historic_data(historic_data_json) logger.info("The historic data was successfully stored.") diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py index 24101c7cba..1a279855ea 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py @@ -18,7 +18,7 @@ logger = get_logger(__file__) # Implementation of s3 bucket persistent storage class PersistentStorageS3(PersistentStorage): - def __init__(self, config: dict, suite: str, s3_bucket: str, branch: str): + def __init__(self, config: dict, suite: str, s3_bucket: str, root_dir: str, branch: str): """ Initializes the persistent storage with the specified s3 bucket. @@ -36,8 +36,8 @@ class PersistentStorageS3(PersistentStorage): # historic_data.json.zip is the file containing the coverage and meta-data of the last TIAF sequence run historic_data_file = f"historic_data.{object_extension}" - # The location of the data is in the form / so the build config of each branch gets its own historic data - self._dir = f'{branch}/{config["meta"]["build_config"]}' + # The location of the data is in the form // so the build config of each branch gets its own historic data + self._dir = f'{root_dir}/{branch}/{config["meta"]["build_config"]}' self._historic_data_key = f'{self._dir}/{historic_data_file}' logger.info(f"Attempting to retrieve historic data for branch '{branch}' at location '{self._historic_data_key}' on bucket '{s3_bucket}'...") From ecd3b015eea1eb49bab8d0eb02f43b16054f82c4 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Thu, 12 Aug 2021 15:10:33 -0500 Subject: [PATCH 173/205] Fixed Signed/Unsigned Mismatch fix in LyShine UiAnimViewAnimNode.cpp (#3062) Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp index 697820d75c..3646e5a413 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp @@ -1482,7 +1482,7 @@ bool CUiAnimViewAnimNode::PasteNodesFromClipboard(QWidget* context) const bool bLightAnimationSetActive = GetSequence()->GetFlags() & IUiAnimSequence::eSeqFlags_LightAnimationSet; const unsigned int numNodes = animNodesRoot->getChildCount(); - for (int i = 0; i < numNodes; ++i) + for (unsigned int i = 0; i < numNodes; ++i) { XmlNodeRef xmlNode = animNodesRoot->getChild(i); From c3ee798acc817aadc7b1bab8e51e67c3c31cfbf4 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Thu, 12 Aug 2021 14:18:10 -0700 Subject: [PATCH 174/205] [redcode/crythread-2nd-pass] updated condition variable handling in Remote Console runtime to cut out extra unlock/lock Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp index 5a137d1664..a4e7bd24fa 100644 --- a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp +++ b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp @@ -132,14 +132,12 @@ void SRemoteServer::StopServer() m_bAcceptClients = false; AZ::AzSock::CloseSocket(m_socket); m_socket = SOCKET_ERROR; - { - AZStd::scoped_lock lock(m_mutex); - for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it) - { - it->pClient->StopClient(); - } - } + AZStd::unique_lock lock(m_mutex); + for (TClients::iterator it = m_clients.begin(); it != m_clients.end(); ++it) + { + it->pClient->StopClient(); + } m_stopCondition.wait(lock, [this] { return m_clients.empty(); }); } From 11d5009f466d394b4f71a3f791f7073e2b65a00f Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 12 Aug 2021 16:31:39 -0500 Subject: [PATCH 175/205] Fixed creating entities in the viewport logic to use hit test detection. Signed-off-by: Chris Galvan --- Code/Editor/EditorViewportWidget.cpp | 3 +- .../SandboxIntegration.cpp | 2 +- Code/Editor/Viewport.cpp | 42 +++++++++++-------- Code/Editor/Viewport.h | 2 + 4 files changed, 28 insertions(+), 21 deletions(-) diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 9ef20e02fb..28e8cce33e 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -2697,8 +2697,7 @@ void EditorViewportWidget::RestoreViewportAfterGameMode() QString( tr("When leaving \" Game Mode \" the engine will automatically restore your camera position to the default position before you " "had entered Game mode.

If you dislike this setting you can always change this anytime in the global " - "preferences.

")) - .arg(EditorPreferencesGeneralRestoreViewportCameraSettingName); + "preferences.

")); QString restoreOnExitGameModePopupDisabledRegKey("Editor/AutoHide/ViewportCameraRestoreOnExitGameMode"); // Read the popup disabled registry value diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 2ed2a30f08..66c57361be 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -1452,7 +1452,7 @@ void SandboxIntegrationManager::ContextMenu_NewEntity() if (view) { const QPoint viewPoint(m_contextMenuViewPoint.GetX(), m_contextMenuViewPoint.GetY()); - worldPosition = LYVec3ToAZVec3(view->SnapToGrid(view->ViewToWorld(viewPoint))); + worldPosition = view->GetHitLocation(viewPoint); } CreateNewEntityAtPosition(worldPosition); diff --git a/Code/Editor/Viewport.cpp b/Code/Editor/Viewport.cpp index 2bc1b21216..873f555c80 100644 --- a/Code/Editor/Viewport.cpp +++ b/Code/Editor/Viewport.cpp @@ -46,24 +46,7 @@ void QtViewport::BuildDragDropContext(AzQtComponents::ViewportDragContext& conte PreWidgetRendering(); // required so that the current render cam is set. - Vec3 pos = Vec3(ZERO); - HitContext hit; - if (HitTest(pt, hit)) - { - pos = hit.raySrc + hit.rayDir * hit.dist; - pos = SnapToGrid(pos); - } - else - { - bool hitTerrain; - pos = ViewToWorld(pt, &hitTerrain); - if (hitTerrain) - { - pos.z = GetIEditor()->GetTerrainElevation(pos.x, pos.y); - } - pos = SnapToGrid(pos); - } - context.m_hitLocation = AZ::Vector3(pos.x, pos.y, pos.z); + context.m_hitLocation = GetHitLocation(pt); PostWidgetRendering(); } @@ -1154,6 +1137,29 @@ bool QtViewport::HitTest(const QPoint& point, HitContext& hitInfo) return false; } +AZ::Vector3 QtViewport::GetHitLocation(const QPoint& point) +{ + Vec3 pos = Vec3(ZERO); + HitContext hit; + if (HitTest(point, hit)) + { + pos = hit.raySrc + hit.rayDir * hit.dist; + pos = SnapToGrid(pos); + } + else + { + bool hitTerrain; + pos = ViewToWorld(point, &hitTerrain); + if (hitTerrain) + { + pos.z = GetIEditor()->GetTerrainElevation(pos.x, pos.y); + } + pos = SnapToGrid(pos); + } + + return AZ::Vector3(pos.x, pos.y, pos.z); +} + ////////////////////////////////////////////////////////////////////////// void QtViewport::SetZoomFactor(float fZoomFactor) { diff --git a/Code/Editor/Viewport.h b/Code/Editor/Viewport.h index 823b8c77b1..6b5bfb5c34 100644 --- a/Code/Editor/Viewport.h +++ b/Code/Editor/Viewport.h @@ -201,6 +201,7 @@ public: //! Performs hit testing of 2d point in view to find which object hit. virtual bool HitTest(const QPoint& point, HitContext& hitInfo) = 0; + virtual AZ::Vector3 GetHitLocation(const QPoint& point) = 0; virtual void MakeConstructionPlane(int axis) = 0; @@ -436,6 +437,7 @@ public: //! Performs hit testing of 2d point in view to find which object hit. bool HitTest(const QPoint& point, HitContext& hitInfo) override; + AZ::Vector3 GetHitLocation(const QPoint& point) override; //! Do 2D hit testing of line in world space. // pToCameraDistance is an optional output parameter in which distance from the camera to the line is returned. From 8f05c7aa2f9d63a46e5350a19587cf273492eee5 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Thu, 12 Aug 2021 16:42:18 -0700 Subject: [PATCH 176/205] Several build fixes --- .../Mac/AzFramework/Windowing/NativeWindow_Mac.mm | 2 +- .../iOS/AzFramework/Windowing/NativeWindow_ios.mm | 2 +- .../GridMate/Session/LANSession_Android.cpp | 1 + .../iOS/GridMate/Session/LANSession_iOS.cpp | 1 + Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm | 1 + .../Platform/Windows/Launcher_Windows.cpp | 1 + Code/Legacy/CryCommon/AppleSpecific.h | 15 +++++++++++++++ Code/Legacy/CryCommon/CryLibrary.h | 2 +- Code/Legacy/CryCommon/MacSpecific.h | 2 ++ .../Scheduler/TestImpactProcessScheduler.cpp | 2 +- .../Enumeration/TestImpactTestEnumerator.cpp | 2 +- Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp | 1 + 12 files changed, 27 insertions(+), 5 deletions(-) diff --git a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm index 2f9e3ab934..f9eef9170a 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm @@ -34,7 +34,7 @@ namespace AzFramework bool GetFullScreenState() const override; void SetFullScreenState(bool fullScreenState) override; bool CanToggleFullScreenState() const override { return true; } - uint32_t GetMainDisplayRefreshRate() const override; + uint32_t GetMainDisplayRefreshRate() const; private: static NSWindowStyleMask ConvertToNSWindowStyleMask(const WindowStyleMasks& styleMasks); diff --git a/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm b/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm index 3c829ec055..83e176b9ef 100644 --- a/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm +++ b/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm @@ -27,7 +27,7 @@ namespace AzFramework const WindowGeometry& geometry, const WindowStyleMasks& styleMasks) override; NativeWindowHandle GetWindowHandle() const override; - uint32_t GetMainDisplayRefreshRate() const override; + uint32_t GetMainDisplayRefreshRate() const; private: UIWindow* m_nativeWindow; diff --git a/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp b/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp index 05fb56dfc1..3fa2a369a6 100644 --- a/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp +++ b/Code/Framework/GridMate/Platform/Android/GridMate/Session/LANSession_Android.cpp @@ -7,6 +7,7 @@ */ #include +#include namespace GridMate { diff --git a/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp b/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp index 05fb56dfc1..3fa2a369a6 100644 --- a/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp +++ b/Code/Framework/GridMate/Platform/iOS/GridMate/Session/LANSession_iOS.cpp @@ -7,6 +7,7 @@ */ #include +#include namespace GridMate { diff --git a/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm b/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm index cfba0d8aac..cbd5a043e1 100644 --- a/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm +++ b/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm @@ -10,6 +10,7 @@ #include #include <../Common/Apple/Launcher_Apple.h> #include <../Common/UnixLike/Launcher_UnixLike.h> +#include #if AZ_TESTS_ENABLED diff --git a/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp b/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp index 5cc3070cdb..44426f6d01 100644 --- a/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp +++ b/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp @@ -9,6 +9,7 @@ #include #include +#include int APIENTRY WinMain([[maybe_unused]] HINSTANCE hInstance, [[maybe_unused]] HINSTANCE hPrevInstance, [[maybe_unused]] LPSTR lpCmdLine, [[maybe_unused]] int nCmdShow) { diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index c572250b26..cd3146403a 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -226,6 +226,21 @@ typedef uint64 __uint64; #define _PTRDIFF_T_DEFINED 1 +typedef union _LARGE_INTEGER +{ + struct + { + DWORD LowPart; + LONG HighPart; + }; + struct + { + DWORD LowPart; + LONG HighPart; + } u; + long long QuadPart; +} LARGE_INTEGER; + #define _A_RDONLY (0x01) /* Read only file */ #define _A_HIDDEN (0x02) /* Hidden file */ #define _A_SUBDIR (0x10) /* Subdirectory */ diff --git a/Code/Legacy/CryCommon/CryLibrary.h b/Code/Legacy/CryCommon/CryLibrary.h index 787085af00..a034a2a04b 100644 --- a/Code/Legacy/CryCommon/CryLibrary.h +++ b/Code/Legacy/CryCommon/CryLibrary.h @@ -49,7 +49,7 @@ */ #include -#include +#include #include #define INJECT_ENVIRONMENT_FUNCTION "InjectEnvironment" diff --git a/Code/Legacy/CryCommon/MacSpecific.h b/Code/Legacy/CryCommon/MacSpecific.h index 0533a1b556..1bc8c8a34b 100644 --- a/Code/Legacy/CryCommon/MacSpecific.h +++ b/Code/Legacy/CryCommon/MacSpecific.h @@ -26,4 +26,6 @@ typedef uint64_t threadID; +#define VK_CONTROL 0 + #endif // CRYINCLUDE_CRYCOMMON_MACSPECIFIC_H diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Process/Scheduler/TestImpactProcessScheduler.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Process/Scheduler/TestImpactProcessScheduler.cpp index a7e20a76f7..94df662a1d 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Process/Scheduler/TestImpactProcessScheduler.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Process/Scheduler/TestImpactProcessScheduler.cpp @@ -230,7 +230,7 @@ namespace TestImpact processInFlight.m_process = LaunchProcess(AZStd::move(processInfo)); processInFlight.m_startTime = createTime; } - catch (ProcessException& e) + catch ([[maybe_unused]] ProcessException& e) { AZ_Warning("ProcessScheduler", false, e.what()); createResult = LaunchResult::Failure; diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Enumeration/TestImpactTestEnumerator.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Enumeration/TestImpactTestEnumerator.cpp index e564b93f6c..756b1c75d6 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Enumeration/TestImpactTestEnumerator.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Enumeration/TestImpactTestEnumerator.cpp @@ -169,7 +169,7 @@ namespace TestImpact WriteFileContents(SerializeTestEnumeration(enumeration.value()), jobInfo->GetCache()->m_file); } } - catch (const Exception& e) + catch ([[maybe_unused]] const Exception& e) { AZ_Warning("Enumerate", false, e.what()); enumerations[jobId] = AZStd::nullopt; diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp index df0961564d..0065ea724e 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/SwapChain.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include From f0ff8da1d772a74c6c880c7a003ccf57f2c13473 Mon Sep 17 00:00:00 2001 From: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> Date: Thu, 12 Aug 2021 16:51:54 -0700 Subject: [PATCH 177/205] [redcode/crythread-2nd-pass] post merge duplicates removed Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm | 2 -- Code/Legacy/CryCommon/AppleSpecific.h | 15 --------------- 2 files changed, 17 deletions(-) diff --git a/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm b/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm index 3396200b87..cbd5a043e1 100644 --- a/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm +++ b/Code/LauncherUnified/Platform/Mac/Launcher_Mac.mm @@ -12,8 +12,6 @@ #include <../Common/UnixLike/Launcher_UnixLike.h> #include -#include - #if AZ_TESTS_ENABLED int main(int argc, char* argv[]) diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index 92fa318b87..cd3146403a 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -473,21 +473,6 @@ typedef HANDLE HMENU; #endif //__cplusplus -typedef union _LARGE_INTEGER -{ - struct - { - DWORD LowPart; - LONG HighPart; - }; - struct - { - DWORD LowPart; - LONG HighPart; - } u; - long long QuadPart; -} LARGE_INTEGER; - extern bool QueryPerformanceCounter(LARGE_INTEGER*); extern bool QueryPerformanceFrequency(LARGE_INTEGER* frequency); From 4cf384c2c555919e9e234c02c4d87fa0aef21840 Mon Sep 17 00:00:00 2001 From: moudgils <47460854+moudgils@users.noreply.github.com> Date: Thu, 12 Aug 2021 21:12:41 -0700 Subject: [PATCH 178/205] Fix minor typo (#3095) Signed-off-by: moudgils --- .../Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm | 4 ++-- .../Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm index f9eef9170a..272faeb4c1 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Windowing/NativeWindow_Mac.mm @@ -34,7 +34,7 @@ namespace AzFramework bool GetFullScreenState() const override; void SetFullScreenState(bool fullScreenState) override; bool CanToggleFullScreenState() const override { return true; } - uint32_t GetMainDisplayRefreshRate() const; + uint32_t GetDisplayRefreshRate() const override; private: static NSWindowStyleMask ConvertToNSWindowStyleMask(const WindowStyleMasks& styleMasks); @@ -142,7 +142,7 @@ namespace AzFramework return nativeMask ? nativeMask : defaultMask; } - uint32_t NativeWindowImpl_Darwin::GetMainDisplayRefreshRate() const + uint32_t NativeWindowImpl_Darwin::GetDisplayRefreshRate() const { return m_mainDisplayRefreshRate; } diff --git a/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm b/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm index 83e176b9ef..0486ca1b92 100644 --- a/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm +++ b/Code/Framework/AzFramework/Platform/iOS/AzFramework/Windowing/NativeWindow_ios.mm @@ -27,7 +27,7 @@ namespace AzFramework const WindowGeometry& geometry, const WindowStyleMasks& styleMasks) override; NativeWindowHandle GetWindowHandle() const override; - uint32_t GetMainDisplayRefreshRate() const; + uint32_t GetDisplayRefreshRate() const override; private: UIWindow* m_nativeWindow; @@ -66,7 +66,7 @@ namespace AzFramework return m_nativeWindow; } - uint32_t NativeWindowImpl_Ios::GetMainDisplayRefreshRate() const + uint32_t NativeWindowImpl_Ios::GetDisplayRefreshRate() const { return m_mainDisplayRefreshRate; } From 706333466e2137f11ba96105907f75291722d4c3 Mon Sep 17 00:00:00 2001 From: antonmic <56370189+antonmic@users.noreply.github.com> Date: Thu, 12 Aug 2021 23:58:51 -0700 Subject: [PATCH 179/205] Addressing PR feedback and making PassBuilder error if referenced shader isn't found Signed-off-by: antonmic <56370189+antonmic@users.noreply.github.com> --- .../Source/RPI.Builders/Pass/PassBuilder.cpp | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp index a803ecf31a..f74792049f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Pass/PassBuilder.cpp @@ -70,16 +70,16 @@ namespace AZ // Helper class to pass parameters to the AddDependency and FindReferencedAssets functions below struct FindPassReferenceAssetParams { - void* passAssetObject; + void* passAssetObject = nullptr; Uuid passAssetUuid; - SerializeContext* serializeContext; - AZStd::string_view passAssetSourceFile; // File path of the pass asset - AZStd::string_view dependencySourceFile; // File pass of the asset the pass asset depends on - const char* jobKey; // Job key for adding job dependency + SerializeContext* serializeContext = nullptr; + AZStd::string_view passAssetSourceFile; // File path of the pass asset + AZStd::string_view dependencySourceFile; // File pass of the asset the pass asset depends on + const char* jobKey = nullptr; // Job key for adding job dependency }; // Helper function to get a file reference and create a corresponding job dependency - void AddDependency(FindPassReferenceAssetParams& params, AssetBuilderSDK::JobDescriptor* job) + bool AddDependency(FindPassReferenceAssetParams& params, AssetBuilderSDK::JobDescriptor* job) { AZStd::string_view& file = params.dependencySourceFile; AZ::Data::AssetInfo sourceInfo; @@ -95,6 +95,12 @@ namespace AZ jobDependency.m_sourceFile.m_sourceFileDependencyPath = file; job->m_jobDependencyList.push_back(jobDependency); AZ_TracePrintf(PassBuilderName, "Creating job dependency on file [%s] \n", file.data()); + return true; + } + else + { + AZ_Error(PassBuilderName, false, "Could not find referenced file [%s]", file.data()); + return false; } } @@ -104,7 +110,7 @@ namespace AZ SerializeContext::ErrorHandler errorLogger; errorLogger.Reset(); - bool foundProblems = false; + bool success = true; // This callback will check whether the given element is an asset reference. If so, it will add it to the list of asset references auto beginCallback = [&](void* ptr, const SerializeContext::ClassData* classData, [[maybe_unused]] const SerializeContext::ClassElement* classElement) @@ -123,7 +129,8 @@ namespace AZ if (job != nullptr) // Create Job Phase { params.dependencySourceFile = path; - AddDependency(params, job); + bool dependencyAddedSuccessfully = AddDependency(params, job); + success = dependencyAddedSuccessfully && success; } else // Process Job Phase { @@ -136,7 +143,7 @@ namespace AZ else { AZ_Error(PassBuilderName, false, "Could not get AssetId for [%s]", assetReference->m_filePath.c_str()); - foundProblems = true; + success = false; } } } @@ -162,7 +169,7 @@ namespace AZ , nullptr ); - return !foundProblems; + return success; } // --- Code related to dependency shader asset handling --- From 4dd39c392979db451abbb22b1f4bae6220a7ed27 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 13 Aug 2021 09:55:06 +0100 Subject: [PATCH 180/205] Address commit re-run corner case. Signed-off-by: John --- scripts/build/TestImpactAnalysis/tiaf.py | 47 ++++++---- .../tiaf_persistent_storage.py | 90 +++++++++++++++---- .../tiaf_persistent_storage_local.py | 13 ++- .../tiaf_persistent_storage_s3.py | 17 ++-- 4 files changed, 124 insertions(+), 43 deletions(-) diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index 6a43ad3c70..28de00d6ba 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -87,7 +87,7 @@ class TestImpact: try: # Attempt to generate a diff between the src and dst commits - logger.error(f"Source '{self._src_commit}' and destination '{self._dst_commit}' will be diff'd.") + logger.info(f"Source '{self._src_commit}' and destination '{self._dst_commit}' will be diff'd.") diff_path = pathlib.Path(pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{self._instance_id}.diff")) self._repo.create_diff_file(self._src_commit, self._dst_commit, diff_path, multi_branch) except RuntimeError as e: @@ -219,28 +219,37 @@ class TestImpact: try: # Persistent storage location if s3_bucket: - persistent_storage = PersistentStorageS3(self._config, suite, s3_bucket, s3_top_level_dir, self._source_of_truth_branch) + persistent_storage = PersistentStorageS3(self._config, suite, self._dst_commit, s3_bucket, s3_top_level_dir, self._source_of_truth_branch) else: - persistent_storage = PersistentStorageLocal(self._config, suite) + persistent_storage = PersistentStorageLocal(self._config, suite, self._dst_commit) except SystemError as e: logger.warning(f"The persistent storage encountered an irrecoverable error, test impact analysis will be disabled: '{e}'") persistent_storage = None if persistent_storage: - # Flag to signify whether or not this is a re-run (multiple runs of the same commit) - # Right now, we don't fully support re-runs but in the future we will have an extra subfolder for each commit hash with the - # last run hash that was used for the first run for the commit so we can retreive the same reference point for building the - # change list to ensure each subsequent run is using the same data but for the time being, just perform a regular run - is_rerun = False + + # Flag for corner case where: + # 1. TIAF was already run previously for this commit. + # 2. There was no last commit hash when TIAF last ran on this commit (due to no coverage data existing get for this branch) + # 3. TIAF has not been run on any other commits between the run for this commit and the last run for this commit. + # The above results in TIAF being stuck in a state of generating an empty change list (and thus doing no work until another + # commit comes in) which is problematic if the commit needs to be re-run for whatever reason so in these conditions we revert + # back to a regular test run until another commit comes in + cannot_rerun_with_instrumentation = False + if persistent_storage.has_historic_data: logger.info("Historic data found.") self._src_commit = persistent_storage.last_commit_hash - # Perform some basic sanity checks on the commit hashes to ensure confidence in the integrity of the environment - if self._src_commit == self._dst_commit: - logger.info(f"Source commit '{self._src_commit}' and destination commit '{self._dst_commit}', implying this is a re-run. A regular sequence will instead be performed.") - persistent_storage = None - is_rerun = True + # Check to see if this is a re-run for this commit before any other changes have come in + if persistent_storage.is_repeat_sequence: + if persistent_storage.can_rerun_sequence: + logger.info(f"This sequence is being re-run before any other changes have come in so the last commit '{persistent_storage.this_commit_last_commit_hash}' used for the previous sequence will be used instead.") + self._src_commit = persistent_storage.this_commit_last_commit_hash + else: + logger.info(f"This sequence is being re-run before any other changes have come in but there is no useful historic data. A regular sequence will be performed instead.") + persistent_storage = None + cannot_rerun_with_instrumentation = True else: self._attempt_to_generate_change_list() else: @@ -268,7 +277,7 @@ class TestImpact: args.append(f"--changelist={self._change_list_path}") logger.info(f"Change list is set to '{self._change_list_path}'.") else: - if self._is_source_of_truth_branch and not is_rerun: + if self._is_source_of_truth_branch and not cannot_rerun_with_instrumentation: # Use seed sequence (instrumented all tests) for coverage updating branches so we can generate the coverage bed for future sequences sequence_type = "seed" # We always continue after test failures when seeding to ensure we capture the coverage for all test targets @@ -314,14 +323,18 @@ class TestImpact: logger.info(f"Args: {unpacked_args}") runtime_result = subprocess.run([str(self._tiaf_bin)] + args) report = None - + # If the sequence completed (with or without failures) we will update the historical meta-data if runtime_result.returncode == 0 or runtime_result.returncode == 7: logger.info("Test impact analysis runtime returned successfully.") - if self._is_source_of_truth_branch and persistent_storage is not None: - persistent_storage.update_and_store_historic_data(self._dst_commit) + + # Get the sequence report the runtime generated with open(report_file) as json_file: report = json.load(json_file) + + # Attempt to store the historic data for this branch and sequence + if self._is_source_of_truth_branch and persistent_storage is not None: + persistent_storage.update_and_store_historic_data() else: logger.error(f"The test impact analysis runtime returned with error: '{runtime_result.returncode}'.") diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py index 1ee3ac7e8c..3fff05b549 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py @@ -15,23 +15,39 @@ logger = get_logger(__file__) # Abstraction for the persistent storage required by TIAF to store and retrieve the branch coverage data and other meta-data class PersistentStorage(ABC): - def __init__(self, config: dict, suite: str): + + WORKSPACE_KEY = "workspace" + LAST_RUNS_KEY = "last_runs" + ACTIVE_KEY = "active" + ROOT_KEY = "root" + RELATIVE_PATHS_KEY = "relative_paths" + TEST_IMPACT_DATA_FILES_KEY = "test_impact_data_files" + LAST_COMMIT_HASH_KEY = "last_commit_hash" + COVERAGE_DATA_KEY = "coverage_data" + + def __init__(self, config: dict, suite: str, commit: str): """ Initializes the persistent storage into a state for which there is no historic data available. @param config: The runtime configuration to obtain the data file paths from. @param suite: The test suite for which the historic data will be obtained for. + @param commit: The commit hash for this build. """ # Work on the assumption that there is no historic meta-data (a valid state to be in, should none exist) self._last_commit_hash = None self._has_historic_data = False + self._has_previous_last_commit_hash = False + self._this_commit_hash = commit + self._this_commit_hash_last_commit_hash = None + self._historic_data = None + logger.info(f"Attempting to access persistent storage for the commit {self._this_commit_hash}") try: # The runtime expects the coverage data to be in the location specified in the config file (unless overridden with # the --datafile command line argument, which the TIAF scripts do not do) - self._active_workspace = pathlib.Path(config["workspace"]["active"]["root"]) - unpacked_coverage_data_file = config["workspace"]["active"]["relative_paths"]["test_impact_data_files"][suite] + self._active_workspace = pathlib.Path(config[self.WORKSPACE_KEY][self.ACTIVE_KEY][self.ROOT_KEY]) + unpacked_coverage_data_file = config[self.WORKSPACE_KEY][self.ACTIVE_KEY][self.RELATIVE_PATHS_KEY][self.TEST_IMPACT_DATA_FILES_KEY][suite] except KeyError as e: raise SystemError(f"The config does not contain the key {str(e)}.") @@ -45,17 +61,36 @@ class PersistentStorage(ABC): """ self._has_historic_data = False + self._has_previous_last_commit_hash = False try: - historic_data = json.loads(historic_data_json) - self._last_commit_hash = historic_data["last_commit_hash"] + self._historic_data = json.loads(historic_data_json) + + # Last commit hash for this branch + self._last_commit_hash = self._historic_data[self.LAST_COMMIT_HASH_KEY] logger.info(f"Last commit hash '{self._last_commit_hash}' found.") + if self.LAST_RUNS_KEY in self._historic_data: + # Last commit hash for the sequence that was run for this commit previously (if any) + if self._this_commit_hash in self._historic_data[self.LAST_RUNS_KEY]: + # 'None' is a valid value for the previously used last commit hash if there was no coverage data at that time + self._this_commit_hash_last_commit_hash = self._historic_data[self.LAST_RUNS_KEY][self._this_commit_hash] + self._has_previous_last_commit_hash = self._this_commit_hash_last_commit_hash is not None + + if self._has_previous_last_commit_hash: + logger.info(f"Last commit hash '{self._this_commit_hash_last_commit_hash}' was used previously for this commit.") + else: + logger.info(f"Prior sequence data found for this commit but it is empty (there was no coverage data vailable at that time).") + else: + logger.info(f"No prior sequence data found for commit '{self._this_commit_hash}', this is the first sequence for this commit.") + else: + logger.info(f"No prior sequence data found for any commits.") + # Create the active workspace directory where the coverage data file will be placed and unpack the coverage data so # it is accessible by the runtime self._active_workspace.mkdir(exist_ok=True) with open(self._unpacked_coverage_data_file, "w", newline='\n') as coverage_data: - coverage_data.write(historic_data["coverage_data"]) + coverage_data.write(self._historic_data[self.COVERAGE_DATA_KEY]) self._has_historic_data = True except json.JSONDecodeError: @@ -65,20 +100,31 @@ class PersistentStorage(ABC): except EnvironmentError as e: logger.error(f"There was a problem the coverage data file '{self._unpacked_coverage_data_file}': '{e}'.") - def _pack_historic_data(self, last_commit_hash: str): + def _pack_historic_data(self): """ Packs the current historic data into a JSON file for serializing. - @param last_commit_hash: The commit hash to associate the coverage data (and any other meta data) with. - @return: The packed historic data in JSON format. + @return: The packed historic data in JSON format. """ try: # Attempt to read the existing coverage data if self._unpacked_coverage_data_file.is_file(): + if not self._historic_data: + self._historic_data = {} + + # Last commit hash for this branch + self._historic_data[self.LAST_COMMIT_HASH_KEY] = self._this_commit_hash + + # Last commit hash for this commit + if not self.LAST_RUNS_KEY in self._historic_data: + self._historic_data[self.LAST_RUNS_KEY] = {} + self._historic_data[self.LAST_RUNS_KEY][self._this_commit_hash] = self._last_commit_hash + + # Coverage data for this branch with open(self._unpacked_coverage_data_file, "r") as coverage_data: - historic_data = {"last_commit_hash": last_commit_hash, "coverage_data": coverage_data.read()} - return json.dumps(historic_data) + self._historic_data[self.COVERAGE_DATA_KEY] = coverage_data.read() + return json.dumps(self._historic_data) else: logger.info(f"No coverage data exists at location '{self._unpacked_coverage_data_file}'.") except EnvironmentError as e: @@ -97,16 +143,14 @@ class PersistentStorage(ABC): """ pass - def update_and_store_historic_data(self, last_commit_hash: str): + def update_and_store_historic_data(self): """ Updates the historic data and stores it in the designated persistent storage location. - - @param last_commit_hash: The commit hash to associate the coverage data (and any other meta data) with. """ - historic_data_json = self._pack_historic_data(last_commit_hash) + historic_data_json = self._pack_historic_data() if historic_data_json: - logger.info(f"Attempting to store historic data with new last commit hash '{last_commit_hash}'...") + logger.info(f"Attempting to store historic data with new last commit hash '{self._this_commit_hash}'...") self._store_historic_data(historic_data_json) logger.info("The historic data was successfully stored.") @@ -119,4 +163,16 @@ class PersistentStorage(ABC): @property def last_commit_hash(self): - return self._last_commit_hash \ No newline at end of file + return self._last_commit_hash + + @property + def is_repeat_sequence(self): + return self._last_commit_hash == self._this_commit_hash + + @property + def this_commit_last_commit_hash(self): + return self._this_commit_hash_last_commit_hash + + @property + def can_rerun_sequence(self): + return self._has_previous_last_commit_hash \ No newline at end of file diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py index ba9b58fbf3..c72fafc580 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py @@ -15,19 +15,24 @@ logger = get_logger(__file__) # Implementation of local persistent storage class PersistentStorageLocal(PersistentStorage): - def __init__(self, config: str, suite: str): + + HISTORIC_KEY = "historic" + DATA_KEY = "data" + + def __init__(self, config: str, suite: str, commit: str): """ Initializes the persistent storage with any local historic data available. @param config: The runtime config file to obtain the data file paths from. @param suite: The test suite for which the historic data will be obtained for. + @param commit: The commit hash for this build. """ - super().__init__(config, suite) + super().__init__(config, suite, commit) try: # Attempt to obtain the local persistent data location specified in the runtime config file - self._historic_workspace = pathlib.Path(config["workspace"]["historic"]["root"]) - historic_data_file = pathlib.Path(config["workspace"]["historic"]["relative_paths"]["data"]) + self._historic_workspace = pathlib.Path(config[self.WORKSPACE_KEY][self.HISTORIC_KEY][self.ROOT_KEY]) + historic_data_file = pathlib.Path(config[self.WORKSPACE_KEY][self.HISTORIC_KEY][self.RELATIVE_PATHS_KEY][self.DATA_KEY]) # Attempt to unpack the local historic data file self._historic_data_file = self._historic_workspace.joinpath(historic_data_file) diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py index 1a279855ea..074caf73a1 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py @@ -18,16 +18,23 @@ logger = get_logger(__file__) # Implementation of s3 bucket persistent storage class PersistentStorageS3(PersistentStorage): - def __init__(self, config: dict, suite: str, s3_bucket: str, root_dir: str, branch: str): + + META_KEY = "meta" + BUILD_CONFIG_KEY = "build_config" + + def __init__(self, config: dict, suite: str, commit: str, s3_bucket: str, root_dir: str, branch: str): """ Initializes the persistent storage with the specified s3 bucket. @param config: The runtime config file to obtain the data file paths from. @param suite: The test suite for which the historic data will be obtained for. + @param commit: The commit hash for this build. @param s3_bucket: The s3 bucket to use for storing nd retrieving historic data. + @param root_dir: The root directory to use for the historic data object. + @branch branch: The branch to retrieve the historic data for. """ - super().__init__(config, suite) + super().__init__(config, suite, commit) try: # We store the historic data as compressed JSON @@ -37,8 +44,8 @@ class PersistentStorageS3(PersistentStorage): historic_data_file = f"historic_data.{object_extension}" # The location of the data is in the form // so the build config of each branch gets its own historic data - self._dir = f'{root_dir}/{branch}/{config["meta"]["build_config"]}' - self._historic_data_key = f'{self._dir}/{historic_data_file}' + self._historic_data_dir = f'{root_dir}/{branch}/{config[self.META_KEY][self.BUILD_CONFIG_KEY]}' + self._historic_data_key = f'{self._historic_data_dir}/{historic_data_file}' logger.info(f"Attempting to retrieve historic data for branch '{branch}' at location '{self._historic_data_key}' on bucket '{s3_bucket}'...") self._s3 = boto3.resource("s3") @@ -49,7 +56,7 @@ class PersistentStorageS3(PersistentStorage): logger.info(f"Historic data found for branch '{branch}'.") # Archive the existing object with the name of the existing last commit hash - #archive_key = f"{self._dir}/archive/{self._last_commit_hash}.{object_extension}" + #archive_key = f"{self._historic_data_dir}/archive/{self._last_commit_hash}.{object_extension}" #logger.info(f"Archiving existing historic data to '{archive_key}' in bucket '{self._bucket.name}'...") #self._bucket.copy({"Bucket": self._bucket.name, "Key": self._historic_data_key}, archive_key) #logger.info(f"Archiving complete.") From a1d855a920f2f741a2aff48b4251b84628598e78 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 13 Aug 2021 10:03:09 +0100 Subject: [PATCH 181/205] Invert corner case flag for readability. Signed-off-by: John --- scripts/build/TestImpactAnalysis/tiaf.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index 28de00d6ba..e8faef30e3 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -235,7 +235,7 @@ class TestImpact: # The above results in TIAF being stuck in a state of generating an empty change list (and thus doing no work until another # commit comes in) which is problematic if the commit needs to be re-run for whatever reason so in these conditions we revert # back to a regular test run until another commit comes in - cannot_rerun_with_instrumentation = False + can_rerun_with_instrumentation = True if persistent_storage.has_historic_data: logger.info("Historic data found.") @@ -249,7 +249,7 @@ class TestImpact: else: logger.info(f"This sequence is being re-run before any other changes have come in but there is no useful historic data. A regular sequence will be performed instead.") persistent_storage = None - cannot_rerun_with_instrumentation = True + can_rerun_with_instrumentation = False else: self._attempt_to_generate_change_list() else: @@ -277,7 +277,7 @@ class TestImpact: args.append(f"--changelist={self._change_list_path}") logger.info(f"Change list is set to '{self._change_list_path}'.") else: - if self._is_source_of_truth_branch and not cannot_rerun_with_instrumentation: + if self._is_source_of_truth_branch and can_rerun_with_instrumentation: # Use seed sequence (instrumented all tests) for coverage updating branches so we can generate the coverage bed for future sequences sequence_type = "seed" # We always continue after test failures when seeding to ensure we capture the coverage for all test targets From 99b369198bb9a8b1e62e870b075031033a69b63e Mon Sep 17 00:00:00 2001 From: Kevin Y <88146293+kev197@users.noreply.github.com> Date: Fri, 13 Aug 2021 08:59:38 -0400 Subject: [PATCH 182/205] Typo fix in duplicate project progress window (#2969) Signed-off-by: Kevin Yu --- Code/Tools/ProjectManager/Source/ProjectUtils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp index 52900f1b28..fb0ea23ece 100644 --- a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp @@ -189,7 +189,7 @@ namespace O3DE::ProjectManager const QString copiedFileSizeString = locale.formattedDataSize(outCopiedFileSize); const QString totalFileSizeString = locale.formattedDataSize(totalSizeToCopy); - progressDialog->setLabelText(QString("Coping file %1 of %2 (%3 of %4) ...").arg(QString::number(outNumCopiedFiles), + progressDialog->setLabelText(QString("Copying file %1 of %2 (%3 of %4) ...").arg(QString::number(outNumCopiedFiles), QString::number(filesToCopyCount), copiedFileSizeString, totalFileSizeString)); From a55cb3e35fa4ac69f6082a101ac7faab66c75a27 Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Fri, 13 Aug 2021 09:09:55 -0700 Subject: [PATCH 183/205] Fixed white-bar at bottom of Project Manager screen (#3091) Signed-off-by: AMZN-alexpete <26804013+AMZN-alexpete@users.noreply.github.com> --- Code/Tools/ProjectManager/Source/Application.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Tools/ProjectManager/Source/Application.cpp b/Code/Tools/ProjectManager/Source/Application.cpp index c977698152..9ca107dae5 100644 --- a/Code/Tools/ProjectManager/Source/Application.cpp +++ b/Code/Tools/ProjectManager/Source/Application.cpp @@ -168,9 +168,13 @@ namespace O3DE::ProjectManager // the decoration wrapper is intended to remember window positioning and sizing auto wrapper = new AzQtComponents::WindowDecorationWrapper(); wrapper->setGuest(m_mainWindow.data()); + + // show the main window here to apply the stylesheet before restoring geometry or we + // can end up with empty white space at the bottom of the window until the frame is resized again + m_mainWindow->show(); + wrapper->enableSaveRestoreGeometry("O3DE", "ProjectManager", "mainWindowGeometry"); wrapper->showFromSettings(); - m_mainWindow->show(); qApp->setQuitOnLastWindowClosed(true); From 9571a15769fc88c2713ca5ea6b834523b525c08e Mon Sep 17 00:00:00 2001 From: mrieggeramzn <61609885+mrieggeramzn@users.noreply.github.com> Date: Fri, 13 Aug 2021 11:36:58 -0700 Subject: [PATCH 184/205] Atom/mriegger/explicit set pcf address mode (#3061) * Explicit setting the addressing mode for the pcf shadowing * Explicitly setting addressing mode for sampler --- .../Assets/ShaderResourceGroups/CoreLights/SceneSrg.azsli | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/SceneSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/SceneSrg.azsli index d1a916dfac..67ccedd720 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/SceneSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/SceneSrg.azsli @@ -30,6 +30,9 @@ partial ShaderResourceGroup SceneSrg // Hardware PCF comparison sampler that is used when sampling the shadow maps SamplerComparisonState m_hwPcfSampler { + AddressU = Clamp; + AddressV = Clamp; + AddressW = Clamp; MagFilter = Linear; MinFilter = Linear; MipFilter = Point; From cd5081a7c3006d72b88dc196ffac0b3a66049673 Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Fri, 13 Aug 2021 13:31:46 -0700 Subject: [PATCH 185/205] Fix byte alignment issue for index/vertex buffers (#3110) * Fix byte alignment issue for index/vertex buffers * Remove default alignment value when getting dynamic buffer Signed-off-by: abrmich --- .../Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp | 4 ++-- .../Include/Atom/RPI.Public/DynamicDraw/DynamicBuffer.h | 4 ++-- .../Atom/RPI.Public/DynamicDraw/DynamicDrawInterface.h | 2 +- .../Include/Atom/RPI.Public/DynamicDraw/DynamicDrawSystem.h | 2 +- .../Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp | 6 +++--- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp index 3a7d50d2a9..10d1bdc2c6 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/DynamicPrimitiveProcessor.cpp @@ -196,7 +196,7 @@ namespace AZ { const size_t sourceByteSize = source.size() * sizeof(AuxGeomIndex); - RHI::Ptr dynamicBuffer = RPI::DynamicDrawInterface::Get()->GetDynamicBuffer(static_cast(sourceByteSize)); + RHI::Ptr dynamicBuffer = RPI::DynamicDrawInterface::Get()->GetDynamicBuffer(static_cast(sourceByteSize), RHI::Alignment::InputAssembly); if (!dynamicBuffer) { AZ_WarningOnce("AuxGeom", false, "Failed to allocate dynamic buffer of size %d.", sourceByteSize); @@ -211,7 +211,7 @@ namespace AZ { const size_t sourceByteSize = source.size() * sizeof(AuxGeomDynamicVertex); - RHI::Ptr dynamicBuffer = RPI::DynamicDrawInterface::Get()->GetDynamicBuffer(static_cast(sourceByteSize)); + RHI::Ptr dynamicBuffer = RPI::DynamicDrawInterface::Get()->GetDynamicBuffer(static_cast(sourceByteSize), RHI::Alignment::InputAssembly); if (!dynamicBuffer) { AZ_WarningOnce("AuxGeom", false, "Failed to allocate dynamic buffer of size %d.", sourceByteSize); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicBuffer.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicBuffer.h index 0c13efbd4b..c50ba2dc9b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicBuffer.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicBuffer.h @@ -25,8 +25,8 @@ namespace AZ //! DynamicBuffers are allocated by DynamicBufferAllocator. Check the description of DynamicBufferAllocator class for detail. //! The typical usage: //! // For every frame - //! auto buffer = DynamicDrawInterface::Get()->GetDynamicBuffer(size); - //! if (buffer) // the buffer could be empty if the allocation failed.e + //! auto buffer = DynamicDrawInterface::Get()->GetDynamicBuffer(size, RHI::Alignment::InputAssembly); + //! if (buffer) // the buffer could be empty if the allocation failed. //! { //! // write data to the buffer //! buffer->Write(data, size); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawInterface.h index cc2125af95..23a93481fd 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawInterface.h @@ -54,7 +54,7 @@ namespace AZ //! Get a DynamicBuffer from DynamicDrawSystem. //! The returned buffer will be invalidated every time the RPISystem's RenderTick is called - virtual RHI::Ptr GetDynamicBuffer(uint32_t size, uint32_t alignment = 1) = 0; + virtual RHI::Ptr GetDynamicBuffer(uint32_t size, uint32_t alignment) = 0; //! Draw a geometry to a scene with a given material virtual void DrawGeometry(Data::Instance material, const GeometryData& geometry, ScenePtr scene) = 0; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawSystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawSystem.h index 4210bca1db..4a00566632 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawSystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/DynamicDraw/DynamicDrawSystem.h @@ -32,7 +32,7 @@ namespace AZ // DynamicDrawInterface overrides... RHI::Ptr CreateDynamicDrawContext() override; - RHI::Ptr GetDynamicBuffer(uint32_t size, uint32_t alignment = 1) override; + RHI::Ptr GetDynamicBuffer(uint32_t size, uint32_t alignment) override; void DrawGeometry(Data::Instance material, const GeometryData& geometry, ScenePtr scene) override; void AddDrawPacket(Scene* scene, AZStd::unique_ptr drawPacket) override; AZStd::vector GetDrawListsForPass(const RasterPass* pass) override; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp index 7ca2bdcee5..29f57d6e0f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/DynamicDraw/DynamicDrawContext.cpp @@ -474,10 +474,10 @@ namespace AZ // Get dynamic buffers for vertex and index buffer. Skip draw if failed to allocate buffers uint32_t vertexDataSize = vertexCount * m_perVertexDataSize; RHI::Ptr vertexBuffer; - vertexBuffer = DynamicDrawInterface::Get()->GetDynamicBuffer(vertexDataSize); + vertexBuffer = DynamicDrawInterface::Get()->GetDynamicBuffer(vertexDataSize, RHI::Alignment::InputAssembly); uint32_t indexDataSize = indexCount * RHI::GetIndexFormatSize(indexFormat); - RHI::Ptr indexBuffer = DynamicDrawInterface::Get()->GetDynamicBuffer(indexDataSize); + RHI::Ptr indexBuffer = DynamicDrawInterface::Get()->GetDynamicBuffer(indexDataSize, RHI::Alignment::InputAssembly); if (indexBuffer == nullptr || vertexBuffer == nullptr) { @@ -572,7 +572,7 @@ namespace AZ // Get dynamic buffers for vertex and index buffer. Skip draw if failed to allocate buffers uint32_t vertexDataSize = vertexCount * m_perVertexDataSize; RHI::Ptr vertexBuffer; - vertexBuffer = DynamicDrawInterface::Get()->GetDynamicBuffer(vertexDataSize); + vertexBuffer = DynamicDrawInterface::Get()->GetDynamicBuffer(vertexDataSize, RHI::Alignment::InputAssembly); if (vertexBuffer == nullptr) { From 80aa4c42ce8082de578c8d3a78b1a95908aeea08 Mon Sep 17 00:00:00 2001 From: evanchia-ly-sdets <80914607+evanchia-ly-sdets@users.noreply.github.com> Date: Fri, 13 Aug 2021 13:41:56 -0700 Subject: [PATCH 186/205] moving smoke test to sandbox suite to investigate failures (#3109) Signed-off-by: evanchia --- .../Gem/PythonTests/smoke/CMakeLists.txt | 12 ++++++++++++ .../smoke/test_RemoteConsole_CPULoadLevel_Works.py | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 3fc4f3db0e..5374b0d318 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -73,5 +73,17 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) AutomatedTesting.GameLauncher AutomatedTesting.Assets ) + ly_add_pytest( + NAME AutomatedTesting::LoadLevelCPU + TEST_SUITE sandbox + PATH ${CMAKE_CURRENT_LIST_DIR}/test_RemoteConsole_CPULoadLevel_Works.py + TIMEOUT 100 + RUNTIME_DEPENDENCIES + AZ::AssetProcessor + AZ::PythonBindingsExample + Legacy::Editor + AutomatedTesting.GameLauncher + AutomatedTesting.Assets + ) endif() diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py index 6522514f2f..701dcfab10 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py @@ -24,7 +24,7 @@ from ly_remote_console.remote_console_commands import ( @pytest.mark.parametrize("launcher_platform", ["windows"]) @pytest.mark.parametrize("project", ["AutomatedTesting"]) @pytest.mark.parametrize("level", ["Simple"]) -@pytest.mark.SUITE_smoke +@pytest.mark.SUITE_sandbox class TestRemoteConsoleLoadLevelWorks(object): @pytest.fixture def remote_console_instance(self, request): From 63a78b906ad04e3fc19d0dfb570f5e7173303e11 Mon Sep 17 00:00:00 2001 From: jromnoa <80134229+jromnoa@users.noreply.github.com> Date: Fri, 13 Aug 2021 14:16:34 -0700 Subject: [PATCH 187/205] fixes light component GPU test AttributeError (I forgot to update atom_component_helper to atom_constants since constants were split from hydra functions into a new module) (#3115) Signed-off-by: jromnoa --- .../hydra_GPUTest_LightComponent.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py index 08f921e68b..8063445608 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py @@ -23,8 +23,7 @@ import azlmbr.legacy.general as general sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) import editor_python_test_tools.hydra_editor_utils as hydra -from atom_renderer.atom_utils import screenshot_utils -from atom_renderer.atom_utils import atom_component_helper +from atom_renderer.atom_utils import atom_component_helper, atom_constants, screenshot_utils from editor_python_test_tools.editor_test_helper import EditorTestHelper helper = EditorTestHelper(log_prefix="Atom_EditorTestHelper") @@ -92,7 +91,7 @@ def area_light_test(): 'SetComponentProperty', light_component_id_pair, LIGHT_TYPE_PROPERTY, - atom_component_helper.LIGHT_TYPES['capsule'] + atom_constants.LIGHT_TYPES['capsule'] ) # Update color and take screenshot in game mode @@ -118,7 +117,7 @@ def area_light_test(): 'SetComponentProperty', light_component_id_pair, LIGHT_TYPE_PROPERTY, - atom_component_helper.LIGHT_TYPES['spot_disk'] + atom_constants.LIGHT_TYPES['spot_disk'] ) area_light_rotation = math.Vector3(DEGREE_RADIAN_FACTOR * 90.0, 0.0, 0.0) azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", area_light.id, area_light_rotation) @@ -131,7 +130,7 @@ def area_light_test(): 'SetComponentProperty', light_component_id_pair, LIGHT_TYPE_PROPERTY, - atom_component_helper.LIGHT_TYPES['sphere'] + atom_constants.LIGHT_TYPES['sphere'] ) general.idle_wait(1.0) screenshot_utils.take_screenshot_game_mode("AreaLight_5", area_light_entity_name) @@ -210,7 +209,7 @@ def spot_light_test(): 'SetComponentProperty', light_component_type, LIGHT_TYPE_PROPERTY, - atom_component_helper.LIGHT_TYPES['spot_disk'] + atom_constants.LIGHT_TYPES['spot_disk'] ) general.idle_wait(1.0) From 906042359243d215cd05303f732a3422a8fa20a1 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 13 Aug 2021 16:20:08 -0500 Subject: [PATCH 188/205] Settings registry notification deadlock fix (#3065) * Added a StealHandlers function to AZ Event The StealHandlers function is able to take all the handlers from an AZ Event parameter and register them with the current AZ Event This allows stealing handlers from expiring AZ Events, which is useful for a lock and swap algorithm for thread safety. 1. Lock persistent AZ::Event 2. Swap persistent AZ::Event with local AZ::Event 3. Unlock persistent AZ::Event - Other threads can now add to this AZ::Event 4. Invoke handlers from local AZ::Event 5. Relock persistent AZ::Event 5. Swap local AZ::Event with persistent AZ::Event 6. Local AZ::Event now contains handlers that were added when the lock was free 7. Persistent AZ::Event now steals from local AZ::Event 8. Unlock persistent AZ::Event Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Separated SettingRegistry update/query mutex from Notifier update mutex The Settings Registry update/query mutex is also better scoped to reduce the amount of lock time. The Notifier mutex being separate allows the Settings Registry to signal a notification event without being under any mutex, by locking and swapping the notifier event with a local instance Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Renamed StealHandlers function to ClaimHandlers Replaced decltype keywords in ClaimHandlers to auto Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/EBus/Event.h | 6 + Code/Framework/AzCore/AzCore/EBus/Event.inl | 26 ++++ .../AzCore/Settings/SettingsRegistryImpl.cpp | 111 +++++++++++++----- .../AzCore/Settings/SettingsRegistryImpl.h | 5 +- Code/Framework/AzCore/Tests/EventTests.cpp | 31 +++++ 5 files changed, 151 insertions(+), 28 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/EBus/Event.h b/Code/Framework/AzCore/AzCore/EBus/Event.h index b3c29b63a2..00310f4dbc 100644 --- a/Code/Framework/AzCore/AzCore/EBus/Event.h +++ b/Code/Framework/AzCore/AzCore/EBus/Event.h @@ -58,6 +58,12 @@ namespace AZ Event& operator=(Event&& rhs); + //! Take the handlers registered with the other event + //! and move them to this event. The other will event + //! will be cleared after call + //! @param other event to move handlers + Event& ClaimHandlers(Event&& other); + //! Returns true if at least one handler is connected to this event. bool HasHandlerConnected() const; diff --git a/Code/Framework/AzCore/AzCore/EBus/Event.inl b/Code/Framework/AzCore/AzCore/EBus/Event.inl index dfb1781991..ffa8c8b9c5 100644 --- a/Code/Framework/AzCore/AzCore/EBus/Event.inl +++ b/Code/Framework/AzCore/AzCore/EBus/Event.inl @@ -207,6 +207,32 @@ namespace AZ } + template + auto Event::ClaimHandlers(Event&& other) -> Event& + { + auto handlers = AZStd::move(other.m_handlers); + auto addList = AZStd::move(other.m_addList); + other.m_freeList = {}; + other.m_updating = false; + + AZStd::array handlerContainers{ &handlers, &addList }; + for (AZStd::vector* handlerList : handlerContainers) + { + for (Handler* handler : *handlerList) + { + if (handler != nullptr) + { + handler->m_index = 0; + handler->m_event = this; + Connect(*handler); + } + } + } + + return *this; + } + + template bool Event::HasHandlerConnected() const { diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp index 0882e1b7f2..3dc2d4145e 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp @@ -20,7 +20,7 @@ namespace AZ { template - bool SettingsRegistryImpl::SetValueInternal(AZStd::string_view path, T value, SettingsRegistryInterface::Type type) + bool SettingsRegistryImpl::SetValueInternal(AZStd::string_view path, T value) { if (path.empty()) { @@ -56,7 +56,6 @@ namespace AZ static_assert(!AZStd::is_same_v, "SettingsRegistryImpl::SetValueInternal called with unsupported type."); } - m_notifiers.Signal(path, type); return true; } return false; @@ -157,11 +156,11 @@ namespace AZ // Setting to empty string to prevent assert path = ""; } - AZStd::scoped_lock lock(m_settingMutex); rapidjson::Pointer pointer(path.data(), path.length()); if (pointer.IsValid()) { + AZStd::scoped_lock lock(m_settingMutex); const rapidjson::Value* value = pointer.Get(m_settings); if (value) { @@ -207,7 +206,7 @@ namespace AZ { NotifyEventHandler notifyHandler{ callback }; { - AZStd::scoped_lock lock(m_settingMutex); + AZStd::scoped_lock lock(m_notifierMutex); notifyHandler.Connect(m_notifiers); } return notifyHandler; @@ -217,7 +216,7 @@ namespace AZ { NotifyEventHandler notifyHandler{ AZStd::move(callback) }; { - AZStd::scoped_lock lock(m_settingMutex); + AZStd::scoped_lock lock(m_notifierMutex); notifyHandler.Connect(m_notifiers); } return notifyHandler; @@ -225,10 +224,35 @@ namespace AZ void SettingsRegistryImpl::ClearNotifiers() { - AZStd::scoped_lock lock(m_settingMutex); + AZStd::scoped_lock lock(m_notifierMutex); m_notifiers.DisconnectAllHandlers(); } + void SettingsRegistryImpl::SignalNotifier(AZStd::string_view jsonPath, Type type) + { + // Move the Notifier AZ::Event to a local AZ::Event in order to allow + // the notifier handlers to be signaled outside of the notifier mutex + // This allows other threads to register notifiers while this thread + // is invoking the handlers + decltype(m_notifiers) localNotifierEvent; + { + AZStd::scoped_lock lock(m_notifierMutex); + localNotifierEvent = AZStd::move(m_notifiers); + } + + localNotifierEvent.Signal(jsonPath, type); + + { + // Swap the local handlers with the current m_notifiers which + // will contain any handlers added during the signaling of the + // local event + AZStd::scoped_lock lock(m_notifierMutex); + AZStd::swap(m_notifiers, localNotifierEvent); + // Append any added handlers to the m_notifier structure + m_notifiers.ClaimHandlers(AZStd::move(localNotifierEvent)); + } + } + SettingsRegistryInterface::Type SettingsRegistryImpl::GetType(AZStd::string_view path) const { if (path.empty()) @@ -239,11 +263,11 @@ namespace AZ path = ""; } - AZStd::scoped_lock lock(m_settingMutex); rapidjson::Pointer pointer(path.data(), path.length()); if (pointer.IsValid()) { + AZStd::scoped_lock lock(m_settingMutex); const rapidjson::Value* value = pointer.Get(m_settings); if (value) { @@ -316,11 +340,11 @@ namespace AZ // Setting to empty string to prevent assert path = ""; } - AZStd::scoped_lock lock(m_settingMutex); rapidjson::Pointer pointer(path.data(), path.length()); if (pointer.IsValid()) { + AZStd::scoped_lock lock(m_settingMutex); const rapidjson::Value* value = pointer.Get(m_settings); if (value) { @@ -333,32 +357,52 @@ namespace AZ bool SettingsRegistryImpl::Set(AZStd::string_view path, bool value) { - AZStd::scoped_lock lock(m_settingMutex); - return SetValueInternal(path, value, Type::Boolean); + if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value)) + { + return false; + } + SignalNotifier(path, Type::Boolean); + return true; } bool SettingsRegistryImpl::Set(AZStd::string_view path, s64 value) { - AZStd::scoped_lock lock(m_settingMutex); - return SetValueInternal(path, value, Type::Integer); + if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value)) + { + return false; + } + SignalNotifier(path, Type::Integer); + return true; } bool SettingsRegistryImpl::Set(AZStd::string_view path, u64 value) { - AZStd::scoped_lock lock(m_settingMutex); - return SetValueInternal(path, value, Type::Integer); + if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value)) + { + return false; + } + SignalNotifier(path, Type::Integer); + return true; } bool SettingsRegistryImpl::Set(AZStd::string_view path, double value) { - AZStd::scoped_lock lock(m_settingMutex); - return SetValueInternal(path, value, Type::FloatingPoint); + if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value)) + { + return false; + } + SignalNotifier(path, Type::FloatingPoint); + return true; } bool SettingsRegistryImpl::Set(AZStd::string_view path, AZStd::string_view value) { - AZStd::scoped_lock lock(m_settingMutex); - return SetValueInternal(path, value, Type::String); + if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value)) + { + return false; + } + SignalNotifier(path, Type::String); + return true; } bool SettingsRegistryImpl::Set(AZStd::string_view path, const char* value) @@ -376,7 +420,6 @@ namespace AZ path = ""; } - AZStd::scoped_lock lock(m_settingMutex); rapidjson::Pointer pointer(path.data(), path.length()); if (pointer.IsValid()) @@ -386,9 +429,10 @@ namespace AZ value, nullptr, valueTypeID, m_serializationSettings); if (jsonResult.GetProcessing() != JsonSerializationResult::Processing::Halted) { + AZStd::scoped_lock lock(m_settingMutex); rapidjson::Value& setting = pointer.Create(m_settings, m_settings.GetAllocator()); setting = AZStd::move(store); - m_notifiers.Signal(path, Type::Object); + SignalNotifier(path, Type::Object); return true; } } @@ -404,13 +448,13 @@ namespace AZ // Setting to empty string to prevent assert path = ""; } - AZStd::scoped_lock lock(m_settingMutex); rapidjson::Pointer pointerPath(path.data(), path.size()); if (!pointerPath.IsValid()) { return false; } + AZStd::scoped_lock lock(m_settingMutex); return pointerPath.Erase(m_settings); } @@ -540,7 +584,7 @@ namespace AZ return false; } - m_notifiers.Signal("", Type::Object); + SignalNotifier("", Type::Object); return true; } @@ -562,8 +606,6 @@ namespace AZ scratchBuffer = &buffer; } - AZStd::scoped_lock lock(m_settingMutex); - bool result = false; if (path[path.length()] == 0) { @@ -577,6 +619,8 @@ namespace AZ R"(Path "%.*s" is too long. Either make sure that the provided path is terminated or use a shorter path.)", static_cast(path.length()), path.data()); Pointer pointer(AZ_SETTINGS_REGISTRY_HISTORY_KEY "/-"); + + AZStd::scoped_lock lock(m_settingMutex); Value pathValue(path.data(), aznumeric_caster(path.length()), m_settings.GetAllocator()); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Unable to read registry file."), m_settings.GetAllocator()) @@ -622,6 +666,7 @@ namespace AZ { AZ_Error("Settings Registry", false, "Folder path for the Setting Registry is too long: %.*s", static_cast(path.size()), path.data()); + AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Folder path for the Setting Registry is too long."), m_settings.GetAllocator()) .AddMember(StringRef("Path"), Value(path.data(), aznumeric_caster(path.length()), m_settings.GetAllocator()), m_settings.GetAllocator()); @@ -659,6 +704,7 @@ namespace AZ if (fileList.size() >= MaxRegistryFolderEntries) { AZ_Error("Settings Registry", false, "Too many files in registry folder."); + AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator()) .AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator()) @@ -678,7 +724,6 @@ namespace AZ SystemFile::FindFiles(folderPath.c_str(), callback); - AZStd::scoped_lock lock(m_settingMutex); if (!platform.empty()) { // Move the folderPath prefix back to the supplied path before the wildcard @@ -696,6 +741,7 @@ namespace AZ if (fileList.size() >= MaxRegistryFolderEntries) { AZ_Error("Settings Registry", false, "Too many files in registry folder."); + AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator()) .AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator()) @@ -923,6 +969,8 @@ namespace AZ collisionFound = true; AZ_Error("Settings Registry", false, R"(Two registry files in "%.*s" point to the same specialization: "%s" and "%s")", AZ_STRING_ARG(folderPath), lhs.m_relativePath.c_str(), rhs.m_relativePath.c_str()); + + AZStd::scoped_lock lock(m_settingMutex); historyPointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator()) .AddMember(StringRef("Path"), @@ -1077,6 +1125,7 @@ namespace AZ } } + AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Unable to parse registry file due to invalid json."), m_settings.GetAllocator()) .AddMember(StringRef("Path"), Value(path, m_settings.GetAllocator()), m_settings.GetAllocator()) @@ -1102,6 +1151,7 @@ namespace AZ R"(To merge the supplied settings registry file, the settings within it must be placed within a JSON Object '{}')" R"( in order to allow moving of its fields using the root-key as an anchor.)", path); + AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Cannot merge registry file with a root which is not a JSON Object," " an empty root key and a merge approach of JsonMergePatch. Otherwise the Settings Registry would be overridden." @@ -1118,6 +1168,7 @@ namespace AZ JsonSerializationResult::ResultCode mergeResult(JsonSerializationResult::Tasks::Merge); if (rootKey.empty()) { + AZStd::scoped_lock lock(m_settingMutex); mergeResult = JsonSerialization::ApplyPatch(m_settings, m_settings.GetAllocator(), jsonPatch, mergeApproach, m_applyPatchSettings); } else @@ -1125,6 +1176,7 @@ namespace AZ Pointer root(rootKey.data(), rootKey.length()); if (root.IsValid()) { + AZStd::scoped_lock lock(m_settingMutex); Value& rootValue = root.Create(m_settings, m_settings.GetAllocator()); mergeResult = JsonSerialization::ApplyPatch(rootValue, m_settings.GetAllocator(), jsonPatch, mergeApproach, m_applyPatchSettings); } @@ -1132,6 +1184,7 @@ namespace AZ { AZ_Error("Settings Registry", false, R"(Failed to root path "%.*s" is invalid.)", aznumeric_cast(rootKey.length()), rootKey.data()); + AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Invalid root key."), m_settings.GetAllocator()) .AddMember(StringRef("Path"), Value(path, m_settings.GetAllocator()), m_settings.GetAllocator()); @@ -1141,15 +1194,19 @@ namespace AZ if (mergeResult.GetProcessing() != JsonSerializationResult::Processing::Completed) { AZ_Error("Settings Registry", false, R"(Failed to fully merge registry file "%s".)", path); + AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Failed to fully merge registry file."), m_settings.GetAllocator()) .AddMember(StringRef("Path"), Value(path, m_settings.GetAllocator()), m_settings.GetAllocator()); return false; } - pointer.Create(m_settings, m_settings.GetAllocator()).SetString(path, m_settings.GetAllocator()); + { + AZStd::scoped_lock lock(m_settingMutex); + pointer.Create(m_settings, m_settings.GetAllocator()).SetString(path, m_settings.GetAllocator()); + } - m_notifiers.Signal("", Type::Object); + SignalNotifier("", Type::Object); return true; } diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h index 41a628cf22..4126e19322 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h @@ -89,7 +89,7 @@ namespace AZ using RegistryFileList = AZStd::fixed_vector; template - bool SetValueInternal(AZStd::string_view path, T value, SettingsRegistryInterface::Type type); + bool SetValueInternal(AZStd::string_view path, T value); template bool GetValueInternal(T& result, AZStd::string_view path) const; VisitResponse Visit(Visitor& visitor, StackedString& path, AZStd::string_view valueName, @@ -100,8 +100,11 @@ namespace AZ const rapidjson::Pointer& historyPointer, AZStd::string_view folderPath); bool ExtractFileDescription(RegistryFile& output, const char* filename, const Specializations& specializations); bool MergeSettingsFileInternal(const char* path, Format format, AZStd::string_view rootKey, AZStd::vector& scratchBuffer); + + void SignalNotifier(AZStd::string_view jsonPath, Type type); mutable AZStd::recursive_mutex m_settingMutex; + mutable AZStd::recursive_mutex m_notifierMutex; NotifyEvent m_notifiers; rapidjson::Document m_settings; JsonSerializerSettings m_serializationSettings; diff --git a/Code/Framework/AzCore/Tests/EventTests.cpp b/Code/Framework/AzCore/Tests/EventTests.cpp index 358c1a62ae..aaa70344e7 100644 --- a/Code/Framework/AzCore/Tests/EventTests.cpp +++ b/Code/Framework/AzCore/Tests/EventTests.cpp @@ -240,6 +240,37 @@ namespace UnitTest static_assert(!AZStd::is_copy_assignable_v>, "AZ Events should not be copy assignable"); } + TEST_F(EventTests, TestClaimHandlers_TakesAllSourceHandlers) + { + AZ::Event<> testEvent1; + AZ::Event<> testEvent2; + + int32_t handlerInvokeCount{}; + auto handlerCallback = [&handlerInvokeCount]() + { + ++handlerInvokeCount; + }; + AZ::Event<>::Handler testHandler1(handlerCallback); + AZ::Event<>::Handler testHandler2(handlerCallback); + + testHandler1.Connect(testEvent1); + testHandler2.Connect(testEvent2); + + EXPECT_TRUE(testEvent1.HasHandlerConnected()); + EXPECT_TRUE(testEvent2.HasHandlerConnected()); + + testEvent1.ClaimHandlers(AZStd::move(testEvent2)); + EXPECT_TRUE(testEvent1.HasHandlerConnected()); + EXPECT_FALSE(testEvent2.HasHandlerConnected()); + + // testEvent1 should have both handlers + testEvent1.Signal(); + EXPECT_EQ(2, handlerInvokeCount); + // testEvent2 should have neither of the handlers + testEvent2.Signal(); + EXPECT_EQ(2, handlerInvokeCount); + } + TEST_F(EventTests, HandlerMoveAssignment_ProperlyDisconnectsFromOldEvent) { AZ::Event<> testEvent1; From 093a03cfbc98993d799883d9426ef3a7fda1a6a8 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 13 Aug 2021 15:58:01 -0700 Subject: [PATCH 189/205] fix for non-unity mac build (#3118) Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Editor/Util/StringHelpers.cpp | 2 -- Code/Editor/Util/StringHelpers.h | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Code/Editor/Util/StringHelpers.cpp b/Code/Editor/Util/StringHelpers.cpp index 6c819270bd..d0999d6ae2 100644 --- a/Code/Editor/Util/StringHelpers.cpp +++ b/Code/Editor/Util/StringHelpers.cpp @@ -10,8 +10,6 @@ #include "StringHelpers.h" #include "Util.h" -#include - int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1) { const size_t minLength = Util::getMin(str0.length(), str1.length()); diff --git a/Code/Editor/Util/StringHelpers.h b/Code/Editor/Util/StringHelpers.h index b5c84d7fe3..8a0883b24c 100644 --- a/Code/Editor/Util/StringHelpers.h +++ b/Code/Editor/Util/StringHelpers.h @@ -12,7 +12,7 @@ #pragma once #include -#include +#include namespace StringHelpers { From 87ae7e865365707ba7d7fc453fdd0c43b34f489a Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Fri, 13 Aug 2021 18:22:40 -0700 Subject: [PATCH 190/205] Fix android gradle scripts to prevent cmake_dependencies.._gamelauncher from being wiped out of the APK Update gradle script generation to correct task dependencies (#3120) - copyNativeArtifacts must run after syncLYLayoutMode - syncLYLayoutMode must must after externalNativeBuild Signed-off-by: Steve Pham --- .../Tools/Platform/Android/android_support.py | 40 ++++++++++++------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/cmake/Tools/Platform/Android/android_support.py b/cmake/Tools/Platform/Android/android_support.py index d820eb1d8c..77c8a37a35 100755 --- a/cmake/Tools/Platform/Android/android_support.py +++ b/cmake/Tools/Platform/Android/android_support.py @@ -372,9 +372,12 @@ CUSTOM_GRADLE_COPY_NATIVE_CONFIG_BUILD_ARTIFACTS_FORMAT_STR = """ }} compile{config}Sources.dependsOn copyNativeArtifacts{config} +""" + +CUSTOM_GRADLE_COPY_NATIVE_CONFIG_BUILD_ARTIFACTS_DEPENDENCY_FORMAT_STR = """ copyNativeArtifacts{config}.mustRunAfter {{ - tasks.findAll {{ task->task.name.contains('externalNativeBuild{config}') }} + tasks.findAll {{ task->task.name.contains('syncLYLayoutMode{config}') }} }} """ @@ -383,7 +386,13 @@ CUSTOM_APPLY_ASSET_LAYOUT_TASK_FORMAT_STR = """ workingDir '{working_dir}' commandLine '{python_full_path}', 'layout_tool.py', '--project-path', '{project_path}', '-p', 'Android', '-a', '{asset_type}', '-m', '{asset_mode}', '--create-layout-root', '-l', '{asset_layout_folder}' }} + compile{config}Sources.dependsOn syncLYLayoutMode{config} + + syncLYLayoutMode{config}.mustRunAfter {{ + tasks.findAll {{ task->task.name.contains('externalNativeBuild{config}') }} + }} + """ @@ -832,25 +841,28 @@ class AndroidProjectGenerator(object): asset_layout_folder=(self.build_dir / 'app/src/main/assets').resolve().as_posix(), file_includes='Test.Assets/**/*.*') else: - # Copy over settings registry files from the Registry folder with build output directory gradle_build_env[f'CUSTOM_APPLY_ASSET_LAYOUT_{native_config_upper}_TASK'] = \ + CUSTOM_APPLY_ASSET_LAYOUT_TASK_FORMAT_STR.format(working_dir=common.normalize_path_for_settings(self.engine_root / 'cmake/Tools'), + python_full_path=common.normalize_path_for_settings(self.engine_root / 'python' / PYTHON_SCRIPT), + asset_type=self.asset_type, + project_path=self.project_path.as_posix(), + asset_mode=self.asset_mode if native_config != 'Release' else 'PAK', + asset_layout_folder=(self.build_dir / 'app/src/main/assets').resolve().as_posix(), + config=native_config) + # Copy over settings registry files from the Registry folder with build output directory + gradle_build_env[f'CUSTOM_APPLY_ASSET_LAYOUT_{native_config_upper}_TASK'] += \ CUSTOM_GRADLE_COPY_NATIVE_CONFIG_BUILD_ARTIFACTS_FORMAT_STR.format(config=native_config, config_lower=native_config_lower, asset_layout_folder=(self.build_dir / 'app/src/main/assets').resolve().as_posix(), file_includes='**/Registry/*.setreg') - - if self.include_assets_in_apk: - if not self.is_test_project: + if self.include_assets_in_apk: + # This is a dependency of the layout sync only if we are including assets in the APK gradle_build_env[f'CUSTOM_APPLY_ASSET_LAYOUT_{native_config_upper}_TASK'] += \ - CUSTOM_APPLY_ASSET_LAYOUT_TASK_FORMAT_STR.format(working_dir=common.normalize_path_for_settings(self.engine_root / 'cmake/Tools'), - python_full_path=common.normalize_path_for_settings(self.engine_root / 'python' / PYTHON_SCRIPT), - asset_type=self.asset_type, - project_path=self.project_path.as_posix(), - asset_mode=self.asset_mode if native_config != 'Release' else 'PAK', - asset_layout_folder=(self.build_dir / 'app/src/main/assets').resolve().as_posix(), - config=native_config) - else: - gradle_build_env[f'CUSTOM_APPLY_ASSET_LAYOUT_{native_config_upper}_TASK'] = '' + CUSTOM_GRADLE_COPY_NATIVE_CONFIG_BUILD_ARTIFACTS_DEPENDENCY_FORMAT_STR.format(config=native_config) + + + + if self.signing_config: gradle_build_env[f'SIGNING_{native_config_upper}_CONFIG'] = f'signingConfig signingConfigs.{native_config_lower}' if self.signing_config else '' else: From 2fa9a831b3d09240d786d0636a173f9c9d169fd7 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Fri, 13 Aug 2021 20:26:49 -0500 Subject: [PATCH 191/205] AtomTools: prepend asterisk to denote modified document tabs Appending is standard and preferred but the tabs elide from the end (instead of middle) and cut it off Signed-off-by: Guthrie Adams --- .../Code/Source/Window/AtomToolsMainWindow.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp index 55bec32dc7..e869e0eb98 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp @@ -199,8 +199,10 @@ namespace AtomToolsFramework { if (documentId == GetDocumentIdFromTab(tabIndex)) { - // We use an asterisk appended to the file name to denote modified document - const AZStd::string modifiedLabel = isModified ? label + " *" : label; + // We use an asterisk prepended to the file name to denote modified document + // Appending is standard and preferred but the tabs elide from the + // end (instead of middle) and cut it off + const AZStd::string modifiedLabel = isModified ? "* " + label : label; m_tabWidget->setTabText(tabIndex, modifiedLabel.c_str()); m_tabWidget->setTabToolTip(tabIndex, toolTip.c_str()); m_tabWidget->repaint(); From 83f6cb813ae42e0e8420a48f791d5c52f3f3178c Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Fri, 13 Aug 2021 18:38:48 -0700 Subject: [PATCH 192/205] Fix Non-Unity compile error with Atom Sample Viewer and the Atom Gem (#3119) Signed-off-by: spham-amzn --- Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h b/Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h index 7c77838330..454a6d4086 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include From fe3b30e42ca96e97c4609de60daacde6d3f4fe60 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Sat, 14 Aug 2021 14:07:36 -0500 Subject: [PATCH 193/205] AtomTools: Fix python terminal help crash ATOM-16242 Checking EditorWindowRequests::GetAppMainWindow before searching for main window Signed-off-by: Guthrie Adams --- .../PythonTerminal/ScriptHelpDialog.cpp | 41 ++++++++++++++++++- .../PythonTerminal/ScriptHelpDialog.h | 34 +-------------- 2 files changed, 42 insertions(+), 33 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.cpp index ea13d368cd..ba85911060 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.cpp @@ -6,7 +6,6 @@ * */ - // Description : For listing available script commands with their descriptions #include "ScriptHelpDialog.h" @@ -23,6 +22,7 @@ // AzToolsFramework #include // for EditorPythonConsoleInterface +#include AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include @@ -313,6 +313,45 @@ namespace AzToolsFramework connect(ui->tableView, &ScriptTableView::doubleClicked, this, &CScriptHelpDialog::OnDoubleClick); } + CScriptHelpDialog* CScriptHelpDialog::GetInstance() + { + static CScriptHelpDialog* pInstance = nullptr; + if (!pInstance) + { + QMainWindow* mainWindow = GetMainWindowOfCurrentApplication(); + if (!mainWindow) + { + AZ_Assert(false, "Failed to find MainWindow."); + return nullptr; + } + + QWidget* parentWidget = mainWindow->window() + ? mainWindow->window() + : mainWindow; // MainWindow might have a WindowDecorationWrapper parent. Makes a difference on macOS. + pInstance = new CScriptHelpDialog(parentWidget); + } + return pInstance; + } + + QMainWindow* CScriptHelpDialog::GetMainWindowOfCurrentApplication() + { + QWidget* widget = nullptr; + EditorWindowRequestBus::BroadcastResult(widget, &EditorWindowRequests::GetAppMainWindow); + if (QMainWindow* mainWindow = qobject_cast(widget)) + { + return mainWindow; + } + + for (QWidget* widget : qApp->topLevelWidgets()) + { + if (QMainWindow* mainWindow = qobject_cast(widget)) + { + return mainWindow; + } + } + return nullptr; + } + void CScriptHelpDialog::OnDoubleClick(const QModelIndex& index) { if (!index.isValid()) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.h b/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.h index e34d652e1b..3cefa919c9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.h @@ -132,43 +132,13 @@ namespace AzToolsFramework { Q_OBJECT public: - static CScriptHelpDialog* GetInstance() - { - static CScriptHelpDialog* pInstance = nullptr; - if (!pInstance) - { - QMainWindow* mainWindow = GetMainWindowOfCurrentApplication(); - if (!mainWindow) - { - AZ_Assert(false, "Failed to find MainWindow."); - return nullptr; - } - - QWidget* parentWidget = mainWindow->window() ? mainWindow->window() : mainWindow; // MainWindow might have a WindowDecorationWrapper parent. Makes a difference on macOS. - pInstance = new CScriptHelpDialog(parentWidget); - } - return pInstance; - } - + static CScriptHelpDialog* GetInstance(); private Q_SLOTS: void OnDoubleClick(const QModelIndex&); private: - static QMainWindow* GetMainWindowOfCurrentApplication() - { - QMainWindow* mainWindow = nullptr; - for (QWidget* w : qApp->topLevelWidgets()) - { - mainWindow = qobject_cast(w); - if (mainWindow) - { - return mainWindow; - } - } - return nullptr; - } - explicit CScriptHelpDialog(QWidget* parent = nullptr); + static QMainWindow* GetMainWindowOfCurrentApplication(); QScopedPointer ui; }; } // namespace AzToolsFramework From d6c5f1444ba8595df24ce84776a8fec881377e72 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Sat, 14 Aug 2021 14:30:54 -0500 Subject: [PATCH 194/205] fixing hidden variable warning Signed-off-by: Guthrie Adams --- .../PythonTerminal/ScriptHelpDialog.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.cpp index ba85911060..e9f6cd9e53 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/PythonTerminal/ScriptHelpDialog.cpp @@ -335,16 +335,16 @@ namespace AzToolsFramework QMainWindow* CScriptHelpDialog::GetMainWindowOfCurrentApplication() { - QWidget* widget = nullptr; - EditorWindowRequestBus::BroadcastResult(widget, &EditorWindowRequests::GetAppMainWindow); - if (QMainWindow* mainWindow = qobject_cast(widget)) + QWidget* mainWindowWidget = nullptr; + EditorWindowRequestBus::BroadcastResult(mainWindowWidget, &EditorWindowRequests::GetAppMainWindow); + if (QMainWindow* mainWindow = qobject_cast(mainWindowWidget)) { return mainWindow; } - for (QWidget* widget : qApp->topLevelWidgets()) + for (QWidget* topLevelWidget : qApp->topLevelWidgets()) { - if (QMainWindow* mainWindow = qobject_cast(widget)) + if (QMainWindow* mainWindow = qobject_cast(topLevelWidget)) { return mainWindow; } From 181698b950e63236d77c525964d9af5bbe617932 Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Mon, 16 Aug 2021 10:54:15 +0100 Subject: [PATCH 195/205] LY-91616 Dyn Veg: Push (up) and Pop (down) Items in Descriptor List (#3013) * LY-91616 Dyn Veg: Push (up) and Pop (down) Items in Descriptor List Signed-off-by: sphrose <82213493+sphrose@users.noreply.github.com> * Changes as per reviews. Signed-off-by: sphrose <82213493+sphrose@users.noreply.github.com> * Additional review changes. Signed-off-by: sphrose <82213493+sphrose@users.noreply.github.com> * review change Signed-off-by: sphrose <82213493+sphrose@users.noreply.github.com> --- .../Components/FancyDocking.cpp | 5 +- .../PropertyEditor/EntityPropertyEditor.cpp | 1117 ++++++++++++++--- .../PropertyEditor/EntityPropertyEditor.hxx | 70 +- .../UI/PropertyEditor/PropertyRowWidget.cpp | 183 ++- .../UI/PropertyEditor/PropertyRowWidget.hxx | 21 + .../ReflectedPropertyEditor.cpp | 224 +++- .../ReflectedPropertyEditor.hxx | 10 + 7 files changed, 1441 insertions(+), 189 deletions(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp index c5aa1a3f88..4ced4ea635 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp @@ -1882,7 +1882,10 @@ namespace AzQtComponents return; } - QApplication::setOverrideCursor(m_dragCursor); + if (!QApplication::overrideCursor()) + { + QApplication::setOverrideCursor(m_dragCursor); + } QPoint relativePressPos = pressPos; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp index f166e85ff9..2c46bb2d26 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp @@ -16,6 +16,7 @@ AZ_POP_DISABLE_WARNING #include #include #include +#include #include #include #include @@ -106,7 +107,11 @@ void initEntityPropertyEditorResources() namespace AzToolsFramework { - static const char* kComponentEditorIndexMimeType = "editor/componentEditorIndices"; + constexpr const char* kComponentEditorIndexMimeType = "editor/componentEditorIndices"; + constexpr const char* kComponentEditorRowWidgetType = "editor/componentEditorRowWidget"; + + constexpr const char* kPropertyEditorMenuActionMoveUp("editor/propertyEditorMoveUp"); + constexpr const char* kPropertyEditorMenuActionMoveDown("editor/propertyEditorMoveDown"); //since component editors are spaced apart to make room for drop indicator, //giving drop logic simple buffer so drops between editors don't go to the bottom @@ -149,6 +154,7 @@ namespace AzToolsFramework : QWidget(parent) , m_editor(editor) , m_dropIndicatorOffset(8) + , m_dropIndicatorRowWidgetOffset(2) { setPalette(Qt::transparent); setWindowFlags(Qt::FramelessWindowHint); @@ -158,22 +164,137 @@ namespace AzToolsFramework } protected: - void paintEvent(QPaintEvent* event) override + static constexpr int TopMargin = 1; + static constexpr int RightMargin = 2; + static constexpr int BottomMargin = 5; + static constexpr int LeftMargin = 2; + static constexpr int RowHighlightIndent = 2; + + void paintDraggingRowWidget(QPainter& painter) { - const int TopMargin = 1; - const int RightMargin = 2; - const int BottomMargin = 5; - const int LeftMargin = 2; + ComponentEditor* rowWidgetEditor = m_editor->GetEditorForCurrentReorderRowWidget(); + PropertyRowWidget* dragRowWidget = m_editor->GetReorderRowWidget(); + PropertyRowWidget* dropTarget = m_editor->GetReorderDropTarget(); + EntityPropertyEditor::DropArea dropArea = m_editor->GetReorderDropArea(); - QWidget::paintEvent(event); + // The user is dragging a row widget. + for (auto componentEditor : m_editor->m_componentEditors) + { + if (!componentEditor->isVisible()) + { + continue; + } - QPainter painter(this); - painter.setCompositionMode(QPainter::CompositionMode_SourceOver); + if (componentEditor != rowWidgetEditor) + { + continue; + } - QRect currRect; + for (auto& [dataNode, rowWidget] : componentEditor->GetPropertyEditor()->GetWidgets()) + { + if (!rowWidget->isVisible()) + { + continue; + } + + QRect globalRect = m_editor->GetWidgetAndVisibleChildrenGlobalRect(rowWidget); + + QRect currRect = QRect( + QPoint(mapFromGlobal(globalRect.topLeft()) + QPoint(LeftMargin, TopMargin)), + QPoint(mapFromGlobal(globalRect.bottomRight()) - QPoint(RightMargin, BottomMargin))); + + currRect.setLeft(LeftMargin + RowHighlightIndent); + currRect.setWidth(rowWidget->GetContainingEditorFrameWidth() - (RightMargin + LeftMargin)); + + if (rowWidget == dragRowWidget) + { + QStyleOption opt; + opt.init(this); + opt.rect = currRect; + qobject_cast (style())->drawDragIndicator(&opt, &painter, this); + } + + if (rowWidget == dropTarget) + { + QRect dropRect = currRect; + if (dropArea == EntityPropertyEditor::DropArea::Above) + { + dropRect.setTop(currRect.top() - m_dropIndicatorRowWidgetOffset); + } + else + { + dropRect.setTop(currRect.bottom()); + } + + dropRect.setHeight(0); + + QStyleOption opt; + opt.init(this); + opt.rect = dropRect; + style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemDrop, &opt, &painter, this); + } + } + } + }; + + void paintMenuHighlight(QPainter& painter, float alpha) + { + // If a RowWidget can be moved up or down, highlight it. + PropertyRowWidget* dragRowWidget = m_editor->GetReorderRowWidget(); + if (!dragRowWidget) + { + return; + } + + PropertyRowWidget* dropTarget = m_editor->GetReorderDropTarget(); + EntityPropertyEditor::DropArea dropArea = m_editor->GetReorderDropArea(); + QPixmap dragImage = m_editor->GetReorderRowWidgetImage(); + + // User has the context menu open with a movable row selected. + QRect globalRect = m_editor->GetWidgetAndVisibleChildrenGlobalRect(dragRowWidget); + + int top = mapFromGlobal(globalRect.topLeft()).y(); + int imageHeight = dragImage.height() / dragImage.devicePixelRatioF(); + int imageWidth = dragImage.width() / dragImage.devicePixelRatioF(); + QRect currRect = QRect(QPoint(LeftMargin + 1, top), QPoint(LeftMargin + 1 + imageWidth, top + imageHeight)); + + painter.setOpacity(alpha); + painter.drawPixmap(currRect, dragImage); + + if (dropTarget) + { + // A move row menu command is highlighted. Draw an indicator to show where the current row will move to. + globalRect = m_editor->GetWidgetAndVisibleChildrenGlobalRect(dropTarget); + QRect dropRect = QRect( + QPoint(mapFromGlobal(globalRect.topLeft()) + QPoint(LeftMargin, TopMargin)), + QPoint(mapFromGlobal(globalRect.bottomRight()) - QPoint(RightMargin, TopMargin))); + + if (dropArea == EntityPropertyEditor::DropArea::Above) + { + dropRect.setTop(dropRect.top() - m_dropIndicatorRowWidgetOffset); + } + else + { + dropRect.setTop(dropRect.bottom()); + } + dropRect.setHeight(0); + + painter.setOpacity(alpha); + QStyleOption lineOpt; + lineOpt.init(this); + lineOpt.rect = dropRect; + style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemDrop, &lineOpt, &painter, this); + painter.setOpacity(1.0f); + } + }; + + void paintDraggingComponent(QPainter& painter) + { bool drag = false; bool drop = false; + QRect currRect; + // Check for a component editor being dragged. for (auto componentEditor : m_editor->m_componentEditors) { if (!componentEditor->isVisible()) @@ -185,8 +306,7 @@ namespace AzToolsFramework currRect = QRect( QPoint(mapFromGlobal(globalRect.topLeft()) + QPoint(LeftMargin, TopMargin)), - QPoint(mapFromGlobal(globalRect.bottomRight()) - QPoint(RightMargin, BottomMargin)) - ); + QPoint(mapFromGlobal(globalRect.bottomRight()) - QPoint(RightMargin, BottomMargin))); currRect.setWidth(currRect.width() - 1); currRect.setHeight(currRect.height() - 1); @@ -226,6 +346,67 @@ namespace AzToolsFramework opt.rect = dropRect; style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemDrop, &opt, &painter, this); } + }; + + void paintMovedRow(QPainter& painter, float alpha) + { + // After a move has been carried out, briefly highlight the moved row. + PropertyRowWidget* rowWidget = m_editor->GetRowToHighlight(); + + if (!rowWidget) + { + return; + } + + QRect globalRect = m_editor->GetWidgetAndVisibleChildrenGlobalRect(rowWidget); + QRect currRect = QRect( + QPoint(mapFromGlobal(globalRect.topLeft()) + QPoint(LeftMargin, TopMargin)), + QPoint(mapFromGlobal(globalRect.bottomRight()) - QPoint(RightMargin, BottomMargin))); + + currRect.setLeft(LeftMargin + 2); + currRect.setWidth(rowWidget->GetContainingEditorFrameWidth() - (RightMargin + LeftMargin)); + + painter.setOpacity(alpha); + + QPen pen; + QColor drawColor = Qt::white; + drawColor.setAlphaF(alpha); + pen.setColor(drawColor); + pen.setWidth(1); + painter.setPen(pen); + painter.drawRect(currRect); + } + + void paintEvent(QPaintEvent* event) override + { + QWidget::paintEvent(event); + + QPainter painter(this); + painter.setCompositionMode(QPainter::CompositionMode_SourceOver); + + EntityPropertyEditor::ReorderState currentState = m_editor->GetReorderState(); + float indicatorAlpha = m_editor->GetMoveIndicatorAlpha(); + + switch (currentState) + { + case EntityPropertyEditor::ReorderState::DraggingRowWidget: + paintDraggingRowWidget(painter); + break; + case EntityPropertyEditor::ReorderState::UsingMenu: + paintMenuHighlight(painter, 1.0f); + break; + case EntityPropertyEditor::ReorderState::MenuOperationInProgress: + paintMenuHighlight(painter, indicatorAlpha); + break; + case EntityPropertyEditor::ReorderState::DraggingComponent: + paintDraggingComponent(painter); + break; + case EntityPropertyEditor::ReorderState::HighlightMovedRow: + paintMovedRow(painter, indicatorAlpha); + break; + default: + break; + } } bool event(QEvent* ev) override @@ -280,6 +461,7 @@ namespace AzToolsFramework private: EntityPropertyEditor* m_editor; int m_dropIndicatorOffset; + int m_dropIndicatorRowWidgetOffset; }; EntityPropertyEditor::SharedComponentInfo::SharedComponentInfo(AZ::Component* component, AZ::Component* sliceReferenceComponent) @@ -382,6 +564,9 @@ namespace AzToolsFramework m_emptyIcon = QIcon(); m_clearIcon = QIcon(":/AssetBrowser/Resources/close.png"); + m_dragIcon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg")); + m_dragCursor = QCursor(m_dragIcon.pixmap(16), 10, 5); + m_serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(m_serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext); AZ_Assert(m_serializeContext, "Failed to acquire application serialize context."); @@ -1867,6 +2052,12 @@ namespace AzToolsFramework return; } + // Don't show if a move operation is pending. + if (m_currentReorderState != ReorderState::Inactive) + { + return; + } + // Locate the owning component and class data corresponding to the clicked node. InstanceDataNode* componentNode = node; while (componentNode->GetParent()) @@ -1905,7 +2096,12 @@ namespace AzToolsFramework if (!menu.actions().empty()) { + m_currentReorderState = EntityPropertyEditor::ReorderState::UsingMenu; menu.exec(position); + if (m_currentReorderState != EntityPropertyEditor::ReorderState::MenuOperationInProgress) + { + m_currentReorderState = EntityPropertyEditor::ReorderState::Inactive; + } } } } @@ -1956,129 +2152,179 @@ namespace AzToolsFramework AZ::SliceComponent* rootSlice = nullptr; AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSlice, contextId, &AzFramework::SliceEntityOwnershipServiceRequestBus::Events::GetRootSlice); - if (!rootSlice) + if (rootSlice) { - return; - } - - AZ::SliceComponent::SliceInstanceAddress address; - AzFramework::SliceEntityRequestBus::EventResult(address, entity->GetId(), - &AzFramework::SliceEntityRequests::GetOwningSlice); - AZ::SliceComponent::SliceReference* sliceReference = address.GetReference(); - if (sliceReference) - { - // This entity is instanced from a slice, so show data push/pull options - AZ::SliceComponent::EntityAncestorList ancestors; - sliceReference->GetInstanceEntityAncestry(entity->GetId(), ancestors); - - AZ_Error("PropertyEditor", !ancestors.empty(), "Entity \"%s\" belongs to a slice, but its source entity could not be located.", entity->GetName().c_str()); - if (!ancestors.empty()) + AZ::SliceComponent::SliceInstanceAddress address; + AzFramework::SliceEntityRequestBus::EventResult(address, entity->GetId(), &AzFramework::SliceEntityRequests::GetOwningSlice); + AZ::SliceComponent::SliceReference* sliceReference = address.GetReference(); + if (sliceReference) { - menu.addSeparator(); + // This entity is instanced from a slice, so show data push/pull options + AZ::SliceComponent::EntityAncestorList ancestors; + sliceReference->GetInstanceEntityAncestry(entity->GetId(), ancestors); - // Populate slice push options. - // Address should start with the fully-addressable component Id to resolve within the target entity. - InstanceDataHierarchy::Address pushFieldAddress; - CalculateAndAdjustNodeAddress(*fieldNode, AddressRootType::RootAtEntity, pushFieldAddress); - if (!pushFieldAddress.empty()) + AZ_Error( + "PropertyEditor", !ancestors.empty(), "Entity \"%s\" belongs to a slice, but its source entity could not be located.", + entity->GetName().c_str()); + if (!ancestors.empty()) { - SliceUtilities::PopulateQuickPushMenu( - menu, - entity->GetId(), - pushFieldAddress, - SliceUtilities::QuickPushMenuOptions("Save field override", SliceUtilities::QuickPushMenuOverrideDisplayCount::ShowOverrideCountOnlyWhenMultiple)); + menu.addSeparator(); + + // Populate slice push options. + // Address should start with the fully-addressable component Id to resolve within the target entity. + InstanceDataHierarchy::Address pushFieldAddress; + CalculateAndAdjustNodeAddress(*fieldNode, AddressRootType::RootAtEntity, pushFieldAddress); + if (!pushFieldAddress.empty()) + { + SliceUtilities::PopulateQuickPushMenu( + menu, entity->GetId(), pushFieldAddress, + SliceUtilities::QuickPushMenuOptions( + "Save field override", + SliceUtilities::QuickPushMenuOverrideDisplayCount::ShowOverrideCountOnlyWhenMultiple)); + } } } - } - menu.addSeparator(); + menu.addSeparator(); - // by leaf node, we mean a visual leaf node in the property editor (ie, we do not have any visible children) - bool isLeafNode = !fieldNode->GetClassMetadata() || !fieldNode->GetClassMetadata()->m_container; + // by leaf node, we mean a visual leaf node in the property editor (ie, we do not have any visible children) + bool isLeafNode = !fieldNode->GetClassMetadata() || !fieldNode->GetClassMetadata()->m_container; - if (isLeafNode) - { - for (const InstanceDataNode& childNode : fieldNode->GetChildren()) + if (isLeafNode) { - if (HasAnyVisibleElements(childNode)) + for (const InstanceDataNode& childNode : fieldNode->GetChildren()) { - // If we have any visible children, we must not be a leaf node - isLeafNode = false; - break; + if (HasAnyVisibleElements(childNode)) + { + // If we have any visible children, we must not be a leaf node + isLeafNode = false; + break; + } } } - } #ifdef ENABLE_SLICE_EDITOR - // Show PreventOverride & HideProperty options - if (GetEntityDataPatchAddress(fieldNode, m_dataPatchAddressBuffer)) - { - AZ::DataPatch::Flags nodeFlags = rootSlice->GetEntityDataFlagsAtAddress(entity->GetId(), m_dataPatchAddressBuffer); + // Show PreventOverride & HideProperty options + if (GetEntityDataPatchAddress(fieldNode, m_dataPatchAddressBuffer)) + { + AZ::DataPatch::Flags nodeFlags = rootSlice->GetEntityDataFlagsAtAddress(entity->GetId(), m_dataPatchAddressBuffer); - if (nodeFlags & AZ::DataPatch::Flag::PreventOverrideSet) - { - QAction* PreventOverrideAction = menu.addAction(tr("Allow property override")); - PreventOverrideAction->setEnabled(isLeafNode); - connect(PreventOverrideAction, &QAction::triggered, this, [this, fieldNode] + if (nodeFlags & AZ::DataPatch::Flag::PreventOverrideSet) { - ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::PreventOverrideSet, false); - InvalidatePropertyDisplay(Refresh_AttributesAndValues); + QAction* PreventOverrideAction = menu.addAction(tr("Allow property override")); + PreventOverrideAction->setEnabled(isLeafNode); + connect( + PreventOverrideAction, &QAction::triggered, this, + [this, fieldNode] + { + ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::PreventOverrideSet, false); + InvalidatePropertyDisplay(Refresh_AttributesAndValues); + }); } - ); - } - else - { - QAction* PreventOverrideAction = menu.addAction(tr("Prevent property override")); - PreventOverrideAction->setEnabled(isLeafNode); - connect(PreventOverrideAction, &QAction::triggered, this, [this, fieldNode] + else { - ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::PreventOverrideSet, true); - InvalidatePropertyDisplay(Refresh_AttributesAndValues); + QAction* PreventOverrideAction = menu.addAction(tr("Prevent property override")); + PreventOverrideAction->setEnabled(isLeafNode); + connect( + PreventOverrideAction, &QAction::triggered, this, + [this, fieldNode] + { + ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::PreventOverrideSet, true); + InvalidatePropertyDisplay(Refresh_AttributesAndValues); + }); } - ); - } - if (nodeFlags & AZ::DataPatch::Flag::HidePropertySet) - { - QAction* HideProperyAction = menu.addAction(tr("Show property on instances")); - HideProperyAction->setEnabled(isLeafNode); - connect(HideProperyAction, &QAction::triggered, this, [this, fieldNode] + if (nodeFlags & AZ::DataPatch::Flag::HidePropertySet) { - ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::HidePropertySet, false); - InvalidatePropertyDisplay(Refresh_AttributesAndValues); + QAction* HideProperyAction = menu.addAction(tr("Show property on instances")); + HideProperyAction->setEnabled(isLeafNode); + connect( + HideProperyAction, &QAction::triggered, this, + [this, fieldNode] + { + ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::HidePropertySet, false); + InvalidatePropertyDisplay(Refresh_AttributesAndValues); + }); } - ); - } - else - { - QAction* HideProperyAction = menu.addAction(tr("Hide property on instances")); - HideProperyAction->setEnabled(isLeafNode); - connect(HideProperyAction, &QAction::triggered, this, [this, fieldNode] + else { - ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::HidePropertySet, true); - InvalidatePropertyDisplay(Refresh_AttributesAndValues); + QAction* HideProperyAction = menu.addAction(tr("Hide property on instances")); + HideProperyAction->setEnabled(isLeafNode); + connect( + HideProperyAction, &QAction::triggered, this, + [this, fieldNode] + { + ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::HidePropertySet, true); + InvalidatePropertyDisplay(Refresh_AttributesAndValues); + }); } - ); } - } #endif - if (sliceReference) - { - // This entity is referenced from a slice, so show property override options - bool hasChanges = fieldNode->HasChangesVersusComparison(false); - - if (!hasChanges && isLeafNode) + if (sliceReference) { - // Add an option to set the ForceOverride flag for this field - menu.setToolTipsVisible(true); - QAction* forceOverrideAction = menu.addAction(tr("Force property override")); - forceOverrideAction->setToolTip(tr("Prevents a property from inheriting from its source slice")); - connect(forceOverrideAction, &QAction::triggered, this, [this, fieldNode]() - { - ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::ForceOverrideSet, true); - } - ); + // This entity is referenced from a slice, so show property override options + bool hasChanges = fieldNode->HasChangesVersusComparison(false); + + if (!hasChanges && isLeafNode) + { + // Add an option to set the ForceOverride flag for this field + menu.setToolTipsVisible(true); + QAction* forceOverrideAction = menu.addAction(tr("Force property override")); + forceOverrideAction->setToolTip(tr("Prevents a property from inheriting from its source slice")); + connect( + forceOverrideAction, &QAction::triggered, this, + [this, fieldNode]() + { + ContextMenuActionSetDataFlag(fieldNode, AZ::DataPatch::Flag::ForceOverrideSet, true); + }); + } + } + } + + m_reorderRowWidget = nullptr; + // Add move up/down actions if appropriate + auto componentEditorIterator = m_componentToEditorMap.find(componentInstance); + AZ_Assert(componentEditorIterator != m_componentToEditorMap.end(), "Unable to find a component editor for the given component"); + if (componentEditorIterator != m_componentToEditorMap.end()) + { + m_reorderRowWidgetEditor = componentEditorIterator->second; + PropertyRowWidget* widget = componentEditorIterator->second->GetPropertyEditor()->GetWidgetFromNode(fieldNode); + if (widget->CanBeReordered()) + { + m_reorderRowWidget = widget; + SetRowWidgetHighlighted(widget); + + QAction* moveUpAction = menu.addAction(tr("Move %1 Up").arg(widget->GetNameLabel()->text())); + moveUpAction->setEnabled(false); + moveUpAction->setData(kPropertyEditorMenuActionMoveUp); + + if (widget->CanMoveUp()) + { + moveUpAction->setEnabled(true); + connect( + moveUpAction, &QAction::triggered, this, + [this, widget] + { + ContextMenuActionMoveItemUp(m_reorderRowWidgetEditor, widget); + }); + } + + QAction* moveDownAction = menu.addAction(tr("Move %1 Down").arg(widget->GetNameLabel()->text())); + moveDownAction->setEnabled(false); + moveDownAction->setData(kPropertyEditorMenuActionMoveDown); + if (widget->CanMoveDown()) + { + moveDownAction->setEnabled(true); + connect( + moveDownAction, &QAction::triggered, this, + [this, widget] + { + ContextMenuActionMoveItemDown(m_reorderRowWidgetEditor, widget); + }); + } + + menu.addSeparator(); } } } @@ -2380,6 +2626,98 @@ namespace AzToolsFramework } } + void EntityPropertyEditor::BeginMoveRowWidgetFade() + { + // Fade out the highlights and indicator bar for two seconds before moving. + m_moveFadeSecondsRemaining = MoveFadeSeconds; + m_currentReorderState = EntityPropertyEditor::ReorderState::MenuOperationInProgress; + AZ::TickBus::Handler::BusConnect(); + } + + void EntityPropertyEditor::HighlightMovedRowWidget() + { + if (m_currentReorderState != ReorderState::WaitForRedraw) + { + return; + } + UpdateOverlay(); + + m_currentReorderState = ReorderState::HighlightMovedRow; + m_moveFadeSecondsRemaining = MoveFadeSeconds; + + AZ::TickBus::Handler::BusConnect(); + m_overlay->setVisible(true); + } + + void EntityPropertyEditor::OnTick(float deltaTime, AZ::ScriptTimePoint /*time*/) + { + m_moveFadeSecondsRemaining -= deltaTime; + m_overlay->setVisible(true); + if (m_moveFadeSecondsRemaining <= 0.0f) + { + m_moveFadeSecondsRemaining = 0.0f; + + if (m_currentReorderState == ReorderState::MenuOperationInProgress) + { + m_reorderRowWidgetEditor->GetPropertyEditor()->MoveNodeToIndex(m_nodeToMove, m_indexMapOfMovedRow[0]); + + // Ensure the highlight gets drawn once the RPE is updated. + m_currentReorderState = ReorderState::WaitForRedraw; + AZ::TickBus::Handler::BusDisconnect(); + ScrollToNewComponent(); + } + else + { + m_currentReorderState = ReorderState::Inactive; + AZ::TickBus::Handler::BusDisconnect(); + m_overlay->setVisible(false); + } + } + + // Force a repaint to show the fade. + repaint(0, 0, -1, -1); + } + + void EntityPropertyEditor::GenerateRowWidgetIndexMapToChildIndex(PropertyRowWidget* parent, int destIndex) + { + m_indexMapOfMovedRow.clear(); + m_indexMapOfMovedRow.push_back(destIndex); + + while (parent) + { + int index = parent->GetIndexInParent(); + if (index < 0) + { + // Top level widget. + break; + } + m_indexMapOfMovedRow.push_back(parent->GetIndexInParent()); + parent = parent->GetParentRow(); + } + } + + void EntityPropertyEditor::ContextMenuActionMoveItemUp(ComponentEditor* componentEditor, PropertyRowWidget* rowWidget) + { + // After the RPE is rebuilt, there'll be no way to work out which is the moved RowWidget. + // Generate a map of the child indices up to the root. + PropertyRowWidget* parent = rowWidget->GetParentRow(); + GenerateRowWidgetIndexMapToChildIndex(parent, rowWidget->GetIndexInParent() - 1); + + m_reorderRowWidgetEditor = componentEditor; + m_nodeToMove = rowWidget->GetNode(); + BeginMoveRowWidgetFade(); + } + + void EntityPropertyEditor::ContextMenuActionMoveItemDown(ComponentEditor* componentEditor, PropertyRowWidget* rowWidget) + { + PropertyRowWidget* parent = rowWidget->GetParentRow(); + GenerateRowWidgetIndexMapToChildIndex(parent, rowWidget->GetIndexInParent() + 1); + + m_reorderRowWidgetEditor = componentEditor; + m_nodeToMove = rowWidget->GetNode(); + BeginMoveRowWidgetFade(); + } + void EntityPropertyEditor::CalculateAndAdjustNodeAddress(const InstanceDataNode& componentFieldNode, AddressRootType rootType, InstanceDataNode::Address& outAddress) const { outAddress = componentFieldNode.ComputeAddress(); @@ -2763,9 +3101,7 @@ namespace AzToolsFramework if (!menu.actions().empty()) { - m_isShowingContextMenu = true; menu.exec(position); - m_isShowingContextMenu = false; } } @@ -3463,6 +3799,76 @@ namespace AzToolsFramework return this == widget || isAncestorOf(widget); } + AZ::u32 EntityPropertyEditor::GetHeightOfRowAndVisibleChildren(const PropertyRowWidget* row) const + { + if (!row->isVisible()) + { + return 0; + } + + QRect rect = QRect(row->mapToGlobal(row->rect().topLeft()), row->mapToGlobal(row->rect().bottomRight())); + + AZ::u32 height = rect.height() + 1; + + for (AZ::u32 childIndex = 0; childIndex < row->GetChildRowCount(); childIndex++) + { + PropertyRowWidget* childRow = row->GetChildRowByIndex(childIndex); + if (childRow->isVisible()) + { + height += GetHeightOfRowAndVisibleChildren(childRow); + } + } + + return height; + } + + QRect EntityPropertyEditor::GetWidgetAndVisibleChildrenGlobalRect(const PropertyRowWidget* widget) const + { + QRect rect = QRect(widget->mapToGlobal(widget->rect().topLeft()), widget->mapToGlobal(widget->rect().bottomRight())); + rect.setHeight(GetHeightOfRowAndVisibleChildren(widget)); + + return rect; + } + + PropertyRowWidget* EntityPropertyEditor::GetRowWidgetAtSameLevelAfter(PropertyRowWidget* widget) const + { + PropertyRowWidget* parent = widget->GetParentRow(); + + bool found = false; + for (PropertyRowWidget* child : parent->GetChildrenRows()) + { + if (found) + { + return child; + } + + if (child == widget) + { + found = true; + } + } + + return nullptr; + } + + PropertyRowWidget* EntityPropertyEditor::GetRowWidgetAtSameLevelBefore(PropertyRowWidget* widget) const + { + PropertyRowWidget* parent = widget->GetParentRow(); + + PropertyRowWidget* previous = nullptr; + for (PropertyRowWidget* child : parent->GetChildrenRows()) + { + if (child == widget) + { + return previous; + } + + previous = child; + } + + return nullptr; + } + QRect EntityPropertyEditor::GetWidgetGlobalRect(const QWidget* widget) const { return QRect( @@ -3757,6 +4163,8 @@ namespace AzToolsFramework m_shouldScrollToNewComponents = false; m_shouldScrollToNewComponentsQueued = false; m_newComponentId.reset(); + + HighlightMovedRowWidget(); } void EntityPropertyEditor::QueueScrollToNewComponent() @@ -3909,9 +4317,64 @@ namespace AzToolsFramework event->accept(); } + bool EntityPropertyEditor::HandleMenuEvent(QObject* /*object*/, QEvent* event) + { + QMenu* menu = qobject_cast(QApplication::activePopupWidget()); + if (!menu) + { + return false; + } + + PropertyRowWidget* lastReorderDropTarget = m_reorderDropTarget; + + switch (event->type()) + { + case QEvent::Leave: + m_reorderDropTarget = nullptr; + break; + case QEvent::Enter: + // Drop through. + case QEvent::MouseMove: + QMouseEvent* originalMouseEvent = static_cast(event); + QAction* action = menu->actionAt(originalMouseEvent->pos()); + if (!action) + { + m_reorderDropTarget = nullptr; + break; + } + + if (action->data() == kPropertyEditorMenuActionMoveUp) + { + m_reorderDropTarget = GetRowWidgetAtSameLevelBefore(m_reorderRowWidget); + + m_reorderDropArea = EntityPropertyEditor::DropArea::Above; + } + else if (action->data() == kPropertyEditorMenuActionMoveDown) + { + m_reorderDropTarget = GetRowWidgetAtSameLevelAfter(m_reorderRowWidget); + + if (m_reorderDropTarget) + { + m_reorderDropArea = EntityPropertyEditor::DropArea::Below; + } + } + + break; + } + + if (lastReorderDropTarget != m_reorderDropTarget) + { + // Force a redraw as the menu is preventing automatic updates. + repaint(0, 0, -1, -1); + } + + return false; + } + //overridden to intercept application level mouse events for component editor selection bool EntityPropertyEditor::eventFilter(QObject* object, QEvent* event) { + HandleMenuEvent(object, event); HandleSelectionEvents(object, event); return false; } @@ -3919,11 +4382,23 @@ namespace AzToolsFramework void EntityPropertyEditor::mousePressEvent(QMouseEvent* event) { ResetDrag(event); + + PropertyRowWidget* rowWidget = FindPropertyRowWidgetAt(event->globalPos()); + if (rowWidget && rowWidget->CanBeReordered() && event->buttons() & Qt::LeftButton) + { + QApplication::setOverrideCursor(m_dragCursor); + } } void EntityPropertyEditor::mouseReleaseEvent(QMouseEvent* event) { ResetDrag(event); + + Qt::MouseButtons realButtons = QApplication::mouseButtons(); + if (QApplication::overrideCursor() && !(event->buttons() & Qt::LeftButton)) + { + QApplication::restoreOverrideCursor(); + } } void EntityPropertyEditor::mouseMoveEvent(QMouseEvent* event) @@ -3963,6 +4438,21 @@ namespace AzToolsFramework void EntityPropertyEditor::dropEvent(QDropEvent* event) { HandleDrop(event); + + if (QApplication::overrideCursor()) + { + QApplication::restoreOverrideCursor(); + } + } + + void EntityPropertyEditor::DragStopped() + { + if (QApplication::overrideCursor()) + { + QApplication::restoreOverrideCursor(); + } + + EndRowWidgetReorder(); } bool EntityPropertyEditor::HandleSelectionEvents(QObject* object, QEvent* event) @@ -4319,11 +4809,110 @@ namespace AzToolsFramework return true; } + bool EntityPropertyEditor::FindAllowedRowWidgetReorderDropTarget(const QPoint& globalPos) + { + const QRect globalRect(globalPos, globalPos); + + AZ_Assert(m_reorderRowWidgetEditor, "Missing editor for row widget drag."); + + AzToolsFramework::ReflectedPropertyEditor::WidgetList widgets = m_reorderRowWidgetEditor->GetPropertyEditor()->GetWidgets(); + for (auto widgetPair : widgets) + { + PropertyRowWidget* widget = widgetPair.second; + if (!widget) + { + continue; + } + + if (DoesIntersectWidget(globalRect, reinterpret_cast(widget))) + { + if (widget->CanBeReordered() && widget->GetParentRow() == m_reorderRowWidget->GetParentRow()) + { + m_reorderDropTarget = widget; + + QRect widgetRect = GetWidgetAndVisibleChildrenGlobalRect(widget); + if (globalPos.y() < widgetRect.center().y()) + { + m_reorderDropArea = EntityPropertyEditor::DropArea::Above; + } + else + { + m_reorderDropArea = EntityPropertyEditor::DropArea::Below; + } + + return true; + } + + // We're hovering over a child of a reorderable ancestor, use the ancestor as the drop target. + PropertyRowWidget* parent = widget->GetParentRow(); + while (parent) + { + if (parent->CanBeReordered() && parent->GetParentRow() == m_reorderRowWidget->GetParentRow()) + { + m_reorderDropTarget = parent; + + QRect widgetRect = GetWidgetAndVisibleChildrenGlobalRect(parent); + if (globalPos.y() < widgetRect.center().y()) + { + m_reorderDropArea = EntityPropertyEditor::DropArea::Above; + } + else + { + m_reorderDropArea = EntityPropertyEditor::DropArea::Below; + } + + return true; + } + parent = parent->GetParentRow(); + } + } + } + + return false; + } + + bool EntityPropertyEditor::UpdateRowWidgetDrag(const QPoint& localPos, Qt::MouseButtons mouseButtons, const QMimeData* /*mimeData*/) + { + const QPoint globalPos(mapToGlobal(localPos)); + const QRect globalRect(globalPos, globalPos); + + if (!m_reorderRowWidget) + { + return false; + } + + if (m_reorderDropTarget) + { + m_reorderDropTarget = nullptr; + } + + UpdateOverlay(); + + // additional checks since handling is done in event filter + if ((mouseButtons & Qt::LeftButton) && DoesIntersectWidget(globalRect, this)) + { + FindAllowedRowWidgetReorderDropTarget(globalPos); + { + UpdateOverlay(); + return true; + } + } + return false; + } + bool EntityPropertyEditor::UpdateDrag(const QPoint& localPos, Qt::MouseButtons mouseButtons, const QMimeData* mimeData) { const QPoint globalPos(mapToGlobal(localPos)); const QRect globalRect(globalPos, globalPos); + if (m_reorderRowWidget) + { + UpdateRowWidgetDrag(localPos, mouseButtons, mimeData); + QueueAutoScroll(); + UpdateOverlay(); + return true; + } + //reset drop indicators for (auto componentEditor : m_componentEditors) { @@ -4357,6 +4946,28 @@ namespace AzToolsFramework return false; } + PropertyRowWidget* EntityPropertyEditor::FindPropertyRowWidgetAt(QPoint globalPos) + { + const QRect globalRect(globalPos, globalPos); + + const bool dragSelected = DoesIntersectSelectedComponentEditor(globalRect); + const auto& componentEditors = dragSelected ? GetSelectedComponentEditors() : GetIntersectingComponentEditors(globalRect); + + for (auto componentEditor : componentEditors) + { + AzToolsFramework::ReflectedPropertyEditor::WidgetList widgets = componentEditor->GetPropertyEditor()->GetWidgets(); + for (auto& [dataNode, rowWidget] : widgets) + { + if (DoesIntersectWidget(globalRect, reinterpret_cast(rowWidget)) && rowWidget->CanBeReordered()) + { + return rowWidget; + } + } + } + + return nullptr; + } + bool EntityPropertyEditor::StartDrag(QMouseEvent* event) { // do not initiate a drag if property editor is disabled @@ -4402,7 +5013,27 @@ namespace AzToolsFramework if (!intersectsHeader) { - return false; + for (auto componentEditor : componentEditors) + { + AzToolsFramework::ReflectedPropertyEditor::WidgetList widgets = componentEditor->GetPropertyEditor()->GetWidgets(); + for (AZStd::pair w : widgets) + { + if (w.second) + { + if (DoesIntersectWidget(dragRect, reinterpret_cast(w.second)) && w.second->CanBeReordered()) + { + m_currentReorderState = EntityPropertyEditor::ReorderState::DraggingRowWidget; + m_reorderRowWidget = w.second; + m_reorderRowWidgetEditor = componentEditor; + if (m_reorderDropTarget) + { + m_reorderDropTarget = nullptr; + } + break; + } + } + } + } } m_dragStarted = true; @@ -4412,105 +5043,166 @@ namespace AzToolsFramework QRect dragImageRect; - AZStd::vector componentEditorIndices; - componentEditorIndices.reserve(componentEditors.size()); - for (auto componentEditor : componentEditors) + if (m_reorderRowWidget) { - //compute the drag image size - if (componentEditorIndices.empty()) - { - dragImageRect = componentEditor->rect(); - } - else - { - dragImageRect.setHeight(dragImageRect.height() + componentEditor->rect().height()); - } + // We're dragging a PropertyRowWidget, grab the image from that. + mimeData->setData(kComponentEditorRowWidgetType, QByteArray()); - //add component editor index to drag data - auto componentEditorIndex = GetComponentEditorIndex(componentEditor); - if (componentEditorIndex >= 0) - { - componentEditorIndices.push_back(GetComponentEditorIndex(componentEditor)); - } + drag->setMimeData(mimeData); + drag->setPixmap(m_reorderRowWidget->createDragImage( + QColor("#8E863E"), QColor("#EAECAA"), 0.5f, PropertyRowWidget::DragImageType::SingleRow)); + drag->setHotSpot(m_dragStartPosition - GetWidgetGlobalRect(m_reorderRowWidget).topLeft()); + drag->setDragCursor(m_dragIcon.pixmap(32), Qt::DropAction::MoveAction); + // Ensure we can tidy up if the drop happens elsewhere. + connect(drag, &QObject::destroyed, this, &EntityPropertyEditor::DragStopped); + drag->exec(Qt::MoveAction, Qt::MoveAction); } - - //build image from dragged editor UI - QImage dragImage(dragImageRect.size(), QImage::Format_ARGB32_Premultiplied); - QPainter painter(&dragImage); - painter.setCompositionMode(QPainter::CompositionMode_Source); - painter.fillRect(dragImageRect, Qt::transparent); - painter.setCompositionMode(QPainter::CompositionMode_SourceOver); - painter.setOpacity(0.5f); - - //render a vertical stack of component editors, may change to render just the headers - QPoint dragImageOffset(0, 0); - for (AZ::s32 index : componentEditorIndices) + else { - auto componentEditor = GetComponentEditorsFromIndex(index); - if (componentEditor) + AZStd::vector componentEditorIndices; + componentEditorIndices.reserve(componentEditors.size()); + for (auto componentEditor : componentEditors) { - if (DoesIntersectWidget(dragRect, componentEditor)) + // compute the drag image size + if (componentEditorIndices.empty()) { - //offset drag image from the drag start position - drag->setHotSpot(dragImageOffset + (m_dragStartPosition - GetWidgetGlobalRect(componentEditor).topLeft())); + dragImageRect = componentEditor->rect(); + } + else + { + dragImageRect.setHeight(dragImageRect.height() + componentEditor->rect().height()); } - //render the component editor to the drag image - componentEditor->render(&painter, dragImageOffset); - - //update the render offset by the component editor height - dragImageOffset.setY(dragImageOffset.y() + componentEditor->rect().height()); + // add component editor index to drag data + auto componentEditorIndex = GetComponentEditorIndex(componentEditor); + if (componentEditorIndex >= 0) + { + componentEditorIndices.push_back(GetComponentEditorIndex(componentEditor)); + } } - } - painter.end(); - //mark dragged components after drag initiated to draw indicators - for (AZ::s32 index : componentEditorIndices) - { - auto componentEditor = GetComponentEditorsFromIndex(index); - if (componentEditor) + // build image from dragged editor UI + QImage dragImage(dragImageRect.size(), QImage::Format_ARGB32_Premultiplied); + QPainter painter(&dragImage); + painter.setCompositionMode(QPainter::CompositionMode_Source); + painter.fillRect(dragImageRect, Qt::transparent); + painter.setCompositionMode(QPainter::CompositionMode_SourceOver); + painter.setOpacity(0.5f); + + // render a vertical stack of component editors, may change to render just the headers + QPoint dragImageOffset(0, 0); + for (AZ::s32 index : componentEditorIndices) { - componentEditor->SetDragged(true); + auto componentEditor = GetComponentEditorsFromIndex(index); + if (componentEditor) + { + if (DoesIntersectWidget(dragRect, componentEditor)) + { + // offset drag image from the drag start position + drag->setHotSpot(dragImageOffset + (m_dragStartPosition - GetWidgetGlobalRect(componentEditor).topLeft())); + } + + // render the component editor to the drag image + componentEditor->render(&painter, dragImageOffset); + + // update the render offset by the component editor height + dragImageOffset.setY(dragImageOffset.y() + componentEditor->rect().height()); + } } - } - UpdateOverlay(); + painter.end(); - //encode component editor indices as internal drag data - mimeData->setData( - kComponentEditorIndexMimeType, - QByteArray(reinterpret_cast(componentEditorIndices.data()), static_cast(componentEditorIndices.size() * sizeof(AZ::s32)))); - - drag->setMimeData(mimeData); - drag->setPixmap(QPixmap::fromImage(dragImage)); - drag->exec(Qt::MoveAction, Qt::MoveAction); - - //mark dragged components after drag completed to stop drawing indicators - for (AZ::s32 index : componentEditorIndices) - { - auto componentEditor = GetComponentEditorsFromIndex(index); - if (componentEditor) + // mark dragged components after drag initiated to draw indicators + for (AZ::s32 index : componentEditorIndices) { - componentEditor->SetDragged(false); + auto componentEditor = GetComponentEditorsFromIndex(index); + if (componentEditor) + { + componentEditor->SetDragged(true); + } + } + UpdateOverlay(); + + // encode component editor indices as internal drag data + mimeData->setData( + kComponentEditorIndexMimeType, + QByteArray( + reinterpret_cast(componentEditorIndices.data()), + static_cast(componentEditorIndices.size() * sizeof(AZ::s32)))); + + drag->setMimeData(mimeData); + drag->setPixmap(QPixmap::fromImage(dragImage)); + drag->exec(Qt::MoveAction, Qt::MoveAction); + + // mark dragged components after drag completed to stop drawing indicators + for (AZ::s32 index : componentEditorIndices) + { + auto componentEditor = GetComponentEditorsFromIndex(index); + if (componentEditor) + { + componentEditor->SetDragged(false); + } } } + UpdateOverlay(); return true; } + void EntityPropertyEditor::SetRowWidgetHighlighted(PropertyRowWidget* rowWidget) + { + m_reorderRowWidget = rowWidget; + m_reorderRowImage = rowWidget->createDragImage( + QColor("#8E863E"), QColor("#EAECAA"), 0.5f, PropertyRowWidget::DragImageType::IncludeVisibleChildren); + } + + void EntityPropertyEditor::EndRowWidgetReorder() + { + m_reorderDropTarget = nullptr; + m_reorderRowWidget = nullptr; + m_reorderDropTarget = nullptr; + m_currentReorderState = EntityPropertyEditor::ReorderState::Inactive; + m_overlay->setVisible(false); + } + bool EntityPropertyEditor::HandleDrop(QDropEvent* event) { const QPoint globalPos(mapToGlobal(event->pos())); const QMimeData* mimeData = event->mimeData(); - if (IsDropAllowed(mimeData, globalPos)) + + if (m_currentReorderState == EntityPropertyEditor::ReorderState::DraggingRowWidget) { - //handle drop for supported mime types - HandleDropForComponentTypes(event); - HandleDropForComponentAssets(event); - HandleDropForAssetBrowserEntries(event); - HandleDropForComponentReorder(event); + if (FindAllowedRowWidgetReorderDropTarget(globalPos)) + { + if (m_reorderDropArea == EntityPropertyEditor::DropArea::Above) + { + m_reorderRowWidgetEditor->GetPropertyEditor()->MoveNodeBefore( + m_reorderRowWidget->GetNode(), m_reorderDropTarget->GetNode()); + } + else + { + m_reorderRowWidgetEditor->GetPropertyEditor()->MoveNodeAfter( + m_reorderRowWidget->GetNode(), m_reorderDropTarget->GetNode()); + } + } + event->acceptProposedAction(); - return true; + + EndRowWidgetReorder(); } + else + { + if (IsDropAllowed(mimeData, globalPos)) + { + // handle drop for supported mime types + HandleDropForComponentTypes(event); + HandleDropForComponentAssets(event); + HandleDropForAssetBrowserEntries(event); + HandleDropForComponentReorder(event); + event->acceptProposedAction(); + return true; + } + } + return false; } @@ -5036,6 +5728,69 @@ namespace AzToolsFramework componentEditor->ActiveComponentModeChanged(componentType); } } + + EntityPropertyEditor::ReorderState EntityPropertyEditor::GetReorderState() const + { + return m_currentReorderState; + } + + ComponentEditor* EntityPropertyEditor::GetEditorForCurrentReorderRowWidget() const + { + return m_reorderRowWidgetEditor; + } + + PropertyRowWidget* EntityPropertyEditor::GetReorderRowWidget() const + { + return m_reorderRowWidget; + } + + PropertyRowWidget* EntityPropertyEditor::GetReorderDropTarget() const + { + return m_reorderDropTarget; + } + + EntityPropertyEditor::DropArea EntityPropertyEditor::GetReorderDropArea() const + { + return m_reorderDropArea; + } + + QPixmap EntityPropertyEditor::GetReorderRowWidgetImage() const + { + return m_reorderRowImage; + } + + float EntityPropertyEditor::GetMoveIndicatorAlpha() const + { + if (m_currentReorderState != ReorderState::MenuOperationInProgress) + { + return 1.0f; + } + + return m_moveFadeSecondsRemaining / MoveFadeSeconds; + } + + PropertyRowWidget* EntityPropertyEditor::GetRowToHighlight() + { + // Use the pregenerated map to find the RowWidget that's in the new position. + QSet rowWidgets = m_reorderRowWidgetEditor->GetPropertyEditor()->GetTopLevelWidgets(); + if (rowWidgets.isEmpty()) + { + return nullptr; + } + + PropertyRowWidget* highlightRow = *rowWidgets.begin(); + + int mapIndex = static_cast(m_indexMapOfMovedRow.size() - 1); + + while (mapIndex >= 0) + { + int mapEntry = m_indexMapOfMovedRow[mapIndex]; + highlightRow = highlightRow->GetChildrenRows()[mapEntry]; + mapIndex--; + } + + return highlightRow; + } } StatusComboBox::StatusComboBox(QWidget* parent) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx index 166d4c4392..3ff69f80e0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -110,6 +111,7 @@ namespace AzToolsFramework , public EditorInspectorComponentNotificationBus::MultiHandler , private AzToolsFramework::ComponentModeFramework::EditorComponentModeNotificationBus::Handler , public AZ::EntitySystemBus::Handler + , public AZ::TickBus::Handler , private EditorWindowUIRequestBus::Handler { Q_OBJECT; @@ -117,6 +119,23 @@ namespace AzToolsFramework AZ_CLASS_ALLOCATOR(EntityPropertyEditor, AZ::SystemAllocator, 0) + enum class ReorderState + { + Inactive, // No row widget reordering operation is in progress. + DraggingComponent, // User is dragging a component editor. + DraggingRowWidget, // User is dragging a row widget around. + UsingMenu, // User has the context menu open and may hover over a move up/down operation. + MenuOperationInProgress, // User has selected a move/up down menu item. + WaitForRedraw, // Wait for rebuild of RPE. + HighlightMovedRow // User has moved a row, highlight the new position. + }; + + enum class DropArea + { + Above, + Below + }; + EntityPropertyEditor(QWidget* pParent = NULL, Qt::WindowFlags flags = Qt::WindowFlags(), bool isLevelEntityEditor = false); virtual ~EntityPropertyEditor(); @@ -151,6 +170,16 @@ namespace AzToolsFramework bool IsLockedToSpecificEntities() const { return !m_overrideSelectedEntityIds.empty(); } static bool AreComponentsCopyable(const AZ::Entity::ComponentArrayType& components, const ComponentFilter& filter); + + ReorderState GetReorderState() const; + ComponentEditor* GetEditorForCurrentReorderRowWidget() const; + PropertyRowWidget* GetReorderRowWidget() const; + PropertyRowWidget* GetReorderDropTarget() const; + DropArea GetReorderDropArea() const; + QPixmap GetReorderRowWidgetImage() const; + float GetMoveIndicatorAlpha() const; + PropertyRowWidget* GetRowToHighlight(); + Q_SIGNALS: void SelectedEntityNameChanged(const AZ::EntityId& entityId, const AZStd::string& name); @@ -211,6 +240,9 @@ namespace AzToolsFramework void GetSelectedEntities(EntityIdList& selectedEntityIds) override; void SetNewComponentId(AZ::ComponentId componentId) override; + // TickBus + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + // EditorWindowRequestBus overrides void SetEditorUiEnabled(bool enable) override; @@ -253,6 +285,10 @@ namespace AzToolsFramework void ContextMenuActionPullFieldData(AZ::Component* parentComponent, InstanceDataNode* fieldNode); void ContextMenuActionSetDataFlag(InstanceDataNode* node, AZ::DataPatch::Flag flag, bool additive); + void GenerateRowWidgetIndexMapToChildIndex(PropertyRowWidget* parent, int destIndex); + void ContextMenuActionMoveItemUp(ComponentEditor* componentEditor, PropertyRowWidget* rowWidget); + void ContextMenuActionMoveItemDown(ComponentEditor* componentEditor, PropertyRowWidget* rowWidget); + /// Given an InstanceDataNode, calculate a DataPatch address relative to the entity. /// @return true if successful. bool GetEntityDataPatchAddress(const InstanceDataNode* componentFieldNode, AZ::DataPatch::AddressType& dataPatchAddressOut, AZ::EntityId* entityIdOut = nullptr) const; @@ -341,8 +377,6 @@ namespace AzToolsFramework QAction* m_actionToMoveComponentsBottom = nullptr; QAction* m_resetToSliceAction = nullptr; - bool m_isShowingContextMenu = false; - void CreateActions(); void UpdateActions(); @@ -390,6 +424,10 @@ namespace AzToolsFramework void ResetToSlice(); bool DoesOwnFocus() const; + AZ::u32 GetHeightOfRowAndVisibleChildren(const PropertyRowWidget* row) const; + QRect GetWidgetAndVisibleChildrenGlobalRect(const PropertyRowWidget* widget) const; + PropertyRowWidget* GetRowWidgetAtSameLevelAfter(PropertyRowWidget* widget) const; + PropertyRowWidget* GetRowWidgetAtSameLevelBefore(PropertyRowWidget* widget) const; QRect GetWidgetGlobalRect(const QWidget* widget) const; bool DoesIntersectWidget(const QRect& globalRect, const QWidget* widget) const; bool DoesIntersectSelectedComponentEditor(const QRect& globalRect) const; @@ -445,6 +483,8 @@ namespace AzToolsFramework bool HandleSelectionEvents(QObject* object, QEvent* event); bool m_selectionEventAccepted; + bool HandleMenuEvent(QObject* object, QEvent* event); + // drag and drop events QRect GetInflatedRectFromPoint(const QPoint& point, int radius) const; bool GetComponentsAtDropEventPosition(QDropEvent* event, AZ::Entity::ComponentArrayType& targetComponents); @@ -458,8 +498,12 @@ namespace AzToolsFramework ComponentEditor* GetReorderDropTarget(const QRect& globalRect) const; bool ResetDrag(QMouseEvent* event); + bool FindAllowedRowWidgetReorderDropTarget(const QPoint& globalPos); + bool UpdateRowWidgetDrag(const QPoint& localPos, Qt::MouseButtons mouseButtons, const QMimeData* mimeData); + PropertyRowWidget* FindPropertyRowWidgetAt(QPoint globalPos); bool UpdateDrag(const QPoint& localPos, Qt::MouseButtons mouseButtons, const QMimeData* mimeData); bool StartDrag(QMouseEvent* event); + void EndRowWidgetReorder(); bool HandleDrop(QDropEvent* event); bool HandleDropForComponentTypes(QDropEvent* event); bool HandleDropForComponentAssets(QDropEvent* event); @@ -468,6 +512,8 @@ namespace AzToolsFramework bool CanDropForComponentTypes(const QMimeData* mimeData) const; bool CanDropForComponentAssets(const QMimeData* mimeData) const; bool CanDropForAssetBrowserEntries(const QMimeData* mimeData) const; + void SetRowWidgetHighlighted(PropertyRowWidget* rowWidget); + AZStd::vector ExtractComponentEditorIndicesFromMimeData(const QMimeData* mimeData) const; ComponentEditorVector GetComponentEditorsFromIndices(const AZStd::vector& indices) const; ComponentEditor* GetComponentEditorsFromIndex(const AZ::s32 index) const; @@ -559,6 +605,8 @@ namespace AzToolsFramework QIcon m_emptyIcon; QIcon m_clearIcon; + QIcon m_dragIcon; + QCursor m_dragCursor; QStandardItem* m_comboItems[StatusItems]; EntityIdSet m_overrideSelectedEntityIds; @@ -566,6 +614,19 @@ namespace AzToolsFramework Prefab::PrefabPublicInterface* m_prefabPublicInterface = nullptr; bool m_prefabsAreEnabled = false; + // Reordering row widgets within the RPE. + static constexpr float MoveFadeSeconds = 0.5f; + + ReorderState m_currentReorderState = ReorderState::Inactive; + ComponentEditor* m_reorderRowWidgetEditor = nullptr; + InstanceDataNode* m_nodeToMove = nullptr; + PropertyRowWidget* m_reorderRowWidget = nullptr; + PropertyRowWidget* m_reorderDropTarget = nullptr; + DropArea m_reorderDropArea = DropArea::Above; + QPixmap m_reorderRowImage; + float m_moveFadeSecondsRemaining; + AZStd::vector m_indexMapOfMovedRow; + // When m_initiatingPropertyChangeNotification is set to true, it means this EntityPropertyEditor is // broadcasting a change to all listeners about a property change for a given entity. This is needed // so that we don't update the values twice for this inspector @@ -573,6 +634,9 @@ namespace AzToolsFramework void ConnectToEntityBuses(const AZ::EntityId& entityId); void DisconnectFromEntityBuses(const AZ::EntityId& entityId); + void BeginMoveRowWidgetFade(); + void HighlightMovedRowWidget(); + //! Stores a component id to be focused on next time the UI updates. AZStd::optional m_newComponentId; @@ -594,6 +658,8 @@ namespace AzToolsFramework bool SelectedEntitiesAreFromSameSourceSliceEntity() const; + void DragStopped(); + AZ::Entity* GetSelectedEntityById(AZ::EntityId& entityId) const; }; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index 05c04872e3..c3da1e69b0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -368,10 +368,15 @@ namespace AzToolsFramework delete m_containerAddButton; } + this->unsetCursor(); + if ((m_parentRow) && (m_parentRow->IsContainerEditable())) { if (!m_elementRemoveButton) { + QIcon icon = QIcon(QStringLiteral(":/Cursors/Grab_release.svg")); + this->setCursor(QCursor(icon.pixmap(16), 5, 2)); + static QIcon s_iconRemove(QStringLiteral(":/stylesheet/img/UI20/delete-16.svg")); m_elementRemoveButton = new QToolButton(this); m_elementRemoveButton->setAutoRaise(true); @@ -570,7 +575,12 @@ namespace AzToolsFramework AZ_Assert(m_selectionEnabled, "Property is not selectable"); m_isSelected = selected; m_nameLabel->setProperty("selected", selected); - } + } + + bool PropertyRowWidget::GetSelected() + { + return m_isSelected; + } void PropertyRowWidget::SetSelectionEnabled(bool selectionEnabled) { @@ -1395,6 +1405,21 @@ namespace AzToolsFramework return !m_childrenRows.empty(); } + AZ::u32 PropertyRowWidget::GetChildRowCount() const + { + return static_cast(m_childrenRows.size()); + } + + PropertyRowWidget* PropertyRowWidget::GetChildRowByIndex(AZ::u32 index) const + { + if (index >= m_childrenRows.size()) + { + return nullptr; + } + + return m_childrenRows[index]; + } + bool PropertyRowWidget::ShouldPreValidatePropertyChange() const { return (m_changeValidators.size() > 0); @@ -1722,6 +1747,162 @@ namespace AzToolsFramework return m_parentRow->CanChildrenBeReordered(); } + + int PropertyRowWidget::GetIndexInParent() const + { + if (!GetParentRow()) + { + return -1; + } + + for (int index = 0; index < GetParentRow()->GetChildRowCount(); index++) + { + if (GetParentRow()->GetChildrenRows()[index] == this) + { + return index; + } + } + + return -1; + } + + bool PropertyRowWidget::CanMoveUp() const + { + if (!CanBeReordered()) + { + return false; + } + + return this != m_parentRow->GetChildRowByIndex(0); + } + + bool PropertyRowWidget::CanMoveDown() const + { + if (!CanBeReordered()) + { + return false; + } + + AZ::u32 numChildrenOfParent = m_parentRow->GetChildRowCount(); + + return this != m_parentRow->GetChildRowByIndex(numChildrenOfParent - 1); + } + + int PropertyRowWidget::GetContainingEditorFrameWidth() + { + QWidget* parent = parentWidget(); + + // Find the first ancestor that can be cast to a QFrame, this will be the RPE. + while (!qobject_cast(parent)) + { + parent = parent->parentWidget(); + } + + if (!parent) + { + return 0; + } + + // The parent of the RPE is the size we want. + parent = parent->parentWidget(); + + return parent->rect().width(); + } + + int PropertyRowWidget::GetHeightOfRowAndVisibleChildren() + { + int height = rect().height(); + + if (!GetChildRowCount() || !IsExpanded()) + { + return height; + } + + for (auto childRow : GetChildrenRows()) + { + height += childRow->GetHeightOfRowAndVisibleChildren(); + } + + return height; + } + + int PropertyRowWidget::DrawDragImageAndVisibleChildrenInto(QPainter& painter, int xpos, int ypos) + { + // Render our image into the given painter. + int ystart = ypos; + + render(&painter, QPoint(xpos, ypos)); + + if (!GetChildRowCount() || !IsExpanded()) + { + return rect().height(); + } + + ypos += rect().height(); + + // Recursively draw any children. + for (auto childRow : GetChildrenRows()) + { + ypos += childRow->DrawDragImageAndVisibleChildrenInto(painter, xpos, ypos); + } + + return ypos - ystart; + } + + QPixmap PropertyRowWidget::createDragImage( + const QColor backgroundColor, const QColor borderColor, const float alpha, DragImageType imageType) + { + // Make the drag box as wide as the containing editor minus a gap each side for the border. + static constexpr int ParentEditorBorderSize = 2; + int width = GetContainingEditorFrameWidth() - ParentEditorBorderSize * 2; + int height = 0; + + if (imageType == DragImageType::IncludeVisibleChildren) + { + height = GetHeightOfRowAndVisibleChildren(); + } + else + { + height = rect().height(); + } + + const auto dpr = devicePixelRatioF(); + QPixmap dragImage(width * dpr, height * dpr); + dragImage.setDevicePixelRatio(dpr); + dragImage.fill(Qt::transparent); + + QRect imageRect = QRect(0, 0, width, height); + + QPainter dragPainter(&dragImage); + dragPainter.setCompositionMode(QPainter::CompositionMode_Source); + dragPainter.fillRect(imageRect, Qt::transparent); + dragPainter.setCompositionMode(QPainter::CompositionMode_SourceOver); + dragPainter.setOpacity(alpha); + dragPainter.fillRect(imageRect, backgroundColor); + + dragPainter.setOpacity(1.0f); + + int marginWidth = (imageRect.width() - rect().width()) / 2 + ParentEditorBorderSize - 1; + + if (imageType == DragImageType::IncludeVisibleChildren) + { + DrawDragImageAndVisibleChildrenInto(dragPainter, marginWidth, 0); + } + else + { + render(&dragPainter, QPoint(marginWidth, 0)); + } + + QPen pen; + pen.setColor(QColor(borderColor)); + pen.setWidth(1); + dragPainter.setPen(pen); + dragPainter.drawRect(0, 0, imageRect.width() - 1, imageRect.height() - 1); + + dragPainter.end(); + + return dragImage; + } } #include "UI/PropertyEditor/moc_PropertyRowWidget.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index ebf7c67b21..68cc9b9cf9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -45,6 +45,13 @@ namespace AzToolsFramework Q_PROPERTY(bool appendDefaultLabelToName READ GetAppendDefaultLabelToName WRITE AppendDefaultLabelToName) public: AZ_CLASS_ALLOCATOR(PropertyRowWidget, AZ::SystemAllocator, 0) + + enum class DragImageType + { + SingleRow, + IncludeVisibleChildren + }; + PropertyRowWidget(QWidget* pParent); virtual ~PropertyRowWidget(); @@ -86,6 +93,9 @@ namespace AzToolsFramework bool GetAppendDefaultLabelToName(); void AppendDefaultLabelToName(bool doAppend); + AZ::u32 GetChildRowCount() const; + PropertyRowWidget* GetChildRowByIndex(AZ::u32 index) const; + AZStd::vector& GetChildrenRows() { return m_childrenRows; } bool HasChildRows() const; @@ -124,6 +134,7 @@ namespace AzToolsFramework void SetSelectionEnabled(bool selectionEnabled); void SetSelected(bool selected); + bool GetSelected(); bool eventFilter(QObject *watched, QEvent *event) override; void paintEvent(QPaintEvent*) override; @@ -152,9 +163,18 @@ namespace AzToolsFramework bool CanChildrenBeReordered() const; bool CanBeReordered() const; + int GetIndexInParent() const; + bool CanMoveUp() const; + bool CanMoveDown() const; + + int GetContainingEditorFrameWidth(); + QPixmap createDragImage(const QColor backgroundColor, const QColor borderColor, const float alpha, DragImageType imageType); protected: int CalculateLabelWidth() const; + int GetHeightOfRowAndVisibleChildren(); + int DrawDragImageAndVisibleChildrenInto(QPainter& painter, int xpos, int ypos); + bool IsHidden(InstanceDataNode* node) const; struct ChangeNotification; @@ -216,6 +236,7 @@ namespace AzToolsFramework bool m_isMultiSizeContainer = false; bool m_isFixedSizeOrSmartPtrContainer = false; bool m_custom = false; + bool m_canChildrenBeReordered = false; bool m_isSelected = false; bool m_selectionEnabled = false; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp index 36462bca66..5d5b00e83d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp @@ -19,6 +19,7 @@ #include #include #include +#include AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 'QTextFormat::d': class 'QSharedDataPointer' needs to have dll-interface to be used by clients of class 'QTextFormat' #include AZ_POP_DISABLE_WARNING @@ -1343,7 +1344,7 @@ namespace AzToolsFramework // calculate the index/offset of the instance data node in the container // (useful for notifying which element in a vector was modified/removed) - static size_t CalculateElementIndexInContainer( + static int CalculateElementIndexInContainer( InstanceDataNode* node, void* parentInstanceNode, AZ::SerializeContext::IDataContainer* container, AZStd::vector& nodeInstancesOut) { @@ -1358,7 +1359,7 @@ namespace AzToolsFramework } } - size_t elementIndex = 0; + int elementIndex = 0; void* elementPtr = nodeInstancesOut.empty() ? nullptr : nodeInstancesOut.front(); // find the index of the element we are about to remove @@ -1429,7 +1430,7 @@ namespace AzToolsFramework // if the element being modified exists in a container, calculate // the index to be passed through to PropertyNotify - const auto calculateElementIndex = [](InstanceDataNode* node) -> size_t { + const auto calculateElementIndex = [](InstanceDataNode* node) -> int { if (InstanceDataNode* parent = node->GetParent()) { if (AZ::SerializeContext::IDataContainer* container = parent->GetClassMetadata()->m_container) @@ -1656,6 +1657,221 @@ namespace AzToolsFramework AzToolsFramework::Refresh_EntireTree); } + InstanceDataNode* ReflectedPropertyEditor::FindContainerNodeForNode(InstanceDataNode* node) const + { + // Locate the owning container. There may be a level of indirection due to wrappers, such as DynamicSerializableField. + InstanceDataNode* pContainerNode = node->GetParent(); + if (!pContainerNode) + { + return nullptr; + } + + while (pContainerNode && !pContainerNode->GetClassMetadata()->m_container) + { + pContainerNode = pContainerNode->GetParent(); + node = node->GetParent(); + } + + // Check for pContainerNode again, can happen if a node is deleted during operation. + if (!pContainerNode) + { + return nullptr; + } + + if (IsParentAssociativeContainer(pContainerNode) && IsPairContainer(pContainerNode)) + { + // Go up one more level to the associative container, we'll remove the pair from that container + pContainerNode = pContainerNode->GetParent(); + node = node->GetParent(); + } + + AZ_Assert( + pContainerNode, "Failed to locate parent container for element \"%s\" of type %s.", + node->GetElementMetadata() ? node->GetElementMetadata()->m_name : node->GetClassMetadata()->m_name, + node->GetClassMetadata()->m_typeId.ToString().c_str()); + + return pContainerNode; + } + + InstanceDataNode* ReflectedPropertyEditor::GetNodeAtIndex(int index) + { + if (index >= m_impl->m_widgetsInDisplayOrder.size()) + { + return nullptr; + } + + return GetNodeFromWidget(m_impl->m_widgetsInDisplayOrder[index]); + } + + QSet ReflectedPropertyEditor::GetTopLevelWidgets() + { + return m_impl->getTopLevelWidgets(); + } + + void ReflectedPropertyEditor::ChangeNodeIndex(InstanceDataNode* containerNode, InstanceDataNode* node, int fromIndex, int toIndex) + { + auto container = containerNode->GetElementMetadata() + ? containerNode->GetElementMetadata()->m_genericClassInfo->GetClassData()->m_container + : nullptr; + + if (fromIndex == toIndex) + { + return; + } + + if (!container || container->GetAssociativeContainerInterface()) + { + return; + } + + AZ::Uuid typeId = node->GetClassMetadata()->m_typeId; + + if (m_impl->m_ptrNotify) + { + m_impl->m_ptrNotify->BeforePropertyModified(containerNode); + } + + const AZ::SerializeContext::ClassElement* containerClassElement = container->GetElement(container->GetDefaultElementNameCrc()); + + AZ::SerializeContext* serializeContext = nullptr; + AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); + + // Backup the item we're moving. + void* srcElement = nullptr; + void* destElement = nullptr; + + int destIndex = -1; + int srcIndex = fromIndex; + + srcElement = container->GetElementByIndex(containerNode->GetInstance(0), containerClassElement, srcIndex); + + void* tmpBuffer = serializeContext->CloneObject(srcElement, typeId); + + // Shuffle all intervening items up (or down). + int indexOffset = (toIndex < fromIndex) ? -1 : 1; + + while (destIndex != toIndex - indexOffset) + { + destIndex = srcIndex; + srcIndex += indexOffset; + + destElement = srcElement; + + srcElement = container->GetElementByIndex(containerNode->GetInstance(0), containerClassElement, srcIndex); + + serializeContext->CloneObjectInplace(destElement, srcElement, typeId); + } + + // Now replace the final element with the one backed up previously. + destElement = srcElement; + + serializeContext->CloneObjectInplace(destElement, tmpBuffer, typeId); + + if (m_impl->m_ptrNotify) + { + m_impl->m_ptrNotify->AfterPropertyModified(containerNode); + m_impl->m_ptrNotify->SealUndoStack(); + } + + // Need to refresh any pinned inspectors as well to keep the container state in sync + QueueInvalidation(Refresh_Values); + AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_Values); + } + + void ReflectedPropertyEditor::MoveNodeToIndex(InstanceDataNode* node, int index) + { + InstanceDataNode* pContainerNode = FindContainerNodeForNode(node); + + if (!pContainerNode) + { + return; + } + + AZ::SerializeContext::IDataContainer* container = pContainerNode->GetClassMetadata()->m_container; + + AZStd::vector nodeInstancesOut; + const int elementIndex = CalculateElementIndexInContainer(node, pContainerNode->GetInstance(0), container, nodeInstancesOut); + + ChangeNodeIndex(pContainerNode, node, elementIndex, index); + } + + void ReflectedPropertyEditor::MoveNodeBefore(InstanceDataNode* nodeToMove, InstanceDataNode* nodeToMoveBefore) + { + InstanceDataNode* pContainerNode = FindContainerNodeForNode(nodeToMove); + InstanceDataNode* pContainerNodeTarget = FindContainerNodeForNode(nodeToMoveBefore); + + if (nodeToMove == nodeToMoveBefore) + { + return; + } + + // Can only move nodes within the same parent. + if (pContainerNode != pContainerNodeTarget) + { + return; + } + + AZ::SerializeContext::IDataContainer* container = pContainerNode->GetClassMetadata()->m_container; + + AZStd::vector nodeInstancesOut; + int elementIndex = CalculateElementIndexInContainer(nodeToMove, pContainerNode->GetInstance(0), container, nodeInstancesOut); + nodeInstancesOut.clear(); + int elementIndexTarget = + CalculateElementIndexInContainer(nodeToMoveBefore, pContainerNode->GetInstance(0), container, nodeInstancesOut); + + if (elementIndex < elementIndexTarget) + { + elementIndexTarget -= 1; + } + + ChangeNodeIndex(pContainerNode, nodeToMove, elementIndex, elementIndexTarget); + } + + void ReflectedPropertyEditor::MoveNodeAfter(InstanceDataNode* nodeToMove, InstanceDataNode* nodeToMoveBefore) + { + InstanceDataNode* pContainerNode = FindContainerNodeForNode(nodeToMove); + InstanceDataNode* pContainerNodeTarget = FindContainerNodeForNode(nodeToMoveBefore); + + if (nodeToMove == nodeToMoveBefore) + { + return; + } + + // Can only move nodes within the same parent. + if (pContainerNode != pContainerNodeTarget) + { + return; + } + + AZ::SerializeContext::IDataContainer* container = pContainerNode->GetClassMetadata()->m_container; + + AZStd::vector nodeInstancesOut; + int elementIndex = CalculateElementIndexInContainer(nodeToMove, pContainerNode->GetInstance(0), container, nodeInstancesOut); + nodeInstancesOut.clear(); + int elementIndexTarget = + CalculateElementIndexInContainer(nodeToMoveBefore, pContainerNode->GetInstance(0), container, nodeInstancesOut); + + if (elementIndex > elementIndexTarget) + { + elementIndexTarget += 1; + } + + ChangeNodeIndex(pContainerNode, nodeToMove, elementIndex, elementIndexTarget); + } + + int ReflectedPropertyEditor::GetNodeIndexInContainer(InstanceDataNode* node) + { + InstanceDataNode* pContainerNode = FindContainerNodeForNode(node); + + AZ::SerializeContext::IDataContainer* container = pContainerNode->GetClassMetadata()->m_container; + + AZStd::vector nodeInstancesOut; + int elementIndex = CalculateElementIndexInContainer(node, pContainerNode->GetInstance(0), container, nodeInstancesOut); + + return elementIndex; + } + void ReflectedPropertyEditor::OnPropertyRowRequestContainerRemoveItem(PropertyRowWidget* widget, InstanceDataNode* node) { // Locate the owning container. There may be a level of indirection due to wrappers, such as DynamicSerializableField. @@ -1690,7 +1906,7 @@ namespace AzToolsFramework // the index of the element being removed AZStd::vector nodeInstancesOut; - const size_t elementIndex = CalculateElementIndexInContainer( + const int elementIndex = CalculateElementIndexInContainer( node, pContainerNode->GetInstance(0), container, nodeInstancesOut); // pass the context as the last parameter to actually delete the related data. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx index b10e153162..28da540098 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx @@ -155,9 +155,19 @@ namespace AzToolsFramework using VisibilityCallback = AZStd::function; void SetVisibilityCallback(VisibilityCallback callback); + void MoveNodeToIndex(InstanceDataNode* node, int index); + void MoveNodeBefore(InstanceDataNode* nodeToMove, InstanceDataNode* nodeToMoveBefore); + void MoveNodeAfter(InstanceDataNode* nodeToMove, InstanceDataNode* nodeToMoveBefore); + + int GetNodeIndexInContainer(InstanceDataNode* node); + InstanceDataNode* GetNodeAtIndex(int index); + QSet GetTopLevelWidgets(); signals: void OnExpansionContractionDone(); private: + InstanceDataNode* FindContainerNodeForNode(InstanceDataNode* node) const; + void ChangeNodeIndex(InstanceDataNode* containerNode, InstanceDataNode* node, int oldIndex, int newIndex); + class Impl; std::unique_ptr m_impl; From f7e536bfb1868203c53e20c2895718da45f4784e Mon Sep 17 00:00:00 2001 From: sphrose <82213493+sphrose@users.noreply.github.com> Date: Mon, 16 Aug 2021 12:37:12 +0100 Subject: [PATCH 196/205] compile fix - signed/unsigned mismatch (#3139) Signed-off-by: sphrose <82213493+sphrose@users.noreply.github.com> --- .../AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index c3da1e69b0..604c6141d7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -1755,7 +1755,7 @@ namespace AzToolsFramework return -1; } - for (int index = 0; index < GetParentRow()->GetChildRowCount(); index++) + for (AZ::u32 index = 0; index < GetParentRow()->GetChildRowCount(); index++) { if (GetParentRow()->GetChildrenRows()[index] == this) { From 5925bd22f6e0607f9fda0a705c6b3738c81bda24 Mon Sep 17 00:00:00 2001 From: jonawals Date: Mon, 16 Aug 2021 14:15:02 +0100 Subject: [PATCH 197/205] Further subdivide TIAF data by suite. (#3128) * Further subdivide TIAF data by suite. * Key fix typo. Signed-off-by: John --- .../TestImpactRuntimeConfigurationFactory.cpp | 25 ++++--------- .../TestImpactClientSequenceReport.h | 2 +- .../TestImpactConfiguration.h | 4 +-- .../Runtime/Code/Source/TestImpactRuntime.cpp | 5 +-- .../ConsoleFrontendConfig.in | 11 ++---- scripts/build/TestImpactAnalysis/tiaf.py | 3 +- .../tiaf_persistent_storage.py | 35 +++++++++++-------- .../tiaf_persistent_storage_local.py | 2 ++ .../tiaf_persistent_storage_s3.py | 6 ++-- 9 files changed, 42 insertions(+), 51 deletions(-) diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactRuntimeConfigurationFactory.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactRuntimeConfigurationFactory.cpp index 8ea32d6447..c2bc95a906 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactRuntimeConfigurationFactory.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactRuntimeConfigurationFactory.cpp @@ -27,7 +27,7 @@ namespace TestImpact "relative_paths", "artifact_dir", "enumeration_cache_dir", - "test_impact_data_files", + "test_impact_data_file", "temp", "active", "target_sources", @@ -72,7 +72,7 @@ namespace TestImpact RelativePaths, ArtifactDir, EnumerationCacheDir, - TestImpactDataFiles, + TestImpactDataFile, TempWorkspace, ActiveWorkspace, TargetSources, @@ -138,31 +138,18 @@ namespace TestImpact tempWorkspaceConfig.m_artifactDirectory = GetAbsPathFromRelPath( tempWorkspaceConfig.m_root, tempWorkspace[Config::Keys[Config::RelativePaths]][Config::Keys[Config::ArtifactDir]].GetString()); + tempWorkspaceConfig.m_enumerationCacheDirectory = GetAbsPathFromRelPath( + tempWorkspaceConfig.m_root, + tempWorkspace[Config::Keys[Config::RelativePaths]][Config::Keys[Config::EnumerationCacheDir]].GetString()); return tempWorkspaceConfig; } - AZStd::array ParseTestImpactAnalysisDataFiles(const RepoPath& root, const rapidjson::Value& sparTiaFile) - { - AZStd::array sparTiaFiles; - sparTiaFiles[static_cast(SuiteType::Main)] = - GetAbsPathFromRelPath(root, sparTiaFile[SuiteTypeAsString(SuiteType::Main).c_str()].GetString()); - sparTiaFiles[static_cast(SuiteType::Periodic)] = - GetAbsPathFromRelPath(root, sparTiaFile[SuiteTypeAsString(SuiteType::Periodic).c_str()].GetString()); - sparTiaFiles[static_cast(SuiteType::Sandbox)] = - GetAbsPathFromRelPath(root, sparTiaFile[SuiteTypeAsString(SuiteType::Sandbox).c_str()].GetString()); - - return sparTiaFiles; - } - WorkspaceConfig::Active ParseActiveWorkspaceConfig(const rapidjson::Value& activeWorkspace) { WorkspaceConfig::Active activeWorkspaceConfig; const auto& relativePaths = activeWorkspace[Config::Keys[Config::RelativePaths]]; activeWorkspaceConfig.m_root = activeWorkspace[Config::Keys[Config::Root]].GetString(); - activeWorkspaceConfig.m_enumerationCacheDirectory - = GetAbsPathFromRelPath(activeWorkspaceConfig.m_root, relativePaths[Config::Keys[Config::EnumerationCacheDir]].GetString()); - activeWorkspaceConfig.m_sparTiaFiles = - ParseTestImpactAnalysisDataFiles(activeWorkspaceConfig.m_root, relativePaths[Config::Keys[Config::TestImpactDataFiles]]); + activeWorkspaceConfig.m_sparTiaFile = relativePaths[Config::Keys[Config::TestImpactDataFile]].GetString(); return activeWorkspaceConfig; } diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h index e86123ddc7..1ddd1042e6 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h @@ -530,7 +530,7 @@ namespace TestImpact size_t GetTotalNumTimedOutTestRuns() const override; size_t GetTotalNumUnexecutedTestRuns() const override; - //! Returns the report for the discarded test runs. + // ImpactAnalysisSequenceReport overrides ... const TestRunSelection GetDiscardedTestRuns() const; //! Returns the report for the discarded test runs. diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactConfiguration.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactConfiguration.h index fcacd90e71..92dd454b01 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactConfiguration.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactConfiguration.h @@ -37,14 +37,14 @@ namespace TestImpact { RepoPath m_root; //!< Path to the temporary workspace (cleaned prior to use). RepoPath m_artifactDirectory; //!< Path to read and write runtime artifacts to and from. + RepoPath m_enumerationCacheDirectory; //!< Path to the test enumerations cache. }; //! Active persistent data workspace configuration. struct Active { RepoPath m_root; //!< Path to the persistent workspace tracked by the repository. - RepoPath m_enumerationCacheDirectory; //!< Path to the test enumerations cache. - AZStd::array m_sparTiaFiles; //!< Paths to the test impact analysis data files for each test suite. + RepoPath m_sparTiaFile; //!< Paths to the test impact analysis data file. }; Temp m_temp; diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp index 8a9d96bca8..515118dd7a 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp @@ -275,7 +275,7 @@ namespace TestImpact m_testEngine = AZStd::make_unique( m_config.m_repo.m_root, m_config.m_target.m_outputDirectory, - m_config.m_workspace.m_active.m_enumerationCacheDirectory, + m_config.m_workspace.m_temp.m_enumerationCacheDirectory, m_config.m_workspace.m_temp.m_artifactDirectory, m_config.m_testEngine.m_testRunner.m_binary, m_config.m_testEngine.m_instrumentation.m_binary, @@ -289,7 +289,8 @@ namespace TestImpact } else { - m_sparTiaFile = m_config.m_workspace.m_active.m_sparTiaFiles[static_cast(m_suiteFilter)].String(); + m_sparTiaFile = + m_config.m_workspace.m_active.m_root / RepoPath(SuiteTypeAsString(m_suiteFilter)) / m_config.m_workspace.m_active.m_sparTiaFile; } // Populate the dynamic dependency map with the existing source coverage data (if any) diff --git a/cmake/TestImpactFramework/ConsoleFrontendConfig.in b/cmake/TestImpactFramework/ConsoleFrontendConfig.in index 17fbd217d7..3b6318e1e0 100644 --- a/cmake/TestImpactFramework/ConsoleFrontendConfig.in +++ b/cmake/TestImpactFramework/ConsoleFrontendConfig.in @@ -15,19 +15,14 @@ "temp": { "root": "${temp_dir}", "relative_paths": { - "artifact_dir": "RuntimeArtifact" + "artifact_dir": "RuntimeArtifact", + "enumeration_cache_dir": "EnumerationCache" } }, "active": { "root": "${active_dir}", "relative_paths": { - "test_impact_data_files": { - "main": "TestImpactData.main.spartia", - "periodic": "TestImpactData.periodic.spartia", - "sandbox": "TestImpactData.sandbox.spartia" - }, - "enumeration_cache_dir": "EnumerationCache", - "last_build_target_list_file": "LastRunBuildTargets.json" + "test_impact_data_file": "TestImpactData.spartia" } }, "historic": { diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index e8faef30e3..27fbaf451f 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -230,7 +230,7 @@ class TestImpact: # Flag for corner case where: # 1. TIAF was already run previously for this commit. - # 2. There was no last commit hash when TIAF last ran on this commit (due to no coverage data existing get for this branch) + # 2. There was no last commit hash when TIAF last ran on this commit (due to no coverage data existing yet for this branch) # 3. TIAF has not been run on any other commits between the run for this commit and the last run for this commit. # The above results in TIAF being stuck in a state of generating an empty change list (and thus doing no work until another # commit comes in) which is problematic if the commit needs to be re-run for whatever reason so in these conditions we revert @@ -323,7 +323,6 @@ class TestImpact: logger.info(f"Args: {unpacked_args}") runtime_result = subprocess.run([str(self._tiaf_bin)] + args) report = None - # If the sequence completed (with or without failures) we will update the historical meta-data if runtime_result.returncode == 0 or runtime_result.returncode == 7: logger.info("Test impact analysis runtime returned successfully.") diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py index 3fff05b549..5445c1f955 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py @@ -17,11 +17,11 @@ logger = get_logger(__file__) class PersistentStorage(ABC): WORKSPACE_KEY = "workspace" - LAST_RUNS_KEY = "last_runs" + HISTORIC_SEQUENCES_KEY = "historic_sequences" ACTIVE_KEY = "active" ROOT_KEY = "root" RELATIVE_PATHS_KEY = "relative_paths" - TEST_IMPACT_DATA_FILES_KEY = "test_impact_data_files" + TEST_IMPACT_DATA_FILE_KEY = "test_impact_data_file" LAST_COMMIT_HASH_KEY = "last_commit_hash" COVERAGE_DATA_KEY = "coverage_data" @@ -35,19 +35,21 @@ class PersistentStorage(ABC): """ # Work on the assumption that there is no historic meta-data (a valid state to be in, should none exist) + self._suite = suite self._last_commit_hash = None self._has_historic_data = False self._has_previous_last_commit_hash = False self._this_commit_hash = commit self._this_commit_hash_last_commit_hash = None self._historic_data = None - logger.info(f"Attempting to access persistent storage for the commit {self._this_commit_hash}") + logger.info(f"Attempting to access persistent storage for the commit '{self._this_commit_hash}' for suite '{self._suite}'") try: # The runtime expects the coverage data to be in the location specified in the config file (unless overridden with # the --datafile command line argument, which the TIAF scripts do not do) self._active_workspace = pathlib.Path(config[self.WORKSPACE_KEY][self.ACTIVE_KEY][self.ROOT_KEY]) - unpacked_coverage_data_file = config[self.WORKSPACE_KEY][self.ACTIVE_KEY][self.RELATIVE_PATHS_KEY][self.TEST_IMPACT_DATA_FILES_KEY][suite] + self._active_workspace = self._active_workspace.joinpath(pathlib.Path(self._suite)) + unpacked_coverage_data_file = config[self.WORKSPACE_KEY][self.ACTIVE_KEY][self.RELATIVE_PATHS_KEY][self.TEST_IMPACT_DATA_FILE_KEY] except KeyError as e: raise SystemError(f"The config does not contain the key {str(e)}.") @@ -70,25 +72,27 @@ class PersistentStorage(ABC): self._last_commit_hash = self._historic_data[self.LAST_COMMIT_HASH_KEY] logger.info(f"Last commit hash '{self._last_commit_hash}' found.") - if self.LAST_RUNS_KEY in self._historic_data: - # Last commit hash for the sequence that was run for this commit previously (if any) - if self._this_commit_hash in self._historic_data[self.LAST_RUNS_KEY]: + # Last commit hash for the sequence that was run for this commit previously (if any) + if self.HISTORIC_SEQUENCES_KEY in self._historic_data: + if self._this_commit_hash in self._historic_data[self.HISTORIC_SEQUENCES_KEY]: # 'None' is a valid value for the previously used last commit hash if there was no coverage data at that time - self._this_commit_hash_last_commit_hash = self._historic_data[self.LAST_RUNS_KEY][self._this_commit_hash] + self._this_commit_hash_last_commit_hash = self._historic_data[self.HISTORIC_SEQUENCES_KEY][self._this_commit_hash] self._has_previous_last_commit_hash = self._this_commit_hash_last_commit_hash is not None if self._has_previous_last_commit_hash: logger.info(f"Last commit hash '{self._this_commit_hash_last_commit_hash}' was used previously for this commit.") else: - logger.info(f"Prior sequence data found for this commit but it is empty (there was no coverage data vailable at that time).") + logger.info(f"Prior sequence data found for this commit but it is empty (there was no coverage data available at that time).") else: logger.info(f"No prior sequence data found for commit '{self._this_commit_hash}', this is the first sequence for this commit.") else: logger.info(f"No prior sequence data found for any commits.") - # Create the active workspace directory where the coverage data file will be placed and unpack the coverage data so - # it is accessible by the runtime + # Create the active workspace directory for the unpacked historic data files so they are accessible by the runtime self._active_workspace.mkdir(exist_ok=True) + + # Coverage file + logger.info(f"Writing coverage data to '{self._unpacked_coverage_data_file}'.") with open(self._unpacked_coverage_data_file, "w", newline='\n') as coverage_data: coverage_data.write(self._historic_data[self.COVERAGE_DATA_KEY]) @@ -117,9 +121,12 @@ class PersistentStorage(ABC): self._historic_data[self.LAST_COMMIT_HASH_KEY] = self._this_commit_hash # Last commit hash for this commit - if not self.LAST_RUNS_KEY in self._historic_data: - self._historic_data[self.LAST_RUNS_KEY] = {} - self._historic_data[self.LAST_RUNS_KEY][self._this_commit_hash] = self._last_commit_hash + if not self.HISTORIC_SEQUENCES_KEY in self._historic_data: + self._historic_data[self.HISTORIC_SEQUENCES_KEY] = {} + self._historic_data[self.HISTORIC_SEQUENCES_KEY][self._this_commit_hash] = self._last_commit_hash + + # Test runs for this completed sequence + self._historic_data[self.PREVIOUS_TEST_RUNS_KEY] = test_runs # Coverage data for this branch with open(self._unpacked_coverage_data_file, "r") as coverage_data: diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py index c72fafc580..7ad9155a41 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py @@ -32,10 +32,12 @@ class PersistentStorageLocal(PersistentStorage): try: # Attempt to obtain the local persistent data location specified in the runtime config file self._historic_workspace = pathlib.Path(config[self.WORKSPACE_KEY][self.HISTORIC_KEY][self.ROOT_KEY]) + self._historic_workspace = self._historic_workspace.joinpath(pathlib.Path(self._suite)) historic_data_file = pathlib.Path(config[self.WORKSPACE_KEY][self.HISTORIC_KEY][self.RELATIVE_PATHS_KEY][self.DATA_KEY]) # Attempt to unpack the local historic data file self._historic_data_file = self._historic_workspace.joinpath(historic_data_file) + logger.info(f"Attempting to retrieve historic data at location '{self._historic_data_file}'...") if self._historic_data_file.is_file(): with open(self._historic_data_file, "r") as historic_data_raw: historic_data_json = historic_data_raw.read() diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py index 074caf73a1..175eb3148d 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py @@ -43,9 +43,9 @@ class PersistentStorageS3(PersistentStorage): # historic_data.json.zip is the file containing the coverage and meta-data of the last TIAF sequence run historic_data_file = f"historic_data.{object_extension}" - # The location of the data is in the form // so the build config of each branch gets its own historic data - self._historic_data_dir = f'{root_dir}/{branch}/{config[self.META_KEY][self.BUILD_CONFIG_KEY]}' - self._historic_data_key = f'{self._historic_data_dir}/{historic_data_file}' + # The location of the data is in the form /// so the build config of each branch gets its own historic data + self._historic_data_dir = f"{root_dir}/{branch}/{config[self.META_KEY][self.BUILD_CONFIG_KEY]}/{self._suite}" + self._historic_data_key = f"{self._historic_data_dir}/{historic_data_file}" logger.info(f"Attempting to retrieve historic data for branch '{branch}' at location '{self._historic_data_key}' on bucket '{s3_bucket}'...") self._s3 = boto3.resource("s3") From e630e3324dc5836fcfea328d9e002fa0877f060b Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Mon, 16 Aug 2021 15:46:46 +0100 Subject: [PATCH 198/205] fixed joint crash when no lead entity is selected (#2867) Signed-off-by: amzn-sean <75276488+amzn-sean@users.noreply.github.com> --- Gems/PhysX/Code/Source/BallJointComponent.cpp | 19 +++++- .../PhysX/Code/Source/FixedJointComponent.cpp | 18 ++++- .../PhysX/Code/Source/HingeJointComponent.cpp | 18 ++++- .../Code/Source/Joint/PhysXJointUtils.cpp | 15 +++-- Gems/PhysX/Code/Tests/PhysXJointsTest.cpp | 66 +++++++++++++++++-- 5 files changed, 121 insertions(+), 15 deletions(-) diff --git a/Gems/PhysX/Code/Source/BallJointComponent.cpp b/Gems/PhysX/Code/Source/BallJointComponent.cpp index 12323e5077..60f7888b0d 100644 --- a/Gems/PhysX/Code/Source/BallJointComponent.cpp +++ b/Gems/PhysX/Code/Source/BallJointComponent.cpp @@ -46,11 +46,26 @@ namespace PhysX JointComponent::LeadFollowerInfo leadFollowerInfo; ObtainLeadFollowerInfo(leadFollowerInfo); - if (!leadFollowerInfo.m_followerActor) + if (leadFollowerInfo.m_followerActor == nullptr || + leadFollowerInfo.m_followerBody == nullptr) { return; } + // if there is no lead body, this will be a constraint of the follower's global position, so use invalid body handle. + AzPhysics::SimulatedBodyHandle parentHandle = AzPhysics::InvalidSimulatedBodyHandle; + if (leadFollowerInfo.m_leadBody != nullptr) + { + parentHandle = leadFollowerInfo.m_leadBody->m_bodyHandle; + } + else + { + AZ_TracePrintf( + "PhysX", "Entity [%s] Ball Joint component missing lead entity. This joint will be a global constraint on the follower's global position.", + GetEntity()->GetName().c_str()); + } + + BallJointConfiguration configuration; configuration.m_parentLocalPosition = leadFollowerInfo.m_leadLocal.GetTranslation(); configuration.m_parentLocalRotation = leadFollowerInfo.m_leadLocal.GetRotation(); @@ -65,7 +80,7 @@ namespace PhysX m_jointHandle = sceneInterface->AddJoint( leadFollowerInfo.m_followerBody->m_sceneOwner, &configuration, - leadFollowerInfo.m_leadBody->m_bodyHandle, + parentHandle, leadFollowerInfo.m_followerBody->m_bodyHandle); m_jointSceneOwner = leadFollowerInfo.m_followerBody->m_sceneOwner; } diff --git a/Gems/PhysX/Code/Source/FixedJointComponent.cpp b/Gems/PhysX/Code/Source/FixedJointComponent.cpp index 53a9946998..82c8cc485c 100644 --- a/Gems/PhysX/Code/Source/FixedJointComponent.cpp +++ b/Gems/PhysX/Code/Source/FixedJointComponent.cpp @@ -54,11 +54,25 @@ namespace PhysX JointComponent::LeadFollowerInfo leadFollowerInfo; ObtainLeadFollowerInfo(leadFollowerInfo); - if (!leadFollowerInfo.m_followerActor) + if (leadFollowerInfo.m_followerActor == nullptr || + leadFollowerInfo.m_followerBody == nullptr) { return; } + // if there is no lead body, this will be a constraint of the follower's global position, so use invalid body handle. + AzPhysics::SimulatedBodyHandle parentHandle = AzPhysics::InvalidSimulatedBodyHandle; + if (leadFollowerInfo.m_leadBody != nullptr) + { + parentHandle = leadFollowerInfo.m_leadBody->m_bodyHandle; + } + else + { + AZ_TracePrintf("PhysX", + "Entity [%s] Fixed Joint component missing lead entity. This joint will be a global constraint on the follower's global position.", + GetEntity()->GetName().c_str()); + } + FixedJointConfiguration configuration; configuration.m_parentLocalPosition = leadFollowerInfo.m_leadLocal.GetTranslation(); configuration.m_parentLocalRotation = leadFollowerInfo.m_leadLocal.GetRotation(); @@ -72,7 +86,7 @@ namespace PhysX m_jointHandle = sceneInterface->AddJoint( leadFollowerInfo.m_followerBody->m_sceneOwner, &configuration, - leadFollowerInfo.m_leadBody->m_bodyHandle, + parentHandle, leadFollowerInfo.m_followerBody->m_bodyHandle); m_jointSceneOwner = leadFollowerInfo.m_followerBody->m_sceneOwner; } diff --git a/Gems/PhysX/Code/Source/HingeJointComponent.cpp b/Gems/PhysX/Code/Source/HingeJointComponent.cpp index f275d32dc7..5edf1803c4 100644 --- a/Gems/PhysX/Code/Source/HingeJointComponent.cpp +++ b/Gems/PhysX/Code/Source/HingeJointComponent.cpp @@ -48,12 +48,24 @@ namespace PhysX JointComponent::LeadFollowerInfo leadFollowerInfo; ObtainLeadFollowerInfo(leadFollowerInfo); if (leadFollowerInfo.m_followerActor == nullptr || - leadFollowerInfo.m_leadBody == nullptr || leadFollowerInfo.m_followerBody == nullptr) { return; } + // if there is no lead body, this will be a constraint of the follower's global position, so use invalid body handle. + AzPhysics::SimulatedBodyHandle parentHandle = AzPhysics::InvalidSimulatedBodyHandle; + if (leadFollowerInfo.m_leadBody != nullptr) + { + parentHandle = leadFollowerInfo.m_leadBody->m_bodyHandle; + } + else + { + AZ_TracePrintf( + "PhysX", "Entity [%s] Hinge Joint component missing lead entity. This joint will be a global constraint on the follower's global position.", + GetEntity()->GetName().c_str()); + } + HingeJointConfiguration configuration; configuration.m_parentLocalPosition = leadFollowerInfo.m_leadLocal.GetTranslation(); configuration.m_parentLocalRotation = leadFollowerInfo.m_leadLocal.GetRotation(); @@ -66,7 +78,9 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { m_jointHandle = sceneInterface->AddJoint( - leadFollowerInfo.m_followerBody->m_sceneOwner, &configuration, leadFollowerInfo.m_leadBody->m_bodyHandle, + leadFollowerInfo.m_followerBody->m_sceneOwner, + &configuration, + parentHandle, leadFollowerInfo.m_followerBody->m_bodyHandle); m_jointSceneOwner = leadFollowerInfo.m_followerBody->m_sceneOwner; } diff --git a/Gems/PhysX/Code/Source/Joint/PhysXJointUtils.cpp b/Gems/PhysX/Code/Source/Joint/PhysXJointUtils.cpp index 5b63a43966..3558c9fb56 100644 --- a/Gems/PhysX/Code/Source/Joint/PhysXJointUtils.cpp +++ b/Gems/PhysX/Code/Source/Joint/PhysXJointUtils.cpp @@ -190,8 +190,9 @@ namespace PhysX { { PxJointActorData actorData = GetJointPxActors(sceneHandle, parentBodyHandle, childBodyHandle); - if (!actorData.parentActor || !actorData.childActor) + if (actorData.parentActor == nullptr && actorData.childActor == nullptr) { + AZ_Warning("PhysX Joint", false, "CreateJoint failed - at least one body must be a PxRigidActor."); return nullptr; } @@ -239,7 +240,8 @@ namespace PhysX { { PxJointActorData actorData = GetJointPxActors(sceneHandle, parentBodyHandle, childBodyHandle); - if (!actorData.parentActor || !actorData.childActor) + //only check the child actor, as a null parent actor means this joint is a global constraint. + if (!actorData.childActor) { return nullptr; } @@ -252,7 +254,8 @@ namespace PhysX { { PHYSX_SCENE_READ_LOCK(actorData.childActor->getScene()); - joint = physx::PxFixedJointCreate(PxGetPhysics(), + joint = physx::PxFixedJointCreate( + PxGetPhysics(), actorData.parentActor, PxMathConvert(parentLocalTM), actorData.childActor, PxMathConvert(childLocalTM)); } @@ -272,7 +275,8 @@ namespace PhysX { { PxJointActorData actorData = GetJointPxActors(sceneHandle, parentBodyHandle, childBodyHandle); - if (!actorData.parentActor || !actorData.childActor) + // only check the child actor, as a null parent actor means this joint is a global constraint. + if (!actorData.childActor) { return nullptr; } @@ -306,7 +310,8 @@ namespace PhysX { { PxJointActorData actorData = GetJointPxActors(sceneHandle, parentBodyHandle, childBodyHandle); - if (!actorData.parentActor || !actorData.childActor) + // only check the child actor, as a null parent actor means this joint is a global constraint. + if (!actorData.childActor) { return nullptr; } diff --git a/Gems/PhysX/Code/Tests/PhysXJointsTest.cpp b/Gems/PhysX/Code/Tests/PhysXJointsTest.cpp index ff9cf11cca..ac5a99e29a 100644 --- a/Gems/PhysX/Code/Tests/PhysXJointsTest.cpp +++ b/Gems/PhysX/Code/Tests/PhysXJointsTest.cpp @@ -123,7 +123,7 @@ namespace PhysX const AZ::Vector3 followerEndPosition = RunJointTest(m_defaultScene, followerEntity->GetId()); - EXPECT_TRUE(followerEndPosition.GetX() > followerPosition.GetX()); + EXPECT_GT(followerEndPosition.GetX(), followerPosition.GetX()); } TEST_F(PhysXJointsTest, Joint_HingeJoint_FollowerSwingsAroundLead) @@ -164,8 +164,8 @@ namespace PhysX const AZ::Vector3 followerEndPosition = RunJointTest(m_defaultScene, followerEntity->GetId()); - EXPECT_TRUE(followerEndPosition.GetX() > followerPosition.GetX()); - EXPECT_TRUE(abs(followerEndPosition.GetZ()) > FLT_EPSILON); + EXPECT_GT(followerEndPosition.GetX(), followerPosition.GetX()); + EXPECT_GT(abs(followerEndPosition.GetZ()), FLT_EPSILON); } TEST_F(PhysXJointsTest, Joint_BallJoint_FollowerSwingsUpAboutLead) @@ -206,7 +206,65 @@ namespace PhysX const AZ::Vector3 followerEndPosition = RunJointTest(m_defaultScene, followerEntity->GetId()); - EXPECT_TRUE(followerEndPosition.GetZ() > followerPosition.GetZ()); + EXPECT_GT(followerEndPosition.GetZ(), followerPosition.GetZ()); + } + + TEST_F(PhysXJointsTest, Joint_BallJoint_GlobalConstraint) + { + // Place an entity in the world with a rigid body, physx collider, and a ball joint components. + // Do not set a lead entity on the ball joint component. + // Set entity's initial velocity to 10 in the X and Y directions on the rigid body component. + // The entity should swing up on the global constraint. + + const AZ::Vector3 followerPosition(0.0f, 0.0f, -1.0f); + const AZ::Vector3 followerInitialLinearVelocity(10.0f, 10.0f, 0.0f); + + const AZ::Vector3 jointLocalPosition(0.0f, 0.0f, 2.0f); + const AZ::Quaternion jointLocalRotation = AZ::Quaternion::CreateRotationY(90.0f); + const AZ::Transform jointLocalTransform = AZ::Transform::CreateFromQuaternionAndTranslation(jointLocalRotation, jointLocalPosition); + + //we want a global constraint, so leave the lead entity unset. + auto jointConfig = AZStd::make_shared(); + jointConfig->m_localTransformFromFollower = jointLocalTransform; + + auto jointLimits = AZStd::make_shared(); + jointLimits->m_isLimited = false; + + auto followerEntity = AddBodyColliderEntity( + m_testSceneHandle, followerPosition, followerInitialLinearVelocity, jointConfig, nullptr, jointLimits); + + const AZ::Vector3 followerEndPosition = RunJointTest(m_defaultScene, followerEntity->GetId()); + + EXPECT_GT(followerEndPosition.GetZ(), followerPosition.GetZ()); + } + + TEST_F(PhysXJointsTest, Joint_HingeJoint_GlobalConstraint) + { + // Place an entity in the world with a rigid body, physx collider, and a hinge joint components. + // Do not set a lead entity on the hinge joint component. + // Set entity's initial velocity to 10 in the X and Y directions on the rigid body component. + // The entity should swing up on the global constraint. + + const AZ::Vector3 followerPosition(0.0f, 0.0f, -1.0f); + const AZ::Vector3 followerInitialLinearVelocity(10.0f, 10.0f, 0.0f); + + const AZ::Vector3 jointLocalPosition(0.0f, 0.0f, 2.0f); + const AZ::Quaternion jointLocalRotation = AZ::Quaternion::CreateFromEulerAnglesDegrees(AZ::Vector3(0.0f, 180.0f, 90.0f)); + const AZ::Transform jointLocalTransform = AZ::Transform::CreateFromQuaternionAndTranslation(jointLocalRotation, jointLocalPosition); + + // do not set the lead entity as that makes this a global constraint + auto jointConfig = AZStd::make_shared(); + jointConfig->m_localTransformFromFollower = jointLocalTransform; + + auto jointLimits = AZStd::make_shared(); + jointLimits->m_isLimited = false; + + auto followerEntity = AddBodyColliderEntity( + m_testSceneHandle, followerPosition, followerInitialLinearVelocity, jointConfig, nullptr, jointLimits); + + const AZ::Vector3 followerEndPosition = RunJointTest(m_defaultScene, followerEntity->GetId()); + + EXPECT_GT(followerEndPosition.GetZ(), followerPosition.GetZ()); } // for some reason TYPED_TEST_CASE with the fixture is not working on Android + Linux From 252c268ffdf340ce43411f1b93c05a39eb92b35b Mon Sep 17 00:00:00 2001 From: jonawals Date: Mon, 16 Aug 2021 16:09:36 +0100 Subject: [PATCH 199/205] Fix corrupt merge. (#3142) * Further subdivide TIAF data by suite. * Key fix typo. Signed-off-by: John --- scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py index 5445c1f955..e499b0303c 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py @@ -125,9 +125,6 @@ class PersistentStorage(ABC): self._historic_data[self.HISTORIC_SEQUENCES_KEY] = {} self._historic_data[self.HISTORIC_SEQUENCES_KEY][self._this_commit_hash] = self._last_commit_hash - # Test runs for this completed sequence - self._historic_data[self.PREVIOUS_TEST_RUNS_KEY] = test_runs - # Coverage data for this branch with open(self._unpacked_coverage_data_file, "r") as coverage_data: self._historic_data[self.COVERAGE_DATA_KEY] = coverage_data.read() From 4f2d4d00ec612a5a7a9ad946ebedf6d04841640c Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Mon, 16 Aug 2021 08:40:27 -0700 Subject: [PATCH 200/205] Auto-completing the inserted text by pressing TAB within Editor's Console results in a silent crash Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- Code/Legacy/CrySystem/XConsole.cpp | 57 ++++++++---------------------- 1 file changed, 14 insertions(+), 43 deletions(-) diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp index ae07f86312..36443fb9ee 100644 --- a/Code/Legacy/CrySystem/XConsole.cpp +++ b/Code/Legacy/CrySystem/XConsole.cpp @@ -2873,7 +2873,7 @@ void CXConsole::Paste() ////////////////////////////////////////////////////////////////////////// int CXConsole::GetNumVars() { - return (int)m_mapVariables.size(); + return static_cast(m_mapVariables.size()); } ////////////////////////////////////////////////////////////////////////// @@ -3132,7 +3132,6 @@ char* CXConsole::GetCheatVarAt(uint32 nOffset) ////////////////////////////////////////////////////////////////////////// size_t CXConsole::GetSortedVars(AZStd::vector& pszArray, const char* szPrefix) { - size_t i = 0; size_t iPrefixLen = szPrefix ? strlen(szPrefix) : 0; // variables @@ -3140,11 +3139,6 @@ size_t CXConsole::GetSortedVars(AZStd::vector& pszArray, con ConsoleVariablesMap::const_iterator it, end = m_mapVariables.end(); for (it = m_mapVariables.begin(); it != end; ++it) { - if (i >= pszArray.size()) - { - break; - } - if (szPrefix) { if (_strnicmp(it->first, szPrefix, iPrefixLen) != 0) @@ -3158,9 +3152,7 @@ size_t CXConsole::GetSortedVars(AZStd::vector& pszArray, con continue; } - pszArray[i] = it->first; - - i++; + pszArray.push_back(it->first); } } @@ -3169,11 +3161,6 @@ size_t CXConsole::GetSortedVars(AZStd::vector& pszArray, con ConsoleCommandsMap::iterator it, end = m_mapCommands.end(); for (it = m_mapCommands.begin(); it != end; ++it) { - if (i >= pszArray.size()) - { - break; - } - if (szPrefix) { if (_strnicmp(it->first.c_str(), szPrefix, iPrefixLen) != 0) @@ -3187,25 +3174,18 @@ size_t CXConsole::GetSortedVars(AZStd::vector& pszArray, con continue; } - pszArray[i] = it->first.c_str(); - - i++; + pszArray.push_back(it->first.c_str()); } } - if (i != 0) - { - std::sort(pszArray.begin(), pszArray.end()); - } - - return i; + std::sort(pszArray.begin(), pszArray.end()); + return pszArray.size(); } ////////////////////////////////////////////////////////////////////////// void CXConsole::FindVar(const char* substr) { AZStd::vector cmds; - cmds.resize(GetNumVars() + m_mapCommands.size()); size_t cmdCount = GetSortedVars(cmds); for (size_t i = 0; i < cmdCount; i++) @@ -3231,10 +3211,9 @@ const char* CXConsole::AutoComplete(const char* substr) // following code can be optimized AZStd::vector cmds; - cmds.resize(GetNumVars() + m_mapCommands.size()); size_t cmdCount = GetSortedVars(cmds); - size_t substrLen = strlen(substr); + size_t substrLen = substr ? strlen(substr) : 0; // If substring is empty return first command. if (substrLen == 0 && cmdCount > 0) @@ -3246,7 +3225,7 @@ const char* CXConsole::AutoComplete(const char* substr) for (size_t i = 0; i < cmdCount; i++) { const char* szCmd = cmds[i].data(); - size_t cmdlen = strlen(szCmd); + size_t cmdlen = cmds[i].size(); if (cmdlen >= substrLen && memcmp(szCmd, substr, substrLen) == 0) { if (substrLen == cmdlen) @@ -3267,7 +3246,7 @@ const char* CXConsole::AutoComplete(const char* substr) { const char* szCmd = cmds[i].data(); - size_t cmdlen = strlen(szCmd); + size_t cmdlen = cmds[i].size(); if (cmdlen >= substrLen && azstrnicmp(szCmd, substr, substrLen) == 0) { if (substrLen == cmdlen) @@ -3301,27 +3280,19 @@ void CXConsole::SetInputLine(const char* szLine) const char* CXConsole::AutoCompletePrev(const char* substr) { AZStd::vector cmds; - cmds.resize(GetNumVars() + m_mapCommands.size()); - size_t cmdCount = GetSortedVars(cmds); + GetSortedVars(cmds); // If substring is empty return last command. - if (strlen(substr) == 0 && cmds.size() > 0) + if (strlen(substr) == 0 && !cmds.empty()) { - return cmds[cmdCount - 1].data(); + return cmds.back().data(); } - for (unsigned int i = 0; i < cmdCount; i++) + for (const AZStd::string_view& cmd : cmds) { - if (azstricmp(substr, cmds[i].data()) == 0) + if (azstricmp(substr, cmd.data()) == 0) { - if (i > 0) - { - return cmds[i - 1].data(); - } - else - { - return cmds[0].data(); - } + return cmd.data(); } } return AutoComplete(substr); From 994403bfa018dd96e8494c5b57fa8ba08b849819 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Mon, 16 Aug 2021 11:56:50 -0500 Subject: [PATCH 201/205] Updated Radius Weight Modifier component name for consistency. Signed-off-by: Chris Galvan --- .../EditorRadiusWeightModifierComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/RadiusWeightModifier/EditorRadiusWeightModifierComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/RadiusWeightModifier/EditorRadiusWeightModifierComponent.cpp index 039255276c..219ab6acb9 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/RadiusWeightModifier/EditorRadiusWeightModifierComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/RadiusWeightModifier/EditorRadiusWeightModifierComponent.cpp @@ -25,7 +25,7 @@ namespace AZ if (AZ::EditContext* editContext = serializeContext->GetEditContext()) { editContext->Class( - "Radius Weight Modifier", "Modifies PostFX override factor based on proximity of an influencer against this entity's bounding sphere") + "PostFX Radius Weight Modifier", "Modifies PostFX override factor based on proximity of an influencer against this entity's bounding sphere") ->ClassElement(Edit::ClassElements::EditorData, "") ->Attribute(Edit::Attributes::Category, "Atom") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Component_Placeholder.svg") From e2b4d8e50249727294bfdd0856b0d935f311aaa2 Mon Sep 17 00:00:00 2001 From: Jacob Hilliard <64656371+jcbhl@users.noreply.github.com> Date: Mon, 16 Aug 2021 10:13:24 -0700 Subject: [PATCH 202/205] Profiler: Runtime region name support (#2924) * Profiler: add support for runtime region names * Profiler: fix group name collisions * Profiler: use set of GroupRegionNames * Profiler: add comments + named constant Signed-off-by: Jacob Hilliard --- .../RHI/Code/Include/Atom/RHI/CpuProfiler.h | 16 +++++++++++ .../Code/Include/Atom/RHI/CpuProfilerImpl.h | 12 +++++++++ .../RHI/Code/Source/RHI/CpuProfilerImpl.cpp | 27 +++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h index 2248474820..3fedc99566 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h @@ -30,6 +30,12 @@ namespace AZ const char* const m_groupName = nullptr; const char* const m_regionName = nullptr; + + struct Hash + { + AZStd::size_t operator()(const GroupRegionName& name) const; + }; + bool operator==(const GroupRegionName& other) const; }; CachedTimeRegion() = default; @@ -95,6 +101,9 @@ namespace AZ virtual void SetProfilerEnabled(bool enabled) = 0; virtual bool IsProfilerEnabled() const = 0 ; + + //! Used by AZ_ATOM_PROFILE_DYNAMIC to create GroupRegionNames with known lifetimes. + virtual const CachedTimeRegion::GroupRegionName& InsertDynamicName(const char* groupName, const AZStd::string& regionName) = 0; }; } // namespace RPI @@ -120,3 +129,10 @@ namespace AZ #define AZ_ATOM_PROFILE_FUNCTION(groupName, regionName) \ AZ_TRACE_METHOD(); \ AZ_ATOM_PROFILE_TIME_GROUP_REGION(groupName, regionName) \ + +//! Macro that allows for region names to be submitted at runtime. Use sparingly - this acquires a lock and allocates new objects within a map. +#define AZ_ATOM_PROFILE_DYNAMIC(groupName, regionName) \ + static_assert(AZStd::is_convertible_v, "Runtime group names are not allowed, use a static string literal instead."); \ + const AZ::RHI::CachedTimeRegion::GroupRegionName& AZ_JOIN(groupRegionName, __LINE__) = \ + AZ::RHI::CpuProfiler::Get()->InsertDynamicName(groupName, regionName); \ + AZ::RHI::TimeRegion AZ_JOIN(timeRegion, __LINE__)(&AZ_JOIN(groupRegionName, __LINE__)); diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h index 7d3b0c5b81..2e4ca67db8 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -114,9 +115,11 @@ namespace AZ bool IsContinuousCaptureInProgress() const final override; void SetProfilerEnabled(bool enabled) final override; bool IsProfilerEnabled() const final override; + const CachedTimeRegion::GroupRegionName& InsertDynamicName(const char* groupName, const AZStd::string& regionName) final override; private: static constexpr AZStd::size_t MaxFramesToSave = 2 * 60 * 120; // 2 minutes of 120fps + static constexpr AZStd::size_t MaxRegionStringPoolSize = 16384; // Max amount of unique strings to save in the pool before throwing warnings. // Lazily create and register the local thread data void RegisterThreadStorage(); @@ -129,6 +132,15 @@ namespace AZ AZStd::vector, AZ::OSStdAllocator> m_registeredThreads; AZStd::mutex m_threadRegisterMutex; + // Pool for GroupRegionNames that are generated at runtime through AZ_ATOM_PROFILE_DYNAMIC. Each unique + // combination of group name and region name submitted will be stored in this pool to emulate static lifetime. + AZStd::unordered_set m_dynamicGroupRegionNamePool; + + // String pool for storing region names submitted at runtime. Each call to AZ_ATOM_PROFILE_DYNAMIC will either construct + // a string in this pool or use an already-existing entry. + AZStd::unordered_set m_regionNameStringPool; + AZStd::mutex m_dynamicNameMutex; + // Thread local storage, gets lazily allocated when a thread is created static thread_local CpuTimingLocalStorage* ms_threadLocalStorage; diff --git a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp index cdfd4ac469..d41b5d656e 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp @@ -74,6 +74,20 @@ namespace AZ { } + AZStd::size_t CachedTimeRegion::GroupRegionName::Hash::operator()(const CachedTimeRegion::GroupRegionName& name) const + { + AZStd::size_t seed = 0; + AZStd::hash_combine(seed, name.m_groupName); + AZStd::hash_combine(seed, name.m_regionName); + return seed; + } + + bool CachedTimeRegion::GroupRegionName::operator==(const GroupRegionName& other) const + { + return (m_groupName == other.m_groupName) && (m_regionName == other.m_regionName); + } + + // --- CpuProfilerImpl --- void CpuProfilerImpl::Init() @@ -218,6 +232,19 @@ namespace AZ return m_enabled; } + const CachedTimeRegion::GroupRegionName& CpuProfilerImpl::InsertDynamicName(const char* groupName, const AZStd::string& regionName) + { + AZStd::scoped_lock lock(m_dynamicNameMutex); + AZ_Warning("CpuProfiler", m_regionNameStringPool.size() < MaxRegionStringPoolSize, + "Stored dynamic region names are accumulating. Consider removing a AZ_ATOM_PROFILE_DYNAMIC invocation."); + auto [regionNameItr, wasRegionInserted] = m_regionNameStringPool.insert(regionName); + + CachedTimeRegion::GroupRegionName newGroupRegionName(groupName, regionNameItr->c_str()); + auto [groupRegionNameItr, wasGroupRegionInserted] = m_dynamicGroupRegionNamePool.insert(newGroupRegionName); + + return *groupRegionNameItr; + } + void CpuProfilerImpl::OnSystemTick() { if (!m_enabled) From 1c7f71f93a5bd42700f7f750d97ce50424048b13 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Mon, 16 Aug 2021 12:13:32 -0500 Subject: [PATCH 203/205] Updated Atom automated test that uses the PostFX Radius Weight Modifier. Signed-off-by: Chris Galvan --- ...ydra_AtomEditorComponents_AddedToEntity.py | 4 +-- .../atom_renderer/test_Atom_MainSuite.py | 26 +++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py index b4031d2ffa..cd10caf57b 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py @@ -206,8 +206,8 @@ def run(): # PostFX Layer Component ComponentTests("PostFX Layer") - # Radius Weight Modifier Component - ComponentTests("Radius Weight Modifier") + # PostFX Radius Weight Modifier Component + ComponentTests("PostFX Radius Weight Modifier") # Light Component ComponentTests("Light") diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index be75801b63..55c049b929 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -32,7 +32,7 @@ class TestAtomEditorComponentsMain(object): Tests the following Atom components and verifies all "expected_lines" appear in Editor.log: 1. Display Mapper 2. Light - 3. Radius Weight Modifier + 3. PostFX Radius Weight Modifier 4. PostFX Layer 5. Physical Sky 6. Global Skylight (IBL) @@ -126,18 +126,18 @@ class TestAtomEditorComponentsMain(object): "PostFX Layer_test: Entity deleted: True", "PostFX Layer_test: UNDO entity deletion works: True", "PostFX Layer_test: REDO entity deletion works: True", - # Radius Weight Modifier Component - "Radius Weight Modifier Entity successfully created", - "Radius Weight Modifier_test: Component added to the entity: True", - "Radius Weight Modifier_test: Component removed after UNDO: True", - "Radius Weight Modifier_test: Component added after REDO: True", - "Radius Weight Modifier_test: Entered game mode: True", - "Radius Weight Modifier_test: Exit game mode: True", - "Radius Weight Modifier_test: Entity is hidden: True", - "Radius Weight Modifier_test: Entity is shown: True", - "Radius Weight Modifier_test: Entity deleted: True", - "Radius Weight Modifier_test: UNDO entity deletion works: True", - "Radius Weight Modifier_test: REDO entity deletion works: True", + # PostFX Radius Weight Modifier Component + "PostFX Radius Weight Modifier Entity successfully created", + "PostFX Radius Weight Modifier_test: Component added to the entity: True", + "PostFX Radius Weight Modifier_test: Component removed after UNDO: True", + "PostFX Radius Weight Modifier_test: Component added after REDO: True", + "PostFX Radius Weight Modifier_test: Entered game mode: True", + "PostFX Radius Weight Modifier_test: Exit game mode: True", + "PostFX Radius Weight Modifier_test: Entity is hidden: True", + "PostFX Radius Weight Modifier_test: Entity is shown: True", + "PostFX Radius Weight Modifier_test: Entity deleted: True", + "PostFX Radius Weight Modifier_test: UNDO entity deletion works: True", + "PostFX Radius Weight Modifier_test: REDO entity deletion works: True", # Light Component "Light Entity successfully created", "Light_test: Component added to the entity: True", From b88a7faf642e102282b45021d91ea50d7ef18cc3 Mon Sep 17 00:00:00 2001 From: AMZN-stankowi <4838196+AMZN-stankowi@users.noreply.github.com> Date: Mon, 16 Aug 2021 10:18:45 -0700 Subject: [PATCH 204/205] Fixed issues with blend shape animations (#3080) Duplicate blend shape animations are now handled correctly. Invalid animation targets are now an error instead of a crash in the builder. Signed-off-by: stankowi <4838196+AMZN-stankowi@users.noreply.github.com> --- .../SDKWrapper/AssImpSceneWrapper.cpp | 3 + .../Importers/AssImpAnimationImporter.cpp | 32 ++++++- .../Importers/AssImpBlendShapeImporter.cpp | 87 ++++++++++++++++--- 3 files changed, 107 insertions(+), 15 deletions(-) diff --git a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp index 0680b41eca..12aefca00c 100644 --- a/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp +++ b/Code/Tools/SceneAPI/SDKWrapper/AssImpSceneWrapper.cpp @@ -70,6 +70,9 @@ namespace AZ // This results in the loss of the offset matrix data for nodes without a mesh which is required for the Transform Importer. m_importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false); m_importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES, false); + // The remove empty bones flag is on by default, but doesn't do anything internal to AssImp right now. + // This is here as a bread crumb to save others times investigating issues with empty bones. + // m_importer.SetPropertyBool(AI_CONFIG_IMPORT_REMOVE_EMPTY_BONES, false); m_sceneFileName = fileName; m_assImpScene = m_importer.ReadFile(fileName, aiProcess_Triangulate //Triangulates all faces of all meshes diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp index 150a50138e..97b5960a8d 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp @@ -147,7 +147,9 @@ namespace AZ SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { - serializeContext->Class()->Version(5); // [LYN-4226] Invert PostRotation matrix in animation chains + // Revision 5: [LYN-4226] Invert PostRotation matrix in animation chains + // Revision 6: Handle duplicate blend shape animations + serializeContext->Class()->Version(6); } } @@ -631,6 +633,15 @@ namespace AZ for (const auto& [meshIdx, keys] : valueToKeyDataMap) { + + if (static_cast(meshIdx) >= mesh->mNumAnimMeshes) + { + AZ_Error( + "AnimationImporter", false, + "Mesh %s has an animation mesh index reference of %d, but only has %d animation meshes. Skipping importing this. This is an error in the source scene file that should be corrected.", + mesh->mName.C_Str(), meshIdx, mesh->mNumAnimMeshes); + continue; + } AZStd::shared_ptr morphAnimNode = AZStd::make_shared(); @@ -656,12 +667,29 @@ namespace AZ morphAnimNode->AddKeyFrame(weight); } + // Some DCC tools, like Maya, include a full path separated by '.' in the node names. + // For example, "cone_skin_blendShapeNode.cone_squash" + // Downstream processing doesn't want anything but the last part of that node name, + // so find the last '.' and remove anything before it. const size_t dotIndex = nodeName.find_last_of('.'); nodeName = nodeName.substr(dotIndex + 1); morphAnimNode->SetBlendShapeName(nodeName.data()); - AZStd::string animNodeName(AZStd::string::format("%s_%s", s_animationNodeName, nodeName.data())); + // Duplicates can exist if an anim mesh had a name with a suffix like .001, in that case + // AssImp will strip off that suffix. Note that this behavior is separate from the + // scan for a period in the node name that came before this. + AZStd::string originalNodeName(AZStd::string::format("%s_%s", s_animationNodeName, nodeName.data())); + AZStd::string animNodeName(originalNodeName); + if (RenamedNodesMap::SanitizeNodeName( + animNodeName, context.m_scene.GetGraph(), context.m_currentGraphPosition, originalNodeName.c_str())) + { + AZ_Warning( + "AnimationImporter", false, + "Duplicate animations were found with the name %s on mesh %s. The duplicate will be named %s.", + originalNodeName.c_str(), mesh->mName.C_Str(), animNodeName.c_str()); + } + Containers::SceneGraph::NodeIndex addNode = context.m_scene.GetGraph().AddChild( context.m_currentGraphPosition, animNodeName.c_str(), AZStd::move(morphAnimNode)); context.m_scene.GetGraph().MakeEndPoint(addNode); diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp index e8eb5ecf68..8e447f9d79 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBlendShapeImporter.cpp @@ -40,7 +40,9 @@ namespace AZ SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { - serializeContext->Class()->Version(3); // LYN-2576 + // Revision 3: Fixed an issue where jack.fbx was failing to process + // Revision 4: Handle duplicate blend shape animations + serializeContext->Class()->Version(4); } } @@ -80,7 +82,32 @@ namespace AZ // AssImp separates meshes that have multiple materials. // This code re-combines them to match previous FBX SDK behavior, // so they can be separated by engine code instead. - AZStd::map>> animToMeshToAnimMeshIndices; + // Can't de-dupe nodes in the first loop because we can't generate names until we create nodes later. + // Because meshes are split on material at this point and need to be recombined, we can be in a position where + // There is a legit duped anim mesh that needs to be combined based on the outer non-anim mesh, + // or this is a duplicately named anim mesh that needs to be de-duped. There is also the case where both are true, + // it's a duplicate name and the non-anim mesh has to be deduped. + + // Helper struct to track an anim mesh and its associated mesh. + struct AnimMeshAndSceneMeshIndex + { + AnimMeshAndSceneMeshIndex(const aiAnimMesh* aiAnimMesh, const aiMesh* aiMesh) + : m_aiAnimMesh(aiAnimMesh) + , m_aiMesh(aiMesh) + { + } + const aiAnimMesh* m_aiAnimMesh = nullptr; + const aiMesh* m_aiMesh = nullptr; + }; + + // Helper struct to track all anim meshes at an index for all scene meshes. + struct AnimMeshAndSceneMeshes + { + AZStd::vector m_animMeshAndSceneMeshIndex; + }; + + // Map the animation index to the list of anim meshes at that index, and the mesh associated with those anim meshes. + AZStd::map animMeshIndexToSceneMeshes; for (int nodeMeshIdx = 0; nodeMeshIdx < numMesh; nodeMeshIdx++) { int sceneMeshIdx = context.m_sourceNode.GetAssImpNode()->mMeshes[nodeMeshIdx]; @@ -88,20 +115,57 @@ namespace AZ for (unsigned int animIdx = 0; animIdx < aiMesh->mNumAnimMeshes; animIdx++) { aiAnimMesh* aiAnimMesh = aiMesh->mAnimMeshes[animIdx]; - animToMeshToAnimMeshIndices[aiAnimMesh->mName.C_Str()].emplace_back(nodeMeshIdx, animIdx); + + // This code executes if: + // A mesh in the FBX file had multiple materials and blend shapes. + // This means that AssImp splits that mesh to one material per mesh. + // AssImp creates a set of anim meshes for each mesh based on that split. + // This verifies that those anim mesh arrays are in the same order across all split meshes, if it fails + // it means this logic needs to be updated, but it also catches that here earlier in an obvious way, + // instead of failing later in a harder to track way. + if (animMeshIndexToSceneMeshes.contains(animIdx)) + { + const AnimMeshAndSceneMeshIndex& firstExistingAnim( + animMeshIndexToSceneMeshes[animIdx].m_animMeshAndSceneMeshIndex[0]); + if (strcmp( + firstExistingAnim.m_aiAnimMesh->mName.C_Str(), + aiAnimMesh->mName.C_Str()) != 0) + { + AZ_Error( + Utilities::ErrorWindow, false, + "Meshes %s and %s on node %s have mismatched animations %s and %s at index %d. This can be resolved by " + "either manually separating meshes by material in the source scene file, or by updating this logic to " + "handle out of order animation indices.", + firstExistingAnim.m_aiMesh->mName.C_Str(), + aiMesh->mName.C_Str(), + context.m_sourceNode.GetName(), + firstExistingAnim.m_aiAnimMesh->mName.C_Str(), + aiAnimMesh->mName.C_Str(), animIdx); + return Events::ProcessingResult::Failure; + } + } + + animMeshIndexToSceneMeshes[animIdx].m_animMeshAndSceneMeshIndex.emplace_back( + AnimMeshAndSceneMeshIndex(aiAnimMesh, aiMesh)); } } - for (const auto& animToMeshIndex : animToMeshToAnimMeshIndices) + for (const auto& animMeshToSceneMeshes : animMeshIndexToSceneMeshes) { AZStd::shared_ptr blendShapeData = AZStd::make_shared(); + if (animMeshToSceneMeshes.second.m_animMeshAndSceneMeshIndex.size() == 0) + { + AZ_Error(Utilities::ErrorWindow, false, "Blend shape animations were expected but missing on node %s.", + context.m_sourceNode.GetName()); + return Events::ProcessingResult::Failure; + } // Some DCC tools, like Maya, include a full path separated by '.' in the node names. // For example, "cone_skin_blendShapeNode.cone_squash" // Downstream processing doesn't want anything but the last part of that node name, // so find the last '.' and remove anything before it. - AZStd::string nodeName(animToMeshIndex.first); + AZStd::string nodeName(animMeshToSceneMeshes.second.m_animMeshAndSceneMeshIndex[0].m_aiAnimMesh->mName.C_Str()); size_t dotIndex = nodeName.rfind('.'); if (dotIndex != AZStd::string::npos) { @@ -109,12 +173,11 @@ namespace AZ } int vertexOffset = 0; RenamedNodesMap::SanitizeNodeName(nodeName, context.m_scene.GetGraph(), context.m_currentGraphPosition, "BlendShape"); - AZ_TraceContext("Blend shape name", nodeName); - for (const auto& meshIndex : animToMeshIndex.second) + + for (const auto& animMeshAndSceneIndex : animMeshToSceneMeshes.second.m_animMeshAndSceneMeshIndex) { - int sceneMeshIdx = context.m_sourceNode.GetAssImpNode()->mMeshes[meshIndex.first]; - const aiMesh* aiMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[sceneMeshIdx]; - const aiAnimMesh* aiAnimMesh = aiMesh->mAnimMeshes[meshIndex.second]; + const aiAnimMesh* aiAnimMesh = animMeshAndSceneIndex.m_aiAnimMesh; + const aiMesh* aiMesh = animMeshAndSceneIndex.m_aiMesh; AZStd::bitset uvSetUsedFlags; for (AZ::u8 uvSetIndex = 0; uvSetIndex < SceneData::GraphData::BlendShapeData::MaxNumUVSets; ++uvSetIndex) @@ -199,6 +262,7 @@ namespace AZ face.mNumIndices); continue; } + for (unsigned int idx = 0; idx < face.mNumIndices; ++idx) { blendFace.vertexIndex[idx] = face.mIndices[idx] + vertexOffset; @@ -207,11 +271,8 @@ namespace AZ blendShapeData->AddFace(blendFace); } vertexOffset += aiMesh->mNumVertices; - - } - // Report problem if no vertex or face converted to MeshData if (blendShapeData->GetVertexCount() <= 0 || blendShapeData->GetFaceCount() <= 0) { From d6b268e84e54b3d606e129bf346010b88be4b1ba Mon Sep 17 00:00:00 2001 From: amzn-phist <52085794+amzn-phist@users.noreply.github.com> Date: Mon, 16 Aug 2021 12:41:24 -0500 Subject: [PATCH 205/205] Remove ResourceSelectorHost and clean up/refactor related bits (#3050) * Sever dependency on legacy resource selector host Audio resource selectors (browse dialogs) no longer need to be registered with the legacy IResourceSelectorHost system. Set up a new EBus specifically to handle browse button presses and directly invokes the dialog. Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> * Hook up legacy audio control selector to new EBus Remaining use of legacy audio selectors (trackview) need to be able to bypass ResourceSelectorHost now. Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> * Removes ResourceSelectorHost and legacy selectors This removes various Variable types that were tied to resource selectors, such as GeomCache, Model, Animation, File. Removes the ResourceSelectorHost completely. The two things that still appeared to have selectors in TrackView are Audio Controls and Texture. Fixed the audio control selector to work via EBus and the Texture selector didn't seem to work at all, but left it in as it was. Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> * Make the default audio selector return old value Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> * Fix some signed/unsigned comparison warnings Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> * Remove deleted function from Editor Mock Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> * Change audio selector api to use string_view Per feedback. Signed-off-by: amzn-phist <52085794+amzn-phist@users.noreply.github.com> --- .../ReflectedPropertyControl/PropertyCtrl.cpp | 3 - .../PropertyGenericCtrl.cpp | 10 -- .../PropertyGenericCtrl.h | 10 -- .../PropertyResourceCtrl.cpp | 78 ++++----- .../ReflectedPropertiesPanel.cpp | 93 ---------- .../ReflectedPropertiesPanel.h | 46 ----- .../ReflectedPropertyItem.cpp | 10 -- .../ReflectedPropertyControl/ReflectedVar.cpp | 14 -- .../ReflectedPropertyControl/ReflectedVar.h | 25 --- .../ReflectedVarWrapper.cpp | 21 +-- .../ReflectedVarWrapper.h | 14 -- Code/Editor/EditorPanelUtils.cpp | 4 +- Code/Editor/IEditor.h | 2 - Code/Editor/IEditorImpl.cpp | 2 - Code/Editor/IEditorImpl.h | 2 - Code/Editor/IEditorPanelUtils.h | 2 +- Code/Editor/Include/IResourceSelectorHost.h | 135 --------------- Code/Editor/Lib/Tests/IEditorMock.h | 1 - .../ComponentEntityEditorPlugin.cpp | 3 - .../SandboxIntegration.cpp | 11 -- .../SandboxIntegration.h | 1 - Code/Editor/ResourceSelectorHost.cpp | 163 ------------------ Code/Editor/ResourceSelectorHost.h | 18 -- Code/Editor/Util/Variable.cpp | 2 +- Code/Editor/Util/Variable.h | 6 - Code/Editor/Util/VariablePropertyType.cpp | 33 ---- Code/Editor/Util/VariablePropertyType.h | 6 - Code/Editor/editor_lib_files.cmake | 8 - .../API/ToolsApplicationAPI.h | 3 - .../UI/PropertyEditor/PropertyAudioCtrl.cpp | 19 +- .../UI/PropertyEditor/PropertyAudioCtrl.h | 21 +++ .../PropertyEditor/PropertyAudioCtrlTypes.h | 10 +- .../Editor/ATLControlsResourceDialog.cpp | 2 + .../Editor/AudioControlsEditorPlugin.cpp | 3 - .../Source/Editor/AudioControlsEditorPlugin.h | 4 +- .../Source/Editor/AudioResourceSelectors.cpp | 105 ++++------- .../Source/Editor/AudioResourceSelectors.h | 11 +- 37 files changed, 125 insertions(+), 776 deletions(-) delete mode 100644 Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.cpp delete mode 100644 Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.h delete mode 100644 Code/Editor/Include/IResourceSelectorHost.h delete mode 100644 Code/Editor/ResourceSelectorHost.cpp delete mode 100644 Code/Editor/ResourceSelectorHost.h diff --git a/Code/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp b/Code/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp index bf87f2017d..c228fbda09 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp @@ -10,7 +10,6 @@ // Editor #include "PropertyCtrl.h" -#include "PropertyAnimationCtrl.h" #include "PropertyResourceCtrl.h" #include "PropertyGenericCtrl.h" #include "PropertyMiscCtrl.h" @@ -22,9 +21,7 @@ void RegisterReflectedVarHandlers() if (!registered) { registered = true; - EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew AnimationPropertyWidgetHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew FileResourceSelectorWidgetHandler()); - EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew ReverbPresetPropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew SequencePropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew SequenceIdPropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew LocalStringPropertyHandler()); diff --git a/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp b/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp index a2c66b8b10..8ff83dd894 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp @@ -73,16 +73,6 @@ void GenericPopupPropertyEditor::SetPropertyType(PropertyType type) m_propertyType = type; } -void ReverbPresetPropertyEditor::onEditClicked() -{ - CSelectEAXPresetDlg PresetDlg(this); - PresetDlg.SetCurrPreset(GetValue()); - if (PresetDlg.exec() == QDialog::Accepted) - { - SetValue(PresetDlg.GetCurrPreset()); - } -} - void SequencePropertyEditor::onEditClicked() { CSelectSequenceDialog gtDlg(this); diff --git a/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h b/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h index 2296773f0a..b6b14cf125 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h +++ b/Code/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h @@ -96,15 +96,6 @@ public: } }; -class ReverbPresetPropertyEditor - : public GenericPopupPropertyEditor -{ -public: - ReverbPresetPropertyEditor(QWidget* pParent = nullptr) - : GenericPopupPropertyEditor(pParent){} - void onEditClicked() override; -}; - class MissionObjPropertyEditor : public GenericPopupPropertyEditor { @@ -155,7 +146,6 @@ public: // So we use our own #define CONST_AZ_CRC(name, value) AZ::u32(value) -using ReverbPresetPropertyHandler = GenericPopupWidgetHandler; using MissionObjPropertyHandler = GenericPopupWidgetHandler; using SequencePropertyHandler = GenericPopupWidgetHandler; using SequenceIdPropertyHandler = GenericPopupWidgetHandler; diff --git a/Code/Editor/Controls/ReflectedPropertyControl/PropertyResourceCtrl.cpp b/Code/Editor/Controls/ReflectedPropertyControl/PropertyResourceCtrl.cpp index d3ae6aaecf..c5ccc599d6 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/PropertyResourceCtrl.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/PropertyResourceCtrl.cpp @@ -17,9 +17,9 @@ // AzToolsFramework #include #include +#include // Editor -#include "IResourceSelectorHost.h" #include "Controls/QToolTipWidget.h" #include "Controls/BitmapToolTip.h" @@ -35,8 +35,8 @@ BrowseButton::BrowseButton(PropertyType type, QWidget* parent /*= nullptr*/) void BrowseButton::SetPathAndEmit(const QString& path) { - //only emit if path changes, except for ePropertyGeomCache. Old property control - if (path != m_path || m_propertyType == ePropertyGeomCache) + //only emit if path changes. Old property control + if (path != m_path) { m_path = path; emit PathChanged(m_path); @@ -78,21 +78,6 @@ private: // Filters for texture. selection = AssetSelectionModel::AssetGroupSelection("Texture"); } - else if (m_propertyType == ePropertyModel) - { - // Filters for models. - selection = AssetSelectionModel::AssetGroupSelection("Geometry"); - } - else if (m_propertyType == ePropertyGeomCache) - { - // Filters for geom caches. - selection = AssetSelectionModel::AssetTypeSelection("Geom Cache"); - } - else if (m_propertyType == ePropertyFile) - { - // Filters for files. - selection = AssetSelectionModel::AssetTypeSelection("File"); - } else { return; @@ -106,14 +91,7 @@ private: switch (m_propertyType) { case ePropertyTexture: - case ePropertyModel: newPath.replace("\\\\", "/"); - } - switch (m_propertyType) - { - case ePropertyTexture: - case ePropertyModel: - case ePropertyFile: if (newPath.size() > MAX_PATH) { newPath.resize(MAX_PATH); @@ -125,26 +103,51 @@ private: } }; -class ResourceSelectorButton +class AudioControlSelectorButton : public BrowseButton { public: - AZ_CLASS_ALLOCATOR(ResourceSelectorButton, AZ::SystemAllocator, 0); + AZ_CLASS_ALLOCATOR(AudioControlSelectorButton, AZ::SystemAllocator, 0); - ResourceSelectorButton(PropertyType type, QWidget* pParent = nullptr) + AudioControlSelectorButton(PropertyType type, QWidget* pParent = nullptr) : BrowseButton(type, pParent) { - setToolTip(tr("Select resource")); + setToolTip(tr("Select Audio Control")); } private: void OnClicked() override { - SResourceSelectorContext x; - x.parentWidget = this; - x.typeName = Prop::GetPropertyTypeToResourceType(m_propertyType); - QString newPath = GetIEditor()->GetResourceSelectorHost()->SelectResource(x, m_path); - SetPathAndEmit(newPath); + AZStd::string resourceResult; + auto ConvertLegacyAudioPropertyType = [](const PropertyType type) -> AzToolsFramework::AudioPropertyType + { + switch (type) + { + case ePropertyAudioTrigger: + return AzToolsFramework::AudioPropertyType::Trigger; + case ePropertyAudioRTPC: + return AzToolsFramework::AudioPropertyType::Rtpc; + case ePropertyAudioSwitch: + return AzToolsFramework::AudioPropertyType::Switch; + case ePropertyAudioSwitchState: + return AzToolsFramework::AudioPropertyType::SwitchState; + case ePropertyAudioEnvironment: + return AzToolsFramework::AudioPropertyType::Environment; + case ePropertyAudioPreloadRequest: + return AzToolsFramework::AudioPropertyType::Preload; + default: + return AzToolsFramework::AudioPropertyType::NumTypes; + } + }; + + auto propType = ConvertLegacyAudioPropertyType(m_propertyType); + if (propType != AzToolsFramework::AudioPropertyType::NumTypes) + { + AzToolsFramework::AudioControlSelectorRequestBus::EventResult( + resourceResult, propType, &AzToolsFramework::AudioControlSelectorRequestBus::Events::SelectResource, + AZStd::string_view{ m_path.toUtf8().constData() }); + SetPathAndEmit(QString{ resourceResult.c_str() }); + } } }; @@ -235,18 +238,13 @@ void FileResourceSelectorWidget::SetPropertyType(PropertyType type) AddButton(new TextureEditButton); m_previewToolTip.reset(new CBitmapToolTip); break; - case ePropertyModel: - case ePropertyGeomCache: case ePropertyAudioTrigger: case ePropertyAudioSwitch: case ePropertyAudioSwitchState: case ePropertyAudioRTPC: case ePropertyAudioEnvironment: case ePropertyAudioPreloadRequest: - AddButton(new ResourceSelectorButton(type)); - break; - case ePropertyFile: - AddButton(new FileBrowseButton(type)); + AddButton(new AudioControlSelectorButton(type)); break; default: break; diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.cpp b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.cpp deleted file mode 100644 index 8651db7e96..0000000000 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : implementation file - -#include "EditorDefs.h" - -#include "ReflectedPropertiesPanel.h" - -///////////////////////////////////////////////////////////////////////////// -// ReflectedPropertiesPanel dialog - - -ReflectedPropertiesPanel::ReflectedPropertiesPanel(QWidget* pParent) - : ReflectedPropertyControl(pParent) -{ -} - -////////////////////////////////////////////////////////////////////////// -void ReflectedPropertiesPanel::DeleteVars() -{ - ClearVarBlock(); - m_updateCallbacks.clear(); - m_varBlock = nullptr; -} - -////////////////////////////////////////////////////////////////////////// -void ReflectedPropertiesPanel::SetVarBlock(class CVarBlock* vb, ReflectedPropertyControl::UpdateVarCallback* updCallback, const char* category) -{ - assert(vb); - - m_varBlock = vb; - - RemoveAllItems(); - m_varBlock = vb; - AddVarBlock(m_varBlock, category); - - SetUpdateCallback(AZStd::bind(&ReflectedPropertiesPanel::OnPropertyChanged, this, AZStd::placeholders::_1)); - - // When new object set all previous callbacks freed. - m_updateCallbacks.clear(); - if (updCallback) - { - stl::push_back_unique(m_updateCallbacks, updCallback); - } -} - -////////////////////////////////////////////////////////////////////////// -void ReflectedPropertiesPanel::AddVars(CVarBlock* vb, ReflectedPropertyControl::UpdateVarCallback* updCallback, const char* category) -{ - assert(vb); - - bool bNewBlock = false; - // Make a clone of properties. - if (!m_varBlock) - { - RemoveAllItems(); - m_varBlock = vb->Clone(true); - AddVarBlock(m_varBlock, category); - bNewBlock = true; - } - m_varBlock->Wire(vb); - - if (bNewBlock) - { - SetUpdateCallback(AZStd::bind(&ReflectedPropertiesPanel::OnPropertyChanged, this, AZStd::placeholders::_1)); - - // When new object set all previous callbacks freed. - m_updateCallbacks.clear(); - } - - if (updCallback) - { - stl::push_back_unique(m_updateCallbacks, updCallback); - } -} - -void ReflectedPropertiesPanel::OnPropertyChanged(IVariable* pVar) -{ - std::list::iterator iter; - for (iter = m_updateCallbacks.begin(); iter != m_updateCallbacks.end(); ++iter) - { - (*iter)->operator()(pVar); - } -} - - diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.h b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.h deleted file mode 100644 index cd551c63e2..0000000000 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#ifndef CRYINCLUDE_EDITOR_REFLECTEDPROPERTIESPANEL_H -#define CRYINCLUDE_EDITOR_REFLECTEDPROPERTIESPANEL_H - -#pragma once - -#include "Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.h" -#include "Util/Variable.h" - -///////////////////////////////////////////////////////////////////////////// -// ReflectedPropertiesPanel dialog - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -//This class is a port of ReflectedPropertiesPanel to use the ReflectedPropertyControl -class SANDBOX_API ReflectedPropertiesPanel - : public ReflectedPropertyControl -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING -public: - ReflectedPropertiesPanel(QWidget* pParent = nullptr); // standard constructor - - void DeleteVars(); - void AddVars(class CVarBlock* vb, ReflectedPropertyControl::UpdateVarCallback* func = nullptr, const char* category = nullptr); - - void SetVarBlock(class CVarBlock* vb, ReflectedPropertyControl::UpdateVarCallback* func = nullptr, const char* category = nullptr); - -protected: - void OnPropertyChanged(IVariable* pVar); - -protected: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - TSmartPtr m_varBlock; - - std::list m_updateCallbacks; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - - -#endif // CRYINCLUDE_EDITOR_REFLECTEDPROPERTIESPANEL_H diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp index 5a9d61be42..303f86d270 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp @@ -255,9 +255,6 @@ void ReflectedPropertyItem::SetVariable(IVariable *var) case ePropertySelection: m_reflectedVarAdapter = new ReflectedVarEnumAdapter; break; - case ePropertyAnimation: - m_reflectedVarAdapter = new ReflectedVarAnimationAdapter; - break; case ePropertyColor: m_reflectedVarAdapter = new ReflectedVarColorAdapter; break; @@ -265,7 +262,6 @@ void ReflectedPropertyItem::SetVariable(IVariable *var) m_reflectedVarAdapter = new ReflectedVarUserAdapter; break; case ePropertyEquip: - case ePropertyReverbPreset: case ePropertyGameToken: case ePropertyMissionObj: case ePropertySequence: @@ -276,15 +272,12 @@ void ReflectedPropertyItem::SetVariable(IVariable *var) m_reflectedVarAdapter = new ReflectedVarGenericPropertyAdapter(desc.m_type); break; case ePropertyTexture: - case ePropertyModel: - case ePropertyGeomCache: case ePropertyAudioTrigger: case ePropertyAudioSwitch: case ePropertyAudioSwitchState: case ePropertyAudioRTPC: case ePropertyAudioEnvironment: case ePropertyAudioPreloadRequest: - case ePropertyFile: m_reflectedVarAdapter = new ReflectedVarResourceAdapter; break; case ePropertyFloatCurve: @@ -569,7 +562,6 @@ void ReflectedPropertyItem::SetValue(const QString& sValue, bool bRecordUndo, bo break; case ePropertyTexture: - case ePropertyModel: value.replace('\\', '/'); break; } @@ -578,8 +570,6 @@ void ReflectedPropertyItem::SetValue(const QString& sValue, bool bRecordUndo, bo switch (m_type) { case ePropertyTexture: - case ePropertyModel: - case ePropertyFile: if (value.length() >= MAX_PATH) { value = value.left(MAX_PATH); diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVar.cpp b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVar.cpp index 5b9c5b8063..263c17a8bb 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVar.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVar.cpp @@ -31,12 +31,6 @@ void ReflectedVarInit::setupReflection(AZ::SerializeContext* serializeContext) ->Field("description", &CReflectedVar::m_description) ->Field("varName", &CReflectedVar::m_varName); - serializeContext->Class () - ->Version(1) - ->Field("animation", &CReflectedVarAnimation::m_animation) - ->Field("entityID", &CReflectedVarAnimation::m_entityID) - ; - serializeContext->Class () ->Version(1) ->Field("path", &CReflectedVarResource::m_path) @@ -76,12 +70,6 @@ void ReflectedVarInit::setupReflection(AZ::SerializeContext* serializeContext) AZ::EditContext* ec = serializeContext->GetEditContext(); if (ec) { - ec->Class< CReflectedVarAnimation >("VarAnimation", "Animation") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &CReflectedVarAnimation::varName) - ->Attribute(AZ::Edit::Attributes::DescriptionTextOverride, &CReflectedVarAnimation::description) - ; - ec->Class< CReflectedVarResource >("VarResource", "Resource") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &CReflectedVarResource::varName) @@ -284,8 +272,6 @@ AZ::u32 CReflectedVarGenericProperty::handler() return AZ_CRC("ePropertyShader", 0xc40932f1); case ePropertyEquip: return AZ_CRC("ePropertyEquip", 0x66ffd290); - case ePropertyReverbPreset: - return AZ_CRC("ePropertyReverbPreset", 0x51469f38); case ePropertyDeprecated0: return AZ_CRC("ePropertyCustomAction", 0x4ffa5ba5); case ePropertyGameToken: diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVar.h b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVar.h index 634f2efd3a..a15f8326d1 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVar.h +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVar.h @@ -265,32 +265,8 @@ public: AZ::Vector3 m_color; }; -//Class to hold ePropertyAnimation (IVariable::DT_ANIMATION ) -class CReflectedVarAnimation - : public CReflectedVar -{ -public: - AZ_RTTI(CReflectedVarAnimation, "{635D982E-23EC-463F-8F33-4FC2C19D5673}", CReflectedVar) - - CReflectedVarAnimation(const AZStd::string& name) - : CReflectedVar(name) - , m_entityID(0) - {} - CReflectedVarAnimation() - : m_entityID(0){} - - AZStd::string varName() const { return m_varName; } - AZStd::string description() const { return m_description; } - - AZStd::string m_animation; - AZ::EntityId m_entityID; -}; - //Class to hold: // ePropertyTexture (IVariable::DT_TEXTURE) -// ePropertyMaterial (IVariable::DT_MATERIAL) -// ePropertyModel (IVariable::DT_OBJECT) -// ePropertyGeomCache (IVariable::DT_GEOM_CACHE) // ePropertyAudioTrigger (IVariable::DT_AUDIO_TRIGGER) // ePropertyAudioSwitch (IVariable::DT_AUDIO_SWITCH ) // ePropertyAudioSwitchState (IVariable::DT_AUDIO_SWITCH_STATE) @@ -344,7 +320,6 @@ public: AZStd::vector m_itemDescriptions; }; -//Class to hold ePropertyAnimation (IVariable::DT_ANIMATION ) class CReflectedVarSpline : public CReflectedVar { diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp index 5639fa95b0..aba346ce6a 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp @@ -392,25 +392,6 @@ void ReflectedVarColorAdapter::SyncIVarToReflectedVar(IVariable *pVariable) -void ReflectedVarAnimationAdapter::SetVariable(IVariable *pVariable) -{ - m_reflectedVar.reset(new CReflectedVarAnimation(pVariable->GetHumanName().toUtf8().data())); - m_reflectedVar->m_description = pVariable->GetDescription().toUtf8().data(); -} - -void ReflectedVarAnimationAdapter::SyncReflectedVarToIVar(IVariable *pVariable) -{ - m_reflectedVar->m_entityID = static_cast(pVariable->GetUserData().value()); - m_reflectedVar->m_animation = pVariable->GetDisplayValue().toUtf8().data(); -} - -void ReflectedVarAnimationAdapter::SyncIVarToReflectedVar(IVariable *pVariable) -{ - pVariable->SetUserData(static_cast(m_reflectedVar->m_entityID)); - pVariable->SetDisplayValue(m_reflectedVar->m_animation.c_str()); - -} - void ReflectedVarResourceAdapter::SetVariable(IVariable *pVariable) { m_reflectedVar.reset(new CReflectedVarResource(pVariable->GetHumanName().toUtf8().data())); @@ -429,7 +410,7 @@ void ReflectedVarResourceAdapter::SyncReflectedVarToIVar(IVariable *pVariable) void ReflectedVarResourceAdapter::SyncIVarToReflectedVar(IVariable *pVariable) { - const bool bForceModified = (m_reflectedVar->m_propertyType == ePropertyGeomCache); + const bool bForceModified = false; pVariable->SetForceModified(bForceModified); pVariable->SetDisplayValue(m_reflectedVar->m_path.c_str()); diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.h b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.h index 07bb72413a..9c49f1ae1a 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.h +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.h @@ -218,20 +218,6 @@ AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING }; -class EDITOR_CORE_API ReflectedVarAnimationAdapter - : public ReflectedVarAdapter -{ -public: - void SetVariable(IVariable* pVariable) override; - void SyncReflectedVarToIVar(IVariable* pVariable) override; - void SyncIVarToReflectedVar(IVariable* pVariable) override; - CReflectedVar* GetReflectedVar() override { return m_reflectedVar.data(); } -private: -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - QScopedPointer m_reflectedVar; -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - class EDITOR_CORE_API ReflectedVarResourceAdapter : public ReflectedVarAdapter { diff --git a/Code/Editor/EditorPanelUtils.cpp b/Code/Editor/EditorPanelUtils.cpp index b19bde4583..12e9457474 100644 --- a/Code/Editor/EditorPanelUtils.cpp +++ b/Code/Editor/EditorPanelUtils.cpp @@ -130,7 +130,7 @@ public: HotKey_BuildDefaults(); for (QPair key : keys) { - for (unsigned int j = 0; j < hotkeys.count(); j++) + for (int j = 0; j < hotkeys.count(); j++) { if (hotkeys[j].path.compare(key.first, Qt::CaseInsensitive) == 0) { @@ -256,7 +256,7 @@ public: hotkey.second = settings.value("keySequence").toString(); if (!hotkey.first.isEmpty()) { - for (unsigned int j = 0; j < hotkeys.count(); j++) + for (int j = 0; j < hotkeys.count(); j++) { if (hotkeys[j].path.compare(hotkey.first, Qt::CaseInsensitive) == 0) { diff --git a/Code/Editor/IEditor.h b/Code/Editor/IEditor.h index f66dca412e..7d0fc653fa 100644 --- a/Code/Editor/IEditor.h +++ b/Code/Editor/IEditor.h @@ -68,7 +68,6 @@ class CDisplaySettings; struct SGizmoParameters; class CLevelIndependentFileMan; class CSelectionTreeManager; -struct IResourceSelectorHost; struct SEditorSettings; class CGameExporter; class IAWSResourceManager; @@ -714,7 +713,6 @@ struct IEditor virtual ESystemConfigSpec GetEditorConfigSpec() const = 0; virtual ESystemConfigPlatform GetEditorConfigPlatform() const = 0; virtual void ReloadTemplates() = 0; - virtual IResourceSelectorHost* GetResourceSelectorHost() = 0; virtual void ShowStatusText(bool bEnable) = 0; // Provides a way to extend the context menu of an object. The function gets called every time the menu is opened. diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp index 1459139f66..1e268d64ef 100644 --- a/Code/Editor/IEditorImpl.cpp +++ b/Code/Editor/IEditorImpl.cpp @@ -67,7 +67,6 @@ AZ_POP_DISABLE_WARNING #include "EditorFileMonitor.h" #include "MainStatusBar.h" -#include "ResourceSelectorHost.h" #include "Util/FileUtil_impl.h" #include "Util/ImageUtil_impl.h" #include "LogFileImpl.h" @@ -187,7 +186,6 @@ CEditorImpl::CEditorImpl() m_pAnimationContext = new CAnimationContext; m_pImageUtil = new CImageUtil_impl(); - m_pResourceSelectorHost.reset(CreateResourceSelectorHost()); m_selectedRegion.min = Vec3(0, 0, 0); m_selectedRegion.max = Vec3(0, 0, 0); DetectVersion(); diff --git a/Code/Editor/IEditorImpl.h b/Code/Editor/IEditorImpl.h index 02be8bb8e3..2cf6c7805b 100644 --- a/Code/Editor/IEditorImpl.h +++ b/Code/Editor/IEditorImpl.h @@ -290,7 +290,6 @@ public: ESystemConfigPlatform GetEditorConfigPlatform() const; void ReloadTemplates(); void AddErrorMessage(const QString& text, const QString& caption); - IResourceSelectorHost* GetResourceSelectorHost() { return m_pResourceSelectorHost.get(); } virtual void ShowStatusText(bool bEnable); void OnObjectContextMenuOpened(QMenu* pMenu, const CBaseObject* pObject); @@ -374,7 +373,6 @@ protected: //! Export manager for exporting objects and a terrain from the game to DCC tools CExportManager* m_pExportManager; std::unique_ptr m_pEditorFileMonitor; - std::unique_ptr m_pResourceSelectorHost; QString m_selectFileBuffer; QString m_levelNameBuffer; diff --git a/Code/Editor/IEditorPanelUtils.h b/Code/Editor/IEditorPanelUtils.h index 5df15bd86b..4649213ae7 100644 --- a/Code/Editor/IEditorPanelUtils.h +++ b/Code/Editor/IEditorPanelUtils.h @@ -65,7 +65,7 @@ struct HotKey int size = (m_catSize < o_catSize) ? m_catSize : o_catSize; //sort categories to keep them together - for (unsigned int i = 0; i < size; i++) + for (int i = 0; i < size; i++) { if (m_categories[i] < o_categories[i]) { diff --git a/Code/Editor/Include/IResourceSelectorHost.h b/Code/Editor/Include/IResourceSelectorHost.h deleted file mode 100644 index 55ce4e15d3..0000000000 --- a/Code/Editor/Include/IResourceSelectorHost.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once -// The aim of IResourceSelectorHost is to unify resource selection dialogs in a one -// API that can be reused with plugins. It also makes possible to register new -// resource selectors dynamically, e.g. inside plugins. -// -// Here is how new selectors are created. In your implementation file you add handler function: -// -// #include "IResourceSelectorHost.h" -// -// QString SoundFileSelector(const SResourceSelectorContext& x, const QString& previousValue) -// { -// CMyModalDialog dialog(CWnd::FromHandle(x.parentWindow)); -// ... -// return previousValue; -// } -// REGISTER_RESOURCE_SELECTOR("Sound", SoundFileSelector, "Icons/sound_16x16.png") -// -// Here is how it can be invoked directly: -// -// SResourceSelectorContext x; -// x.parentWindow = parent.GetSafeHwnd(); -// x.typeName = "Sound"; -// string newValue = GetIEditor()->GetResourceSelector()->SelectResource(x, previousValue).c_str(); -// -// If you have your own resource selectors in the plugin you will need to run -// -// RegisterModuleResourceSelectors(GetIEditor()->GetResourceSelector()) -// -// during plugin initialization. -// -// If you want to be able to pass some custom context to the selector (e.g. source of the information for the -// list of items or something similar) then you can add a poitner argument to your selector function, i.e.: -// -// QString SoundFileSelector(const SResourceSelectorContext& x, const QString& previousValue, -// SoundFileList* list) // your context argument - -#include - -class QWidget; - -struct SResourceSelectorContext -{ - const char* typeName; - - // use either parentWidget or parentWindow (not both) until everything porting to QWidget. - QWidget* parentWidget; - - unsigned int entityId; - void* contextObject; - - SResourceSelectorContext() - : parentWidget(0) - , typeName(0) - , entityId(0) - , contextObject() - { - } -}; - -// TResourceSelecitonFunction is used to declare handlers for specific types. -// -// For canceled dialogs previousValue should be returned. -typedef QString (* TResourceSelectionFunction)(const SResourceSelectorContext& selectorContext, const QString& previousValue); -typedef QString (* TResourceSelectionFunctionWithContext)(const SResourceSelectorContext& selectorContext, const QString& previousValue, void* contextObject); - -struct SStaticResourceSelectorEntry; - -// See note at the beginning of the file. -struct IResourceSelectorHost -{ - virtual ~IResourceSelectorHost() = default; - virtual QString SelectResource(const SResourceSelectorContext& context, const QString& previousValue) = 0; - virtual const char* ResourceIconPath(const char* typeName) const = 0; - - virtual void RegisterResourceSelector(const SStaticResourceSelectorEntry* entry) = 0; - - // secondary responsibility of this class is to store global selections - virtual void SetGlobalSelection(const char* resourceType, const char* value) = 0; - virtual const char* GetGlobalSelection(const char* resourceType) const = 0; -}; - -// --------------------------------------------------------------------------- -#define INTERNAL_RSH_COMBINE_UTIL(A, B) A##B -#define INTERNAL_RSH_COMBINE(A, B) INTERNAL_RSH_COMBINE_UTIL(A, B) -#define REGISTER_RESOURCE_SELECTOR(name, function, icon) \ - static SStaticResourceSelectorEntry INTERNAL_RSH_COMBINE(selector_##function, __LINE__)((name), (function), (icon)); - -struct SStaticResourceSelectorEntry -{ - const char* typeName; - TResourceSelectionFunction function; - TResourceSelectionFunctionWithContext functionWithContext; - const char* iconPath; - - static SStaticResourceSelectorEntry*& GetFirst() { static SStaticResourceSelectorEntry* first; return first; } - SStaticResourceSelectorEntry* next; - - SStaticResourceSelectorEntry(const char* typeName, TResourceSelectionFunction function, const char* icon) - : typeName(typeName) - , function(function) - , functionWithContext() - , iconPath(icon) - { - next = GetFirst(); - GetFirst() = this; - } - - template - SStaticResourceSelectorEntry(const char* typeName, QString (*function)(const SResourceSelectorContext&, const QString& previousValue, T * context), const char* icon) - : typeName(typeName) - , function() - , functionWithContext(TResourceSelectionFunctionWithContext(function)) - , iconPath(icon) - { - next = GetFirst(); - GetFirst() = this; - } -}; - -inline void RegisterModuleResourceSelectors(IResourceSelectorHost* editorResourceSelector) -{ - for (SStaticResourceSelectorEntry* current = SStaticResourceSelectorEntry::GetFirst(); current != 0; current = current->next) - { - editorResourceSelector->RegisterResourceSelector(current); - } -} diff --git a/Code/Editor/Lib/Tests/IEditorMock.h b/Code/Editor/Lib/Tests/IEditorMock.h index 9f99b0cd9d..242bf4d25c 100644 --- a/Code/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Editor/Lib/Tests/IEditorMock.h @@ -178,7 +178,6 @@ public: MOCK_CONST_METHOD0(GetEditorConfigSpec, ESystemConfigSpec()); MOCK_CONST_METHOD0(GetEditorConfigPlatform, ESystemConfigPlatform()); MOCK_METHOD0(ReloadTemplates, void()); - MOCK_METHOD0(GetResourceSelectorHost, IResourceSelectorHost* ()); MOCK_METHOD1(ShowStatusText, void(bool )); MOCK_METHOD1(RegisterObjectContextMenuExtension, void(TContextMenuExtensionFunc )); MOCK_METHOD0(GetEnv, SSystemGlobalEnvironment* ()); diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp index 3f4cd1b566..50b315b9c3 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp @@ -9,7 +9,6 @@ #include "ComponentEntityEditorPlugin.h" #include -#include "IResourceSelectorHost.h" #include "UI/QComponentEntityEditorMainWindow.h" #include "UI/QComponentEntityEditorOutlinerWindow.h" @@ -180,8 +179,6 @@ ComponentEntityEditorPlugin::ComponentEntityEditorPlugin([[maybe_unused]] IEdito RegisterViewPane(LyViewPane::SliceRelationships, LyViewPane::CategoryTools, options); } - RegisterModuleResourceSelectors(GetIEditor()->GetResourceSelectorHost()); - ComponentEntityEditorPluginInternal::RegisterSandboxObjects(); // Check for common mistakes in component declarations diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 66c57361be..b10fe35513 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -82,7 +82,6 @@ #include #include #include -#include #include "CryEdit.h" #include "Undo/Undo.h" @@ -1387,16 +1386,6 @@ AZStd::string SandboxIntegrationManager::GetLevelName() return AZStd::string(GetIEditor()->GetGameEngine()->GetLevelName().toUtf8().constData()); } -AZStd::string SandboxIntegrationManager::SelectResource(const AZStd::string& resourceType, const AZStd::string& previousValue) -{ - SResourceSelectorContext context; - context.parentWidget = GetMainWindow(); - context.typeName = resourceType.c_str(); - - QString resource = GetEditor()->GetResourceSelectorHost()->SelectResource(context, previousValue.c_str()); - return AZStd::string(resource.toUtf8().constData()); -} - void SandboxIntegrationManager::OnContextReset() { // Deselect everything. diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h index a2ec3b579b..d14ba80bce 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h @@ -158,7 +158,6 @@ private: void LaunchLuaEditor(const char* files) override; bool IsLevelDocumentOpen() override; AZStd::string GetLevelName() override; - AZStd::string SelectResource(const AZStd::string& resourceType, const AZStd::string& previousValue) override; void OpenPinnedInspector(const AzToolsFramework::EntityIdSet& entities) override; void ClosePinnedInspector(AzToolsFramework::EntityPropertyEditor* editor) override; void GoToSelectedOrHighlightedEntitiesInViewports() override; diff --git a/Code/Editor/ResourceSelectorHost.cpp b/Code/Editor/ResourceSelectorHost.cpp deleted file mode 100644 index eb82b57ab4..0000000000 --- a/Code/Editor/ResourceSelectorHost.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "EditorDefs.h" - -#include "ResourceSelectorHost.h" - -// Qt -#include -#include - -// AzToolsFramework -#include -#include -#include - - -class CResourceSelectorHost - : public IResourceSelectorHost -{ -public: - CResourceSelectorHost() - { - RegisterModuleResourceSelectors(this); - } - - QString SelectResource(const SResourceSelectorContext& context, const QString& previousValue) override - { - if (!context.typeName) - { - assert(false && "SResourceSelectorContext::typeName is not specified"); - return QString(); - } - - TTypeMap::iterator it = m_typeMap.find(context.typeName); - if (it == m_typeMap.end()) - { - QMessageBox::critical(QApplication::activeWindow(), QString(), QObject::tr("No Resource Selector is registered for resource type \"%1\"").arg(context.typeName)); - return previousValue; - } - - QString result = previousValue; - if (it->second->function) - { - result = it->second->function(context, previousValue); - } - else if (it->second->functionWithContext) - { - result = it->second->functionWithContext(context, previousValue, context.contextObject); - } - - return result; - } - - const char* ResourceIconPath(const char* typeName) const override - { - TTypeMap::const_iterator it = m_typeMap.find(typeName); - if (it != m_typeMap.end()) - { - return it->second->iconPath; - } - return ""; - } - - void RegisterResourceSelector(const SStaticResourceSelectorEntry* entry) override - { - m_typeMap[entry->typeName] = entry; - } - - void SetGlobalSelection(const char* resourceType, const char* value) override - { - if (!resourceType || !value) - { - return; - } - m_globallySelectedResources[resourceType] = value; - } - - const char* GetGlobalSelection(const char* resourceType) const override - { - if (!resourceType) - { - return ""; - } - auto it = m_globallySelectedResources.find(resourceType); - if (it != m_globallySelectedResources.end()) - { - return it->second.c_str(); - } - return ""; - } - -private: - using TTypeMap = std::map>; - TTypeMap m_typeMap; - - std::map m_globallySelectedResources; -}; - -// --------------------------------------------------------------------------- - -IResourceSelectorHost* CreateResourceSelectorHost() -{ - return new CResourceSelectorHost(); -} - -// --------------------------------------------------------------------------- - -QString SoundFileSelector([[maybe_unused]] const SResourceSelectorContext& x, const QString& previousValue) -{ - AssetSelectionModel selection = AssetSelectionModel::AssetTypeSelection("Audio"); - AzToolsFramework::EditorRequests::Bus::Broadcast(&AzToolsFramework::EditorRequests::BrowseForAssets, selection); - if (selection.IsValid()) - { - return Path::FullPathToGamePath(QString(selection.GetResult()->GetFullPath().c_str())); - } - else - { - return Path::FullPathToGamePath(previousValue); - } -} -REGISTER_RESOURCE_SELECTOR("Sound", SoundFileSelector, "") - -// --------------------------------------------------------------------------- -QString ModelFileSelector([[maybe_unused]] const SResourceSelectorContext& x, const QString& previousValue) -{ - AssetSelectionModel selection = AssetSelectionModel::AssetGroupSelection("Geometry"); - AzToolsFramework::EditorRequests::Bus::Broadcast(&AzToolsFramework::EditorRequests::BrowseForAssets, selection); - if (selection.IsValid()) - { - return Path::FullPathToGamePath(QString(selection.GetResult()->GetFullPath().c_str())); - } - else - { - return Path::FullPathToGamePath(previousValue); - } -} -REGISTER_RESOURCE_SELECTOR("Model", ModelFileSelector, "") - -// --------------------------------------------------------------------------- -QString GeomCacheFileSelector([[maybe_unused]] const SResourceSelectorContext& x, const QString& previousValue) -{ - AssetSelectionModel selection = AssetSelectionModel::AssetTypeSelection("Geom Cache"); - AzToolsFramework::EditorRequests::Bus::Broadcast(&AzToolsFramework::EditorRequests::BrowseForAssets, selection); - if (selection.IsValid()) - { - return Path::FullPathToGamePath(QString(selection.GetResult()->GetFullPath().c_str())); - } - else - { - return Path::FullPathToGamePath(previousValue); - } -} - -REGISTER_RESOURCE_SELECTOR("GeomCache", GeomCacheFileSelector, "") - - diff --git a/Code/Editor/ResourceSelectorHost.h b/Code/Editor/ResourceSelectorHost.h deleted file mode 100644 index 266b7c39d1..0000000000 --- a/Code/Editor/ResourceSelectorHost.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_EDITOR_RESOURCESELECTORHOST_H -#define CRYINCLUDE_EDITOR_RESOURCESELECTORHOST_H -#pragma once - -#include "IResourceSelectorHost.h" - -IResourceSelectorHost* CreateResourceSelectorHost(); - -#endif // CRYINCLUDE_EDITOR_RESOURCESELECTORHOST_H diff --git a/Code/Editor/Util/Variable.cpp b/Code/Editor/Util/Variable.cpp index ee5ccc9879..97c2a1e8af 100644 --- a/Code/Editor/Util/Variable.cpp +++ b/Code/Editor/Util/Variable.cpp @@ -351,7 +351,7 @@ void CVarBlock::EnableUpdateCallbacks(bool boEnable) void CVarBlock::GatherUsedResourcesInVar(IVariable* pVar, CUsedResources& resources) { int type = pVar->GetDataType(); - if (type == IVariable::DT_FILE || type == IVariable::DT_OBJECT || type == IVariable::DT_TEXTURE) + if (type == IVariable::DT_TEXTURE) { // this is file. QString filename; diff --git a/Code/Editor/Util/Variable.h b/Code/Editor/Util/Variable.h index ecd54e42ae..da506b9db0 100644 --- a/Code/Editor/Util/Variable.h +++ b/Code/Editor/Util/Variable.h @@ -142,15 +142,10 @@ struct IVariable DT_PERCENT, //!< Percent data type, (Same as simple but value is from 0-1 and UI will be from 0-100). DT_COLOR, DT_ANGLE, - DT_FILE, DT_TEXTURE, - DT_ANIMATION, - DT_OBJECT, DT_SHADER, DT_LOCAL_STRING, DT_EQUIP, - DT_REVERBPRESET, - DT_DEPRECATED0, // formerly DT_MATERIAL DT_MATERIALLOOKUP, DT_EXTARRAY, // Extendable Array DT_SEQUENCE, // Movie Sequence (DEPRECATED, use DT_SEQUENCE_ID, instead.) @@ -160,7 +155,6 @@ struct IVariable DT_SEQUENCE_ID, // Movie Sequence DT_LIGHT_ANIMATION, // Light Animation Node in the global Light Animation Set DT_PARTICLE_EFFECT, - DT_GEOM_CACHE, // Geometry cache DT_DEPRECATED, // formerly DT_FLARE DT_AUDIO_TRIGGER, DT_AUDIO_SWITCH, diff --git a/Code/Editor/Util/VariablePropertyType.cpp b/Code/Editor/Util/VariablePropertyType.cpp index 014995467b..17c80a505c 100644 --- a/Code/Editor/Util/VariablePropertyType.cpp +++ b/Code/Editor/Util/VariablePropertyType.cpp @@ -37,17 +37,12 @@ namespace Prop { IVariable::DT_CURVE | IVariable::DT_PERCENT, "FloatCurve", ePropertyFloatCurve, 13 }, { IVariable::DT_CURVE | IVariable::DT_COLOR, "ColorCurve", ePropertyColorCurve, 1 }, { IVariable::DT_ANGLE, "Angle", ePropertyAngle, 0 }, - { IVariable::DT_FILE, "File", ePropertyFile, 7 }, { IVariable::DT_TEXTURE, "Texture", ePropertyTexture, 4 }, - { IVariable::DT_ANIMATION, "Animation", ePropertyAnimation, -1 }, { IVariable::DT_MOTION, "Motion", ePropertyMotion, -1 }, - { IVariable::DT_OBJECT, "Model", ePropertyModel, 5 }, { IVariable::DT_SIMPLE, "Selection", ePropertySelection, -1 }, { IVariable::DT_SIMPLE, "List", ePropertyList, -1 }, { IVariable::DT_SHADER, "Shader", ePropertyShader, 9 }, - { IVariable::DT_DEPRECATED0, "DEPRECATED", ePropertyDeprecated2, -1 }, { IVariable::DT_EQUIP, "Equip", ePropertyEquip, 11 }, - { IVariable::DT_REVERBPRESET, "ReverbPreset", ePropertyReverbPreset, 11 }, { IVariable::DT_LOCAL_STRING, "LocalString", ePropertyLocalString, 3 }, { IVariable::DT_SEQUENCE, "Sequence", ePropertySequence, -1 }, { IVariable::DT_MISSIONOBJ, "Mission Objective", ePropertyMissionObj, -1 }, @@ -55,7 +50,6 @@ namespace Prop { IVariable::DT_SEQUENCE_ID, "SequenceId", ePropertySequenceId, -1 }, { IVariable::DT_LIGHT_ANIMATION, "LightAnimation", ePropertyLightAnimation, -1 }, { IVariable::DT_PARTICLE_EFFECT, "ParticleEffect", ePropertyParticleName, 3 }, - { IVariable::DT_GEOM_CACHE, "Geometry Cache", ePropertyGeomCache, 5 }, { IVariable::DT_AUDIO_TRIGGER, "Audio Trigger", ePropertyAudioTrigger, 6 }, { IVariable::DT_AUDIO_SWITCH, "Audio Switch", ePropertyAudioSwitch, 6 }, { IVariable::DT_AUDIO_SWITCH_STATE, "Audio Switch", ePropertyAudioSwitchState, 6 }, @@ -301,31 +295,4 @@ namespace Prop return -1; } - - const char* GetPropertyTypeToResourceType(PropertyType type) - { - // The strings below are names used together with - // REGISTER_RESOURCE_SELECTOR. See IResourceSelector.h. - switch (type) - { - case ePropertyModel: - return "Model"; - case ePropertyGeomCache: - return "GeomCache"; - case ePropertyAudioTrigger: - return "AudioTrigger"; - case ePropertyAudioSwitch: - return "AudioSwitch"; - case ePropertyAudioSwitchState: - return "AudioSwitchState"; - case ePropertyAudioRTPC: - return "AudioRTPC"; - case ePropertyAudioEnvironment: - return "AudioEnvironment"; - case ePropertyAudioPreloadRequest: - return "AudioPreloadRequest"; - default: - return nullptr; - } - } } diff --git a/Code/Editor/Util/VariablePropertyType.h b/Code/Editor/Util/VariablePropertyType.h index af2865add1..decb930cb3 100644 --- a/Code/Editor/Util/VariablePropertyType.h +++ b/Code/Editor/Util/VariablePropertyType.h @@ -28,16 +28,11 @@ enum PropertyType ePropertyAngle, ePropertyFloatCurve, ePropertyColorCurve, - ePropertyFile, ePropertyTexture, - ePropertyAnimation, - ePropertyModel, ePropertySelection, ePropertyList, ePropertyShader, - ePropertyDeprecated2, // formerly ePropertyMaterial ePropertyEquip, - ePropertyReverbPreset, ePropertyLocalString, ePropertyDeprecated0, // formerly ePropertyCustomAction ePropertyGameToken, @@ -48,7 +43,6 @@ enum PropertyType ePropertyLightAnimation, ePropertyDeprecated1, // formerly ePropertyFlare ePropertyParticleName, - ePropertyGeomCache, ePropertyAudioTrigger, ePropertyAudioSwitch, ePropertyAudioSwitchState, diff --git a/Code/Editor/editor_lib_files.cmake b/Code/Editor/editor_lib_files.cmake index 4b80a5d461..c10db3bac5 100644 --- a/Code/Editor/editor_lib_files.cmake +++ b/Code/Editor/editor_lib_files.cmake @@ -289,7 +289,6 @@ set(FILES Include/IPlugin.h Include/IPreferencesPage.h Include/IRenderListener.h - Include/IResourceSelectorHost.h Include/ISourceControl.h Include/ISubObjectSelectionReferenceFrameCalculator.h Include/ITextureDatabaseUpdater.h @@ -360,8 +359,6 @@ set(FILES Controls/TimelineCtrl.cpp Controls/TimelineCtrl.h Controls/WndGridHelper.h - Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp - Controls/ReflectedPropertyControl/PropertyAnimationCtrl.h Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp Controls/ReflectedPropertyControl/PropertyGenericCtrl.h Controls/ReflectedPropertyControl/PropertyMiscCtrl.cpp @@ -372,8 +369,6 @@ set(FILES Controls/ReflectedPropertyControl/PropertyResourceCtrl.h Controls/ReflectedPropertyControl/PropertyCtrl.cpp Controls/ReflectedPropertyControl/PropertyCtrl.h - Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.cpp - Controls/ReflectedPropertyControl/ReflectedPropertiesPanel.h MainStatusBar.cpp MainStatusBar.h MainStatusBarItems.h @@ -590,8 +585,6 @@ set(FILES FBXExporterDialog.ui FileTypeUtils.cpp LightmapCompiler/SimpleTriangleRasterizer.cpp - ResourceSelectorHost.cpp - ResourceSelectorHost.h ToolBox.cpp TrackViewNewSequenceDialog.cpp TrackViewNewSequenceDialog.ui @@ -668,7 +661,6 @@ set(FILES TrackView/2DBezierKeyUIControls.cpp TrackView/AssetBlendKeyUIControls.cpp TrackView/CaptureKeyUIControls.cpp - TrackView/CharacterKeyUIControls.cpp TrackView/ConsoleKeyUIControls.cpp TrackView/EventKeyUIControls.cpp TrackView/GotoKeyUIControls.cpp diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h index f6046b9f25..9e5db5b5b7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h @@ -841,9 +841,6 @@ namespace AzToolsFramework */ virtual AZStd::string GetComponentIconPath(const AZ::Uuid& /*componentType*/, AZ::Crc32 /*componentIconAttrib*/, AZ::Component* /*component*/) { return AZStd::string(); } - /// Resource Selector hook, returns a path for a resource. - virtual AZStd::string SelectResource(const AZStd::string& /*resourceType*/, const AZStd::string& /*previousValue*/) { return AZStd::string(); } - /** * Calculate the navigation 2D radius in units of an agent given its Navigation Type Name * @param angentTypeName the name that identifies the agent navigation type diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrl.cpp index 6951d7ae8c..274db35da2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrl.cpp @@ -7,8 +7,8 @@ */ -#include "PropertyAudioCtrl.h" -#include "PropertyQTConstants.h" +#include +#include #include #include @@ -34,7 +34,7 @@ namespace AzToolsFramework : QWidget(parent) , m_browseEdit(nullptr) , m_mainLayout(nullptr) - , m_propertyType(AudioPropertyType::Invalid) + , m_propertyType(AudioPropertyType::NumTypes) { // create the gui m_mainLayout = new QHBoxLayout(); @@ -96,7 +96,7 @@ namespace AzToolsFramework return; } - if (type != AudioPropertyType::Invalid) + if (type != AudioPropertyType::NumTypes) { m_propertyType = type; } @@ -136,10 +136,11 @@ namespace AzToolsFramework void AudioControlSelectorWidget::OnOpenAudioControlSelector() { - AZStd::string resourceResult; - AZStd::string resourceType(GetResourceSelectorNameFromType(m_propertyType)); AZStd::string currentValue(m_controlName.toStdString().c_str()); - EditorRequests::Bus::BroadcastResult(resourceResult, &EditorRequests::Bus::Events::SelectResource, resourceType, currentValue); + AZStd::string resourceResult; + AudioControlSelectorRequestBus::EventResult( + resourceResult, m_propertyType, + &AudioControlSelectorRequestBus::Events::SelectResource, currentValue); SetControlName(QString(resourceResult.c_str())); } @@ -167,12 +168,12 @@ namespace AzToolsFramework { case AudioPropertyType::Trigger: return { "AudioTrigger" }; + case AudioPropertyType::Rtpc: + return { "AudioRTPC" }; case AudioPropertyType::Switch: return { "AudioSwitch" }; case AudioPropertyType::SwitchState: return { "AudioSwitchState" }; - case AudioPropertyType::Rtpc: - return { "AudioRTPC" }; case AudioPropertyType::Environment: return { "AudioEnvironment" }; case AudioPropertyType::Preload: diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrl.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrl.h index 4996806a8d..dbc45a592d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrl.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrl.h @@ -29,6 +29,27 @@ class QMimeData; namespace AzToolsFramework { + //============================================================================= + // Audio Control Selector Request Bus + // For connecting UI proper + //============================================================================= + class AudioControlSelectorRequests + : public AZ::EBusTraits + { + public: + // EBusTraits + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + using BusIdType = AudioPropertyType; + + virtual AZStd::string SelectResource(AZStd::string_view previousValue) + { + return previousValue; + } + }; + + using AudioControlSelectorRequestBus = AZ::EBus; + //============================================================================= // Audio Control Selector Widget //============================================================================= diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrlTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrlTypes.h index df31e297cd..c23e082a44 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrlTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAudioCtrlTypes.h @@ -18,15 +18,15 @@ namespace AzToolsFramework { //========================================================================= - enum class AudioPropertyType + enum class AudioPropertyType : AZ::u32 { - Invalid = 0, - Trigger, + Trigger = 0, + Rtpc, Switch, SwitchState, - Rtpc, Environment, Preload, + NumTypes, }; //========================================================================= @@ -40,7 +40,7 @@ namespace AzToolsFramework virtual ~CReflectedVarAudioControl() = default; AZStd::string m_controlName; - AudioPropertyType m_propertyType = AudioPropertyType::Invalid; + AudioPropertyType m_propertyType = AudioPropertyType::NumTypes; static void Reflect(AZ::ReflectContext* context) { diff --git a/Gems/AudioSystem/Code/Source/Editor/ATLControlsResourceDialog.cpp b/Gems/AudioSystem/Code/Source/Editor/ATLControlsResourceDialog.cpp index 46941baf17..d3121f6245 100644 --- a/Gems/AudioSystem/Code/Source/Editor/ATLControlsResourceDialog.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/ATLControlsResourceDialog.cpp @@ -30,6 +30,8 @@ namespace AudioControls : QDialog(pParent) , m_eType(eType) { + AZ_Assert(CAudioControlsEditorPlugin::GetATLModel() != nullptr, "ATLControlsDialog - ATL Model is null!"); + setWindowTitle(GetWindowTitle(m_eType)); setWindowModality(Qt::ApplicationModal); diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp index 2b7023df61..f3d5a03ffc 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp @@ -14,8 +14,6 @@ #include #include -#include - #include #include #include @@ -41,7 +39,6 @@ CAudioControlsEditorPlugin::CAudioControlsEditorPlugin(IEditor* editor) QtViewOptions options; options.canHaveMultipleInstances = true; RegisterQtViewPane(editor, LyViewPane::AudioControlsEditor, LyViewPane::CategoryOther, options); - RegisterAudioControlsResourceSelectors(); Audio::AudioSystemRequestBus::BroadcastResult(ms_pIAudioProxy, &Audio::AudioSystemRequestBus::Events::GetFreeAudioProxy); diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.h b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.h index 4e5c528901..f8288a5d7f 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.h +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.h @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -68,6 +69,7 @@ private: static AudioControls::FilepathSet ms_currentFilenames; static Audio::IAudioProxy* ms_pIAudioProxy; static Audio::TAudioControlID ms_nAudioTriggerID; - static CImplementationManager ms_implementationManager; + + AudioControls::AudioControlSelectorHandler m_controlSelector; }; diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp index 74233be2e9..a6ab3878b8 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp @@ -10,88 +10,45 @@ #include #include #include -#include -#include #include +#include + namespace AudioControls { //-------------------------------------------------------------------------------------------// - QString ShowSelectDialog(const SResourceSelectorContext& context, const QString& pPreviousValue, const EACEControlType controlType) + AudioControlSelectorHandler::AudioControlSelectorHandler() { - AZ_Assert(CAudioControlsEditorPlugin::GetATLModel() != nullptr, "AudioResourceSelectors - ATL Model is null!"); - - AZStd::string levelName; - AzToolsFramework::EditorRequestBus::BroadcastResult(levelName, &AzToolsFramework::EditorRequests::GetLevelName); - - ATLControlsDialog dialog(context.parentWidget, controlType); - dialog.SetScope(levelName); - return dialog.ChooseItem(pPreviousValue.toUtf8().constData()); - } - - //-------------------------------------------------------------------------------------------// - QString AudioTriggerSelector(const SResourceSelectorContext& context, const QString& pPreviousValue) - { - return ShowSelectDialog(context, pPreviousValue, eACET_TRIGGER); - } - - //-------------------------------------------------------------------------------------------// - QString AudioSwitchSelector(const SResourceSelectorContext& context, const QString& pPreviousValue) - { - return ShowSelectDialog(context, pPreviousValue, eACET_SWITCH); - } - - //-------------------------------------------------------------------------------------------// - QString AudioSwitchStateSelector(const SResourceSelectorContext& context, const QString& pPreviousValue) - { - return ShowSelectDialog(context, pPreviousValue, eACET_SWITCH_STATE); - } - - //-------------------------------------------------------------------------------------------// - QString AudioRTPCSelector(const SResourceSelectorContext& context, const QString& pPreviousValue) - { - return ShowSelectDialog(context, pPreviousValue, eACET_RTPC); - } - - //-------------------------------------------------------------------------------------------// - QString AudioEnvironmentSelector(const SResourceSelectorContext& context, const QString& pPreviousValue) - { - return ShowSelectDialog(context, pPreviousValue, eACET_ENVIRONMENT); - } - - //-------------------------------------------------------------------------------------------// - QString AudioPreloadRequestSelector(const SResourceSelectorContext& context, const QString& pPreviousValue) - { - return ShowSelectDialog(context, pPreviousValue, eACET_PRELOAD); - } - - //-------------------------------------------------------------------------------------------// - static SStaticResourceSelectorEntry audioTriggerSelector( - "AudioTrigger", AudioTriggerSelector, ":/Icons/Trigger_Icon.svg"); - static SStaticResourceSelectorEntry audioSwitchSelector( - "AudioSwitch", AudioSwitchSelector, ":/Icons/Switch_Icon.svg"); - static SStaticResourceSelectorEntry audioStateSelector( - "AudioSwitchState", AudioSwitchStateSelector, ":/Icons/Property_Icon.png"); - static SStaticResourceSelectorEntry audioRtpcSelector( - "AudioRTPC", AudioRTPCSelector, ":/Icons/RTPC_Icon.svg"); - static SStaticResourceSelectorEntry audioEnvironmentSelector( - "AudioEnvironment", AudioEnvironmentSelector, ":/Icons/Environment_Icon.svg"); - static SStaticResourceSelectorEntry audioPreloadSelector( - "AudioPreloadRequest", AudioPreloadRequestSelector, ":/Icons/Bank_Icon.png"); - - //-------------------------------------------------------------------------------------------// - void RegisterAudioControlsResourceSelectors() - { - if (IResourceSelectorHost* host = GetIEditor()->GetResourceSelectorHost(); - host != nullptr) + for (AZ::u32 type = 0; type < static_cast(AzToolsFramework::AudioPropertyType::NumTypes); ++type) { - host->RegisterResourceSelector(&audioTriggerSelector); - host->RegisterResourceSelector(&audioSwitchSelector); - host->RegisterResourceSelector(&audioStateSelector); - host->RegisterResourceSelector(&audioRtpcSelector); - host->RegisterResourceSelector(&audioEnvironmentSelector); - host->RegisterResourceSelector(&audioPreloadSelector); + AzToolsFramework::AudioControlSelectorRequestBus::MultiHandler::BusConnect( + static_cast(type)); } } + AudioControlSelectorHandler::~AudioControlSelectorHandler() + { + AzToolsFramework::AudioControlSelectorRequestBus::MultiHandler::BusDisconnect(); + } + + AZStd::string AudioControlSelectorHandler::SelectResource(AZStd::string_view previousValue) + { + using namespace AzToolsFramework; + if (auto busId = AudioControlSelectorRequestBus::GetCurrentBusId(); + busId != nullptr) + { + auto controlType = static_cast(*busId); + QWidget* parentWidget = nullptr; + AzToolsFramework::EditorRequestBus::BroadcastResult(parentWidget, &AzToolsFramework::EditorRequestBus::Events::GetMainWindow); + + AZStd::string levelName; + AzToolsFramework::EditorRequestBus::BroadcastResult(levelName, &AzToolsFramework::EditorRequests::GetLevelName); + + ATLControlsDialog dialog(parentWidget, controlType); + dialog.SetScope(levelName); + return dialog.ChooseItem(previousValue.data()); + } + return previousValue; + } + } // namespace AudioControls diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.h b/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.h index d2bff7c799..127cfb15b4 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.h +++ b/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.h @@ -8,7 +8,16 @@ #pragma once +#include + namespace AudioControls { - void RegisterAudioControlsResourceSelectors(); + class AudioControlSelectorHandler + : public AzToolsFramework::AudioControlSelectorRequestBus::MultiHandler + { + public: + AudioControlSelectorHandler(); + ~AudioControlSelectorHandler(); + AZStd::string SelectResource(AZStd::string_view previousValue) override; + }; }