merge from main

This commit is contained in:
greerdv
2021-05-19 12:14:25 +01:00
11816 changed files with 189923 additions and 1002401 deletions
@@ -36,4 +36,4 @@ namespace AzToolsFramework
};
using EditorAnimationSystemRequestsBus = AZ::EBus<EditorAnimationSystemRequests>;
}
}
@@ -13,6 +13,12 @@
#include <AzCore/EBus/EBus.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/std/string/string.h>
namespace AZ
{
struct BehaviorParameter;
}
namespace AzToolsFramework
{
@@ -40,6 +46,8 @@ namespace AzToolsFramework
};
using GlobalFunctionCollection = AZStd::vector<GlobalFunction>;
virtual void GetGlobalFunctionList(GlobalFunctionCollection& globalFunctionCollection) const = 0;
virtual AZStd::string FetchPythonTypeName(const AZ::BehaviorParameter& param) = 0;
};
//! Interface to signal the phases for the Python virtual machine
@@ -52,4 +52,4 @@ namespace AzToolsFramework
using EntityCompositionNotificationBus = AZ::EBus<EntityCompositionNotifications>;
}
}
@@ -31,6 +31,10 @@ namespace AzToolsFramework
//! Allows a component to get the list of selected entities
//! \param selectedEntityIds the return vector holding the entities required
virtual void GetSelectedEntities(EntityIdList& selectedEntityIds) = 0;
//! Explicitly sets a component as having been the most recently added.
//! This means that the next time the UI refreshes, that component will be ensured to be visible.
virtual void SetNewComponentId(AZ::ComponentId componentId) = 0;
};
using EntityPropertyEditorRequestBus = AZ::EBus<EntityPropertyEditorRequests>;
@@ -348,6 +348,11 @@ namespace AzToolsFramework
*/
virtual bool AreAnyEntitiesSelected() = 0;
/*!
* Returns the number of selected entities.
*/
virtual int GetSelectedEntitiesCount() = 0;
/*!
* Retrieves the set of selected entities.
* \return a list of entity Ids.
@@ -756,16 +761,6 @@ namespace AzToolsFramework
/// If the view pane was not registered with the ViewPaneOptions.isDeletable set to true, the view pane will be hidden instead.
virtual void CloseViewPane(const char* /*paneName*/) {}
/// Request generation of all level cubemaps.
virtual void GenerateAllCubemaps() {}
/// Regenerate cubemap for a particular entity.
/// \param entityId ID of the entity that the cubemap is for
/// \param cubemapOutputPath path to a image file to generate
/// \param hideEntity Indicates whether the entity should be hidden during cubemap generation. Controls whether the entity's current cubemap output is baked into the new cubemap.
virtual void GenerateCubemapForEntity(AZ::EntityId /*entityId*/, AZStd::string* /*cubemapOutputPath*/, bool /*hideEntity*/) {}
virtual void GenerateCubemapWithIDForEntity(AZ::EntityId /*entityId*/, AZ::Uuid /*cubemapId*/, AZStd::string* /*cubemapOutputPath*/, bool /*hideEntity*/, bool /*hasCubemapId*/) {}
//! Spawn asset browser for the appropriate asset types.
virtual void BrowseForAssets(AssetBrowser::AssetSelectionModel& /*selection*/) = 0;
@@ -57,4 +57,4 @@ namespace AzToolsFramework
}
}
#include "Application/moc_Ticker.cpp"
#include "Application/moc_Ticker.cpp"
@@ -55,4 +55,4 @@ namespace AzToolsFramework
float m_timeoutMS;
};
}
}
@@ -284,6 +284,10 @@ namespace AzToolsFramework
void ToolsApplication::Start(const Descriptor& descriptor, const StartupParameters& startupParameters/* = StartupParameters()*/)
{
Application::Start(descriptor, startupParameters);
if (!m_isStarted)
{
return;
}
m_editorEntityManager.Start();
@@ -395,6 +399,7 @@ namespace AzToolsFramework
->Event("MarkEntityDeselected", &ToolsApplicationRequests::MarkEntityDeselected)
->Event("IsSelected", &ToolsApplicationRequests::IsSelected)
->Event("AreAnyEntitiesSelected", &ToolsApplicationRequests::AreAnyEntitiesSelected)
->Event("GetSelectedEntitiesCount", &ToolsApplicationRequests::GetSelectedEntitiesCount)
;
behaviorContext->EBus<ToolsApplicationNotificationBus>("ToolsApplicationNotificationBus")
@@ -670,20 +675,8 @@ namespace AzToolsFramework
// if the new viewport interaction model is enabled we do not want to
// filter out locked entities as this breaks with the logic of being
// able to select locked entities in the entity outliner
if (IsNewViewportInteractionModelEnabled())
{
selectedEntitiesFiltered.insert(
selectedEntitiesFiltered.begin(), selectedEntities.begin(), selectedEntities.end());
}
else
{
for (AZ::EntityId nowSelectedId : selectedEntities)
{
AZ_Assert(nowSelectedId.IsValid(), "Invalid entity Id being marked as selected.");
selectedEntitiesFiltered.push_back(nowSelectedId);
}
}
selectedEntitiesFiltered.insert(
selectedEntitiesFiltered.begin(), selectedEntities.begin(), selectedEntities.end());
EntityIdList newlySelectedIds;
EntityIdList newlyDeselectedIds;
@@ -101,6 +101,7 @@ namespace AzToolsFramework
SourceControlFileInfo GetSceneSourceControlInfo() override;
bool AreAnyEntitiesSelected() override { return !m_selectedEntities.empty(); }
int GetSelectedEntitiesCount() override { return m_selectedEntities.size(); }
const EntityIdList& GetSelectedEntities() override { return m_selectedEntities; }
const EntityIdList& GetHighlightedEntities() override { return m_highlightedEntities; }
void SetSelectedEntities(const EntityIdList& selectedEntities) override;
@@ -216,14 +216,9 @@ namespace AzToolsFramework::AssetUtils
constexpr const char* AssetProcessorGamePlatformConfigFileName = "AssetProcessorGamePlatformConfig.ini";
constexpr const char* AssetProcessorGamePlatformConfigSetreg = "AssetProcessorGamePlatformConfig.setreg";
AZStd::vector<AZ::IO::Path> configFiles;
AZ::IO::Path configRoot(engineRoot);
AZ::IO::Path rootConfigFile = configRoot / AssetProcessorPlatformConfigFileName;
configFiles.push_back(rootConfigFile);
// Add a file entry for the Engine Root AssetProcessor setreg file
rootConfigFile = configRoot / AssetProcessorPlatformConfigSetreg;
configFiles.push_back(rootConfigFile);
// Add the AssetProcessorPlatformConfig setreg file at the engine root
configFiles.push_back(AZ::IO::Path(engineRoot) / AssetProcessorPlatformConfigSetreg);
if (addPlatformConfigs)
{
@@ -200,71 +200,69 @@ namespace AzToolsFramework
{
if (AzFramework::StringFunc::Equal(extension.c_str(), ".abc"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/ABC_16.svg");
return SourceFileDetails("Icons/AssetBrowser/ABC_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".bnk"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/Audio_16.svg");
return SourceFileDetails("Icons/AssetBrowser/Audio_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".cgf"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/LegacyMesh_16.svg");
return SourceFileDetails("Icons/AssetBrowser/LegacyMesh_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".font"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/Font_16.svg");
return SourceFileDetails("Icons/AssetBrowser/Font_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".fontfamily"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/Font_16.svg");
return SourceFileDetails("Icons/AssetBrowser/Font_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".i_caf"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/LegacyAnimation_16.svg");
return SourceFileDetails("Icons/AssetBrowser/LegacyAnimation_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".inputbindings"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/InputBindings_16.svg");
return SourceFileDetails("Icons/AssetBrowser/InputBindings_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".lua"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/Lua_16.svg");
return SourceFileDetails("Icons/AssetBrowser/Lua_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".mtl"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/Material_16.svg");
return SourceFileDetails("Icons/AssetBrowser/Material_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), AzToolsFramework::SliceUtilities::GetSliceFileExtension().c_str()))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/Slice_16.svg");
return SourceFileDetails("Icons/AssetBrowser/Slice_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".skin"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/LegacySkin_16.svg");
return SourceFileDetails("Icons/AssetBrowser/LegacySkin_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".ttf"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/Font_16.svg");
return SourceFileDetails("Icons/AssetBrowser/Font_16.svg");
}
if (AzFramework::StringFunc::Equal(extension.c_str(), ".xml"))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/XML_16.svg");
return SourceFileDetails("Icons/AssetBrowser/XML_16.svg");
}
// this is here to prevent having to include IResourceCompilerHelper, which is in CryCommon.
static const char* sourceFormats[] = { ".tif", ".bmp", ".gif", ".jpg", ".jpeg", ".jpe", ".tga", ".png" };
for (unsigned int sourceImageFormatIndex = 0, numSources = AZ_ARRAY_SIZE(sourceFormats); sourceImageFormatIndex < numSources; ++sourceImageFormatIndex)
@@ -272,7 +270,7 @@ namespace AzToolsFramework
const char* sourceFormatExtension = sourceFormats[sourceImageFormatIndex];
if (AzFramework::StringFunc::Equal(extension.c_str(), sourceFormatExtension))
{
return SourceFileDetails("Editor/Icons/AssetBrowser/Image_16.svg");
return SourceFileDetails("Icons/AssetBrowser/Image_16.svg");
}
}
}
@@ -165,4 +165,4 @@ namespace AzToolsFramework
AZ::Data::AssetId m_assetId;
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -75,4 +75,4 @@ namespace AzToolsFramework
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -76,4 +76,4 @@ namespace AzToolsFramework
QString m_title;
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -283,4 +283,4 @@ namespace AzToolsFramework
} // namespace AssetBrowser
} // namespace AzToolsFramework
#include "AssetBrowser/Entries/moc_AssetBrowserEntry.cpp"
#include "AssetBrowser/Entries/moc_AssetBrowserEntry.cpp"
@@ -69,4 +69,4 @@ namespace AzToolsFramework
m_absolutePathToFileId.clear();
}
}
}
}
@@ -55,4 +55,4 @@ namespace AzToolsFramework
AZ_DISABLE_COPY_MOVE(FolderAssetBrowserEntry);
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -63,4 +63,4 @@ namespace AzToolsFramework
AZ_DISABLE_COPY_MOVE(ProductAssetBrowserEntry);
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -52,17 +52,16 @@ namespace AzToolsFramework
return AssetEntryType::Root;
}
void RootAssetBrowserEntry::Update(const char* devPath)
void RootAssetBrowserEntry::Update(const char* enginePath)
{
RemoveChildren();
EntryCache::GetInstance()->Clear();
m_scanFolderOutputPrefixMap.clear();
m_devPath = devPath;
m_enginePath = enginePath;
// there is no "Gems" scan folder registered in db, create one manually
auto gemFolder = aznew FolderAssetBrowserEntry();
gemFolder->m_name = m_devPath + AZ_CORRECT_DATABASE_SEPARATOR + GEMS_FOLDER_NAME;
gemFolder->m_name = m_enginePath + AZ_CORRECT_DATABASE_SEPARATOR + GEMS_FOLDER_NAME;
gemFolder->m_displayName = GEMS_FOLDER_NAME;
gemFolder->m_isGemsFolder = true;
AddChild(gemFolder);
@@ -90,11 +89,6 @@ namespace AzToolsFramework
scanFolder->m_displayName = QString::fromUtf8(scanFolderDatabaseEntry.m_displayName.c_str());
EntryCache::GetInstance()->m_scanFolderIdMap[scanFolderDatabaseEntry.m_scanFolderID] = scanFolder;
}
if (!scanFolderDatabaseEntry.m_outputPrefix.empty())
{
m_scanFolderOutputPrefixMap[scanFolderDatabaseEntry.m_scanFolderID] = scanFolderDatabaseEntry.m_outputPrefix;
}
}
void RootAssetBrowserEntry::AddFile(const AssetDatabase::FileDatabaseEntry& fileDatabaseEntry)
@@ -132,7 +126,7 @@ namespace AzToolsFramework
return;
}
const char* filePath = GetScanFolderOutputAdjustedPath(fileDatabaseEntry, scanFolder);
const char* filePath = fileDatabaseEntry.m_fileName.c_str();
AssetBrowserEntry* file;
// file can be either folder or actual file
@@ -441,33 +435,5 @@ namespace AzToolsFramework
{
return MAKE_TKEY(ThumbnailKey);
}
const char* RootAssetBrowserEntry::GetScanFolderOutputAdjustedPath(const AssetDatabase::FileDatabaseEntry& fileDatabaseEntry, const AssetBrowserEntry* scanFolder)
{
Q_UNUSED(scanFolder);
const char* filePath = fileDatabaseEntry.m_fileName.c_str();
// adjust for output prefixes on scan folders (i.e. "editor")
auto itScanFolderOutputPrefix = m_scanFolderOutputPrefixMap.find(fileDatabaseEntry.m_scanFolderPK);
if (itScanFolderOutputPrefix != m_scanFolderOutputPrefixMap.end())
{
const AZStd::string& outputPrefix = itScanFolderOutputPrefix->second;
// Check if the input path starts with the output prefix.
// If it doesn't, something probably went seriously wrong,
// or someone is calling this function with an absolute path.
bool pathStartsWithPrefix = ((strncmp(filePath, outputPrefix.c_str(), outputPrefix.length()) == 0) && (fileDatabaseEntry.m_fileName.length() > (outputPrefix.length() + 1)));
AZ_Warning("Asset Browser", pathStartsWithPrefix, "Entry %s reported as under a ScanFolder (%s) with an 'output=%s', but the new entry does not begin with the output prefix! RootAssetBrowserEntry::GetScanFolderOutputAdjustedPath expects relative paths, not absolute; treating the input path as if it does not contain the ScanFolder output prefix.", filePath, scanFolder->m_name.c_str(), outputPrefix.c_str());
if (pathStartsWithPrefix)
{
// move the beginning ahead by the output prefix plus the separator
filePath += (outputPrefix.length() + 1);
}
}
return filePath;
}
} // namespace AssetBrowser
} // namespace AzToolsFramework
@@ -60,8 +60,8 @@ namespace AzToolsFramework
AssetEntryType GetEntryType() const override;
//! Update root node to new dev location
void Update(const char* devPath);
//! Update root node to new engine location
void Update(const char* enginePath);
void AddScanFolder(const AssetDatabase::ScanFolderDatabaseEntry& scanFolderDatabaseEntry);
void AddFile(const AssetDatabase::FileDatabaseEntry& fileDatabaseEntry);
@@ -82,17 +82,14 @@ namespace AzToolsFramework
private:
AZ_DISABLE_COPY_MOVE(RootAssetBrowserEntry);
AZStd::string m_devPath;
AZStd::unordered_map<AZ::s64, AZStd::string> m_scanFolderOutputPrefixMap;
AZStd::string 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);
//! Get the path for the fileDatabaseEntry, offset by the output prefix for the scan folder ancestor, if it's been specified and if it's appropriate
const char* GetScanFolderOutputAdjustedPath(const AssetDatabase::FileDatabaseEntry& fileDatabaseEntry, const AssetBrowserEntry* scanFolder);
bool m_isInitialUpdate = false;
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -80,4 +80,4 @@ namespace AzToolsFramework
AZ_DISABLE_COPY_MOVE(SourceAssetBrowserEntry);
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -47,4 +47,4 @@ namespace AzToolsFramework
QScopedPointer<Ui::EmptyPreviewerClass> m_ui;
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -23,4 +23,4 @@ namespace AzToolsFramework
}
}
#include <AssetBrowser/Previewer/moc_Previewer.cpp>
#include <AssetBrowser/Previewer/moc_Previewer.cpp>
@@ -44,4 +44,4 @@ namespace AzToolsFramework
using PreviewerRequestBus = AZ::EBus<PreviewerRequests>;
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -34,4 +34,4 @@ namespace AzToolsFramework
virtual const QString& GetName() const = 0;
};
} // namespace AssetBrowser
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -613,4 +613,4 @@ namespace AzToolsFramework
} // namespace AssetBrowser
} // namespace AzToolsFramework
#include "AssetBrowser/Search/moc_Filter.cpp"
#include "AssetBrowser/Search/moc_Filter.cpp"
@@ -12,4 +12,4 @@
</g>
</g>
</g>
</svg>
</svg>

Before

Width:  |  Height:  |  Size: 948 B

After

Width:  |  Height:  |  Size: 949 B

@@ -8,4 +8,4 @@
<rect id="Icon-Background" x="0" y="0" width="24" height="24"></rect>
<path d="M20.9694824,19.6604004 L16.3757324,15.0666504 C17.4069824,13.7541504 17.9694824,12.1604004 17.9694824,10.4729004 C17.9694824,6.34790039 14.5944824,2.97290039 10.4694824,2.97290039 C6.34448242,2.97290039 2.96948242,6.34790039 2.96948242,10.4729004 C2.96948242,14.5979004 6.34448242,17.9729004 10.4694824,17.9729004 C12.1569824,17.9729004 13.7507324,17.4104004 15.0632324,16.3791504 L19.6569824,20.9729004 L20.9694824,19.6604004 Z M10.4694824,16.0979004 C7.37573242,16.0979004 4.84448242,13.5666504 4.84448242,10.4729004 C4.84448242,7.37915039 7.37573242,4.84790039 10.4694824,4.84790039 C13.5632324,4.84790039 16.0944824,7.37915039 16.0944824,10.4729004 C16.0944824,13.5666504 13.5632324,16.0979004 10.4694824,16.0979004 Z" id="Shape" fill="#E9E9E9" fill-rule="nonzero"></path>
</g>
</svg>
</svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -10,8 +10,8 @@
*
*/
#include <AzCore/Utils/Utils.h>
#include <AzCore/Debug/Trace.h>
#include <AzCore/StringFunc/StringFunc.h>
#include <AzToolsFramework/AssetBrowser/Thumbnails/FolderThumbnail.h>
#include <AzFramework/API/ApplicationAPI.h>
#include <QPixmap>
@@ -50,11 +50,11 @@ namespace AzToolsFramework
//////////////////////////////////////////////////////////////////////////
// FolderThumbnail
//////////////////////////////////////////////////////////////////////////
static constexpr const char* FolderIconPath = "Editor/Icons/AssetBrowser/Folder_16.svg";
static constexpr const char* GemIconPath = "Editor/Icons/AssetBrowser/GemFolder_16.svg";
static constexpr const char* FolderIconPath = "Assets/Editor/Icons/AssetBrowser/Folder_16.svg";
static constexpr const char* GemIconPath = "Assets/Editor/Icons/AssetBrowser/GemFolder_16.svg";
FolderThumbnail::FolderThumbnail(SharedThumbnailKey key, int thumbnailSize)
: Thumbnail(key, thumbnailSize)
FolderThumbnail::FolderThumbnail(SharedThumbnailKey key)
: Thumbnail(key)
{}
void FolderThumbnail::LoadThread()
@@ -62,14 +62,10 @@ namespace AzToolsFramework
auto folderKey = azrtti_cast<const FolderThumbnailKey*>(m_key.data());
AZ_Assert(folderKey, "Incorrect key type, excpected FolderThumbnailKey");
const char* engineRoot = nullptr;
AzFramework::ApplicationRequests::Bus::BroadcastResult(engineRoot, &AzFramework::ApplicationRequests::GetEngineRoot);
AZ_Assert(engineRoot, "Engine Root not initialized");
const char* folderIcon = folderKey->IsGem() ? GemIconPath : FolderIconPath;
AZStd::string absoluteIconPath;
AZ::StringFunc::Path::Join(engineRoot, folderIcon, absoluteIconPath);
m_icon = QIcon(absoluteIconPath.c_str());
auto absoluteIconPath = AZ::IO::FixedMaxPath(AZ::Utils::GetEnginePath()) / folderIcon;
m_pixmap.load(absoluteIconPath.c_str());
m_state = m_pixmap.isNull() ? State::Failed : State::Ready;
}
//////////////////////////////////////////////////////////////////////////
@@ -47,7 +47,7 @@ namespace AzToolsFramework
{
Q_OBJECT
public:
FolderThumbnail(SharedThumbnailKey key, int thumbnailSize);
FolderThumbnail(SharedThumbnailKey key);
void LoadThread() override;
};
@@ -55,10 +55,10 @@ namespace AzToolsFramework
//////////////////////////////////////////////////////////////////////////
// ProductThumbnail
//////////////////////////////////////////////////////////////////////////
static const char* DEFAULT_PRODUCT_ICON_PATH = "Editor/Icons/AssetBrowser/DefaultProduct_16.svg";
static const char* DEFAULT_PRODUCT_ICON_PATH = "Icons/AssetBrowser/DefaultProduct_16.svg";
ProductThumbnail::ProductThumbnail(Thumbnailer::SharedThumbnailKey key, int thumbnailSize)
: Thumbnail(key, thumbnailSize)
ProductThumbnail::ProductThumbnail(Thumbnailer::SharedThumbnailKey key)
: Thumbnail(key)
{}
void ProductThumbnail::LoadThread()
@@ -96,12 +96,8 @@ namespace AzToolsFramework
iconPath = QString::fromUtf8(DEFAULT_PRODUCT_ICON_PATH);
}
m_icon = QIcon(iconPath);
if (m_icon.isNull())
{
m_state = State::Failed;
}
m_pixmap.load(iconPath);
m_state = m_pixmap.isNull() ? State::Failed : State::Ready;
}
//////////////////////////////////////////////////////////////////////////
@@ -44,7 +44,7 @@ namespace AzToolsFramework
{
Q_OBJECT
public:
ProductThumbnail(Thumbnailer::SharedThumbnailKey key, int thumbnailSize);
ProductThumbnail(Thumbnailer::SharedThumbnailKey key);
protected:
void LoadThread() override;
@@ -55,11 +55,11 @@ namespace AzToolsFramework
//////////////////////////////////////////////////////////////////////////
// SourceThumbnail
//////////////////////////////////////////////////////////////////////////
static constexpr const char* DefaultFileIconPath = "Editor/Icons/AssetBrowser/Default_16.svg";
static constexpr const char* DefaultFileIconPath = "Icons/AssetBrowser/Default_16.svg";
QMutex SourceThumbnail::m_mutex;
SourceThumbnail::SourceThumbnail(SharedThumbnailKey key, int thumbnailSize)
: Thumbnail(key, thumbnailSize)
SourceThumbnail::SourceThumbnail(SharedThumbnailKey key)
: Thumbnail(key)
{
}
@@ -124,7 +124,8 @@ namespace AzToolsFramework
iconPathToUse = iconPath.c_str();
}
m_icon = QIcon(iconPathToUse);
m_pixmap.load(iconPathToUse);
m_state = m_pixmap.isNull() ? State::Failed : State::Ready;
}
//////////////////////////////////////////////////////////////////////////
@@ -44,7 +44,7 @@ namespace AzToolsFramework
{
Q_OBJECT
public:
SourceThumbnail(SharedThumbnailKey key, int thumbnailSize);
SourceThumbnail(SharedThumbnailKey key);
protected:
void LoadThread() override;
@@ -139,8 +139,11 @@ namespace AzToolsFramework
}
else
{
QPixmap pixmap = thumbnail->GetPixmap(size);
painter->drawPixmap(point, pixmap.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
// Scaling and centering pixmap within bounds to preserve aspect ratio
const QPixmap pixmap = thumbnail->GetPixmap().scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
const QSize sizeDelta = size - pixmap.size();
const QPoint pointDelta = QPoint(sizeDelta.width() / 2, sizeDelta.height() / 2);
painter->drawPixmap(point + pointDelta, pixmap);
}
return m_iconSize;
}
@@ -17,7 +17,7 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/Utils.h>
#include <AzCore/std/parallel/thread.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Utils/Utils.h>
#include <AzFramework/Asset/AssetBundleManifest.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <AzFramework/API/ApplicationAPI.h>
@@ -250,7 +250,7 @@ namespace AzToolsFramework
AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
AZ_Assert(fileIO != nullptr, "AZ::IO::FileIOBase must be ready for use.\n");
AZStd::string bundleFilePath = assetBundleSettings.m_bundleFilePath;
AZ::IO::Path bundleFilePath = AZ::IO::Path(AZStd::string_view{ AZ::Utils::GetEnginePath() }) / assetBundleSettings.m_bundleFilePath;
AzFramework::PlatformId platformId = static_cast<AzFramework::PlatformId>(AzFramework::PlatformHelper::GetPlatformIndexFromName(assetBundleSettings.m_platform.c_str()));
@@ -259,22 +259,13 @@ namespace AzToolsFramework
return false;
}
const char* appRoot = nullptr;
AzFramework::ApplicationRequests::Bus::BroadcastResult(appRoot, &AzFramework::ApplicationRequests::GetAppRoot);
if (AzFramework::StringFunc::Path::IsRelative(bundleFilePath.c_str()))
{
AzFramework::StringFunc::Path::ConstructFull(appRoot, bundleFilePath.c_str(), bundleFilePath, true);
}
AZ::u64 maxSizeInBytes = static_cast<AZ::u64>(assetBundleSettings.m_maxBundleSizeInMB * NumOfBytesInMB);
AZ::u64 assetCatalogFileSizeBuffer = static_cast<AZ::u64>(AssetCatalogFileSizeBufferPercentage * assetBundleSettings.m_maxBundleSizeInMB * NumOfBytesInMB) / 100;
AZ::u64 bundleSize = 0;
AZ::u64 totalFileSize = 0;
int bundleIndex = 0;
AZStd::string bundleFullPath = bundleFilePath;
AZStd::string tempBundleFilePath = bundleFullPath + "_temp";
AZStd::string tempBundleFilePath = bundleFilePath.Native() + "_temp";
AZStd::vector<AZStd::string> dependentBundleNames;
AZStd::vector<AZStd::string> levelDirs;
@@ -301,7 +292,7 @@ namespace AzToolsFramework
if (fileIO->Exists(bundleFilePath.c_str()))
{
// This will delete both the parent bundle as well as all the dependent bundles mentioned in the manifest file of the parent bundle.
if (!DeleteBundleFiles(bundleFilePath))
if (!DeleteBundleFiles(bundleFilePath.Native()))
{
return false;
}
@@ -390,7 +381,7 @@ namespace AzToolsFramework
// we need to find a bundle which does not exist on disk;
bundleIndex++;
numOfTries--;
dependentBundleFileName = CreateAssetBundleFileName(bundleFilePath, bundleIndex);
dependentBundleFileName = CreateAssetBundleFileName(bundleFilePath.Native(), bundleIndex);
AzFramework::StringFunc::Path::ReplaceFullName(tempBundleFilePath, (dependentBundleFileName + tempBundleFileSuffix).c_str());
} while (numOfTries && fileIO->Exists(tempBundleFilePath.c_str()));
@@ -463,15 +454,7 @@ namespace AzToolsFramework
AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
AZStd::string assetFileInfoListPath = assetBundleSettings.m_assetFileInfoListPath;
const char* appRoot = nullptr;
AzFramework::ApplicationRequests::Bus::BroadcastResult(appRoot, &AzFramework::ApplicationRequests::GetAppRoot);
if (AzFramework::StringFunc::Path::IsRelative(assetFileInfoListPath.c_str()))
{
AzFramework::StringFunc::Path::ConstructFull(appRoot, assetFileInfoListPath.c_str(), assetFileInfoListPath, true);
}
AZ::IO::Path assetFileInfoListPath = AZ::IO::Path{ AZStd::string_view{AZ::Utils::GetEnginePath()} } / assetBundleSettings.m_assetFileInfoListPath;
if (!fileIO->Exists(assetFileInfoListPath.c_str()))
{
@@ -943,10 +943,8 @@ namespace AzToolsFramework
const char* scanFolder,
const char* displayName,
const char* portableKey,
const char* outputPrefix,
int isRoot)
: m_scanFolderID(scanFolderID)
, m_outputPrefix(outputPrefix)
, m_isRoot(isRoot)
{
if (scanFolder)
@@ -967,10 +965,8 @@ namespace AzToolsFramework
const char* scanFolder,
const char* displayName,
const char* portableKey,
const char* outputPrefix,
int isRoot)
: m_outputPrefix(outputPrefix)
, m_isRoot(isRoot)
: m_isRoot(isRoot)
{
if (scanFolder)
{
@@ -993,7 +989,6 @@ namespace AzToolsFramework
, m_scanFolder(other.m_scanFolder)
, m_displayName(other.m_displayName)
, m_portableKey(other.m_portableKey)
, m_outputPrefix(other.m_outputPrefix)
, m_isRoot(other.m_isRoot)
{
}
@@ -1011,7 +1006,6 @@ namespace AzToolsFramework
m_scanFolderID = other.m_scanFolderID;
m_displayName = AZStd::move(other.m_displayName);
m_portableKey = AZStd::move(other.m_portableKey);
m_outputPrefix = AZStd::move(other.m_outputPrefix);
m_isRoot = other.m_isRoot;
}
return *this;
@@ -1023,7 +1017,6 @@ namespace AzToolsFramework
m_scanFolderID = other.m_scanFolderID;
m_displayName = other.m_displayName;
m_portableKey = other.m_portableKey;
m_outputPrefix = other.m_outputPrefix;
m_isRoot = other.m_isRoot;
return *this;
}
@@ -1050,7 +1043,6 @@ namespace AzToolsFramework
MakeColumn("ScanFolder", m_scanFolder),
MakeColumn("DisplayName", m_displayName),
MakeColumn("PortableKey", m_portableKey),
MakeColumn("OutputPrefix", m_outputPrefix),
MakeColumn("IsRoot", m_isRoot)
);
}
@@ -68,6 +68,7 @@ namespace AzToolsFramework
AddedLastScanTimeField = 28,
AddedScanTimeSecondsSinceEpochField = 29,
ChangedSortFunctionFromQSortToStdStableSort = 30,
RemoveOutputPrefixFromScanFolders,
//Add all new versions before this
DatabaseVersionCount,
LatestVersion = DatabaseVersionCount - 1
@@ -99,12 +100,10 @@ namespace AzToolsFramework
const char* scanFolder,
const char* displayName,
const char* portableKey,
const char* outputPrefix,
int isRoot = 0);
ScanFolderDatabaseEntry(const char* scanFolder,
const char* displayName,
const char* portableKey,
const char* outputPrefix,
int isRoot = 0);
ScanFolderDatabaseEntry(const ScanFolderDatabaseEntry& other);
ScanFolderDatabaseEntry(ScanFolderDatabaseEntry&& other);
@@ -120,7 +119,6 @@ namespace AzToolsFramework
AZStd::string m_scanFolder; // the actual local computer path to that scan folder.
AZStd::string m_displayName; // a display name, blank means it should not show up in UIs
AZStd::string m_portableKey; // a key that uniquely identifies a scan folder so that we can recognize the same one in other databases/computer
AZStd::string m_outputPrefix;
int m_isRoot = 0;
};
@@ -52,8 +52,8 @@
#include <AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.h>
#include <AzToolsFramework/UI/EditorEntityUi/EditorEntityUiSystemComponent.h>
#include <AzToolsFramework/Thumbnails/ThumbnailerComponent.h>
#include <AzToolsFramework/Thumbnails/ThumbnailerNullComponent.h>
#include <AzToolsFramework/AssetBrowser/AssetBrowserComponent.h>
#include <AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.h>
#include <AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.h>
namespace AzToolsFramework
@@ -92,8 +92,8 @@ namespace AzToolsFramework
AzToolsFramework::AssetBundleComponent::CreateDescriptor(),
AzToolsFramework::SliceDependencyBrowserComponent::CreateDescriptor(),
AzToolsFramework::Thumbnailer::ThumbnailerComponent::CreateDescriptor(),
AzToolsFramework::Thumbnailer::ThumbnailerNullComponent::CreateDescriptor(),
AzToolsFramework::AssetBrowser::AssetBrowserComponent::CreateDescriptor(),
AzToolsFramework::MaterialBrowser::MaterialBrowserComponent::CreateDescriptor(),
AzToolsFramework::EditorInteractionSystemComponent::CreateDescriptor(),
AzToolsFramework::Components::EditorComponentAPIComponent::CreateDescriptor(),
AzToolsFramework::Components::EditorLevelComponentAPIComponent::CreateDescriptor(),
@@ -25,4 +25,4 @@ namespace AzToolsFramework
AzToolsFrameworkModule();
~AzToolsFrameworkModule() override = default;
};
}
}
@@ -72,4 +72,4 @@ namespace AzToolsFramework
m_componentModeBuilders, m_transition);
}
} // namespace ComponentModeFramework
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -50,4 +50,4 @@ namespace AzToolsFramework
Transition m_transition; ///< Entering/Leaving ComponentMode.
};
} // namespace ComponentModeFramework
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -105,4 +105,4 @@ namespace AzToolsFramework
return PivotHasTranslationOverride(pivotOverride) || PivotHasOrientationOverride(pivotOverride);
}
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -103,4 +103,4 @@ namespace AzToolsFramework
bool PivotHasOrientationOverride(AZ::u8 pivotOverride);
bool PivotHasTransformOverride(AZ::u8 pivotOverride);
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -32,4 +32,4 @@ namespace AzToolsFramework
{
m_boxEdit.UpdateManipulators();
}
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -40,4 +40,4 @@ namespace AzToolsFramework
private:
BoxViewportEdit m_boxEdit;
};
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -183,4 +183,4 @@ namespace AzToolsFramework
} // Debug
} // AzToolsFramework
#endif // AZ_ENABLE_TRACE_CONTEXT
#endif // AZ_ENABLE_TRACE_CONTEXT
@@ -20,4 +20,4 @@ namespace AzToolsFramework
return Print(buffer, size, stack, printUuids, startIndex);
}
} // Debug
} // AzToolsFramework
} // AzToolsFramework
@@ -49,6 +49,8 @@ namespace AzToolsFramework
/// Retrieve the Id of the editor entity context.
virtual AzFramework::EntityContextId GetEditorEntityContextId() = 0;
virtual AzFramework::EntityContext* GetEditorEntityContextInstance() = 0;
/// Creates an entity in the editor context.
/// \return the EntityId for the created Entity
virtual AZ::EntityId CreateNewEditorEntity(const char* name) = 0;
@@ -189,9 +189,6 @@ namespace AzToolsFramework
SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect();
EditorLegacyGameModeNotificationBus::Handler::BusConnect();
m_entityVisibilityBoundsUnionSystem.Connect();
}
//=========================================================================
@@ -199,8 +196,6 @@ namespace AzToolsFramework
//=========================================================================
void EditorEntityContextComponent::Deactivate()
{
m_entityVisibilityBoundsUnionSystem.Disconnect();
EditorLegacyGameModeNotificationBus::Handler::BusDisconnect();
SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusDisconnect();
@@ -77,6 +77,7 @@ namespace AzToolsFramework
//////////////////////////////////////////////////////////////////////////
// EditorEntityContextRequestBus
AzFramework::EntityContextId GetEditorEntityContextId() override { return GetContextId(); }
AzFramework::EntityContext* GetEditorEntityContextInstance() override { return this; }
void ResetEditorContext() override;
AZ::EntityId CreateNewEditorEntity(const char* name) override;
@@ -188,8 +189,6 @@ namespace AzToolsFramework
//! EditorEntityContextRequestBus::Events::AddRequiredComponents()
AZ::ComponentTypeList m_requiredEditorComponentTypes;
//! Edit time visibility management integrating entities with the IVisibilitySystem.
AzFramework::EntityVisibilityBoundsUnionSystem m_entityVisibilityBoundsUnionSystem;
bool m_isLegacySliceService;
UndoSystem::UndoCacheInterface* m_undoCacheInterface = nullptr;
@@ -37,4 +37,4 @@ namespace AzToolsFramework
using EditorEntityContextPickingRequestBus = AZ::EBus<EditorEntityContextPickingRequests>;
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -36,4 +36,4 @@ namespace AzToolsFramework
void OnSliceEntitiesLoaded(const AZStd::vector<AZ::Entity*>& entities) override;
////////////////////////////////////////////////////////////////////////
};
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -117,8 +117,6 @@ namespace AzToolsFramework
{
EditorEntityModel::EditorEntityModel()
{
AzFramework::ApplicationRequests::Bus::BroadcastResult(m_isPrefabEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled);
EntityCompositionNotificationBus::Handler::BusConnect();
EditorOnlyEntityComponentNotificationBus::Handler::BusConnect();
EditorEntityRuntimeActivationChangeNotificationBus::Handler::BusConnect();
@@ -565,7 +563,7 @@ namespace AzToolsFramework
{
//retrieve or add an entity entry to the table
//the entry must exist, even if not connected, so children and other data can be assigned
[[maybe_unused]] auto [it, inserted] = m_entityInfoTable.try_emplace(entityId, m_isPrefabEnabled);
[[maybe_unused]] auto [it, inserted] = m_entityInfoTable.try_emplace(entityId);
auto& entityInfo = it->second;
//the entity id defaults to invalid and must be set to match the requested id
@@ -882,11 +880,6 @@ namespace AzToolsFramework
}
}
EditorEntityModel::EditorEntityModelEntry::EditorEntityModelEntry(bool isPrefabEnabled)
: m_isPrefabEnabled(isPrefabEnabled)
{
}
EditorEntityModel::EditorEntityModelEntry::~EditorEntityModelEntry()
{
Disconnect();
@@ -1213,29 +1206,15 @@ namespace AzToolsFramework
auto childItr = m_childIndexCache.find(childId);
if (childItr != m_childIndexCache.end())
{
if (m_isPrefabEnabled)
{
// Take the last entry and move it into the removed spot instead of deleting the entry and having to move all
// following entries one step down.
AZ::EntityId backEntity = m_children.back();
m_children[childItr->second] = backEntity;
// Update cached index for the moved id to the new index.
m_childIndexCache[backEntity] = childItr->second;
// Now remove the deleted id from the children and cache.
m_childIndexCache.erase(childId);
m_children.erase(m_children.end() - 1);
}
else
{
m_children.erase(m_children.begin() + childItr->second);
// rebuild index cache for faster lookup
m_childIndexCache.clear();
for (auto childIdToCache : m_children)
{
m_childIndexCache[childIdToCache] = static_cast<AZ::u64>(m_childIndexCache.size());
}
}
// Take the last entry and move it into the removed spot instead of deleting the entry and having to move all
// following entries one step down.
AZ::EntityId backEntity = m_children.back();
m_children[childItr->second] = backEntity;
// Update cached index for the moved id to the new index.
m_childIndexCache[backEntity] = childItr->second;
// Now remove the deleted id from the children and cache.
m_childIndexCache.erase(childId);
m_children.erase(m_children.end() - 1);
}
}
@@ -171,7 +171,6 @@ namespace AzToolsFramework
, public PropertyEditorEntityChangeNotificationBus::Handler
{
public:
explicit EditorEntityModelEntry(bool isPrefabEnabled);
~EditorEntityModelEntry();
// Separately connect to EditorEntityInfoRequestBus and refresh Entity
@@ -336,7 +335,6 @@ namespace AzToolsFramework
bool m_visible = true;
bool m_locked = false;
bool m_connected = false;
bool m_isPrefabEnabled = false;
AZStd::string m_name;
AZStd::string m_sliceAssetName;
AZStd::unordered_map<AZ::EntityId, AZ::u64> m_childIndexCache;
@@ -375,6 +373,5 @@ namespace AzToolsFramework
AZ::EntityId m_postInstantiateBeforeEntity;
AZ::EntityId m_postInstantiateSliceParent;
bool m_gotInstantiateSliceDetails = false;
bool m_isPrefabEnabled = false;
};
}
@@ -25,4 +25,4 @@ namespace AzToolsFramework
virtual void RemoveFromChildrenWithOverrides(const EntityIdList& parentEntityIds, const AZ::EntityId& entityId) = 0;
};
using EditorEntityModelRequestBus = AZ::EBus<EditorEntityModelRequests>;
}
}
@@ -12,6 +12,7 @@
#pragma once
#include <AzCore/Asset/AssetCommon.h>
#include <AzCore/Component/Entity.h>
#include <AzCore/IO/GenericStreams.h>
#include <AzCore/std/smart_ptr/unique_ptr.h>
@@ -31,13 +32,25 @@ namespace AzToolsFramework
//! /param entities The entities to put under the new prefab.
//! /param nestedPrefabInstances The nested prefab instances to put under the new prefab.
//! /param filePath The filepath corresponding to the prefab file to be created.
//! /param instanceToParentUnder The instance under which the newly created prefab instance is parented under.
//! /param instanceToParentUnder The instance the newly created prefab instance is parented under.
//! /return The optional reference to the prefab created.
virtual Prefab::InstanceOptionalReference CreatePrefab(
const AZStd::vector<AZ::Entity*>& entities, AZStd::vector<AZStd::unique_ptr<Prefab::Instance>>&& nestedPrefabInstances,
AZ::IO::PathView filePath, Prefab::InstanceOptionalReference instanceToParentUnder = AZStd::nullopt) = 0;
//! Instantiate the prefab file provided.
//! /param filePath The filepath for the prefab file the instance should be created from.
//! /param instanceToParentUnder The instance the newly instantiated prefab instance is parented under.
//! /return The optional reference to the prefab instance.
virtual Prefab::InstanceOptionalReference InstantiatePrefab(
AZ::IO::PathView filePath, Prefab::InstanceOptionalReference instanceToParentUnder = AZStd::nullopt) = 0;
virtual Prefab::InstanceOptionalReference GetRootPrefabInstance() = 0;
//! Get all Assets generated by Prefab processing when entering Play-In Editor mode (Ctrl+G)
//! /return The vector of Assets generated by Prefab processing
virtual const AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& GetPlayInEditorAssetData() = 0;
virtual bool LoadFromStream(AZ::IO::GenericStream& stream, AZStd::string_view filename) = 0;
virtual bool SaveToStream(AZ::IO::GenericStream& stream, AZStd::string_view filename) = 0;
@@ -13,12 +13,14 @@
#include <AzCore/Component/Entity.h>
#include <AzCore/Component/TransformBus.h>
#include <AzCore/Script/ScriptSystemBus.h>
#include <AzCore/Serialization/Utils.h>
#include <AzFramework/API/ApplicationAPI.h>
#include <AzFramework/Entity/GameEntityContextBus.h>
#include <AzFramework/Spawnable/RootSpawnableInterface.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h>
#include <AzToolsFramework/Prefab/EditorPrefabComponent.h>
#include <AzToolsFramework/Prefab/Instance/InstanceEntityMapperInterface.h>
#include <AzToolsFramework/Prefab/Instance/Instance.h>
#include <AzToolsFramework/Prefab/PrefabDomUtils.h>
#include <AzToolsFramework/Prefab/PrefabLoader.h>
@@ -241,19 +243,6 @@ namespace AzToolsFramework
return false;
}
}
else
{
// The template is already loaded, this is the case of either saving as same name or different name(loaded from before).
// Update the template with the changes
AzToolsFramework::Prefab::PrefabDom dom;
bool success = AzToolsFramework::Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(*m_rootInstance, dom);
if (!success)
{
AZ_Error("Prefab", false, "Failed to convert current root instance into a DOM when saving file '%.*s'", AZ_STRING_ARG(filename));
return false;
}
m_prefabSystemComponent->UpdatePrefabTemplate(templateId, dom);
}
Prefab::TemplateId prevTemplateId = m_rootInstance->GetTemplateId();
m_rootInstance->SetTemplateId(templateId);
@@ -293,14 +282,26 @@ namespace AzToolsFramework
containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent());
HandleEntitiesAdded({containerEntity});
HandleEntitiesAdded(entities);
// Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded.
Prefab::PrefabDom serializedInstance;
if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(addedInstance, serializedInstance))
return addedInstance;
}
return AZStd::nullopt;
}
Prefab::InstanceOptionalReference PrefabEditorEntityOwnershipService::InstantiatePrefab(
AZ::IO::PathView filePath, Prefab::InstanceOptionalReference instanceToParentUnder)
{
AZStd::unique_ptr<Prefab::Instance> createdPrefabInstance = m_prefabSystemComponent->InstantiatePrefab(filePath);
if (createdPrefabInstance)
{
if (!instanceToParentUnder)
{
m_prefabSystemComponent->UpdatePrefabTemplate(addedInstance.GetTemplateId(), serializedInstance);
instanceToParentUnder = *m_rootInstance;
}
Prefab::Instance& addedInstance = instanceToParentUnder->get().AddInstance(AZStd::move(createdPrefabInstance));
HandleEntitiesAdded({addedInstance.m_containerEntity.get()});
return addedInstance;
}
@@ -313,6 +314,11 @@ namespace AzToolsFramework
return *m_rootInstance;
}
const AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& PrefabEditorEntityOwnershipService::GetPlayInEditorAssetData()
{
return m_playInEditorData.m_assets;
}
void PrefabEditorEntityOwnershipService::OnEntityRemoved(AZ::EntityId entityId)
{
AzFramework::SliceEntityRequestBus::MultiHandler::BusDisconnect(entityId);
@@ -334,6 +340,65 @@ namespace AzToolsFramework
m_validateEntitiesCallback = AZStd::move(validateEntitiesCallback);
}
void PrefabEditorEntityOwnershipService::LoadReferencedAssets(AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& referencedAssets)
{
// Start our loads on all assets by calling GetAsset from the AssetManager
for (AZ::Data::Asset<AZ::Data::AssetData>& asset : referencedAssets)
{
if (!asset.GetId().IsValid())
{
AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode");
continue;
}
const AZ::Data::AssetLoadBehavior loadBehavior = asset.GetAutoLoadBehavior();
if (loadBehavior == AZ::Data::AssetLoadBehavior::NoLoad)
{
continue;
}
AZ::Data::AssetId assetId = asset.GetId();
AZ::Data::AssetType assetType = asset.GetType();
asset = AZ::Data::AssetManager::Instance().GetAsset(assetId, assetType, loadBehavior);
if (!asset.GetId().IsValid())
{
AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode");
continue;
}
}
// For all Preload assets we block until they're ready
// We do this as a seperate pass so that we don't interrupt queuing up all other asset loads
for (AZ::Data::Asset<AZ::Data::AssetData>& asset : referencedAssets)
{
if (!asset.GetId().IsValid())
{
AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode");
continue;
}
const AZ::Data::AssetLoadBehavior loadBehavior = asset.GetAutoLoadBehavior();
if (loadBehavior != AZ::Data::AssetLoadBehavior::PreLoad)
{
continue;
}
asset.BlockUntilLoadComplete();
if (asset.IsError())
{
AZ_Error("Prefab", false, "Asset with id %s failed to preload while entering game mode",
asset.GetId().ToString<AZStd::string>().c_str());
continue;
}
}
}
void PrefabEditorEntityOwnershipService::StartPlayInEditor()
{
// This is a workaround until the replacement for GameEntityContext is done
@@ -373,16 +438,21 @@ namespace AzToolsFramework
rootSpawnableIndex = m_playInEditorData.m_assets.size();
}
LoadReferencedAssets(product.GetReferencedAssets());
AZ::Data::AssetInfo info;
info.m_assetId = product.GetAsset().GetId();
info.m_assetType = product.GetAssetType();
info.m_relativePath = product.GetId();
AZ::Data::AssetCatalogRequestBus::Broadcast(
&AZ::Data::AssetCatalogRequestBus::Events::RegisterAsset, product.GetAsset().GetId(), info);
&AZ::Data::AssetCatalogRequestBus::Events::RegisterAsset, info.m_assetId, info);
m_playInEditorData.m_assets.emplace_back(product.ReleaseAsset().release(), AZ::Data::AssetLoadBehavior::Default);
}
// make sure that PRE_NOTIFY assets get their notify before we activate, so that we can preserve the order of
// (load asset) -> (notify) -> (init) -> (activate)
AZ::Data::AssetManager::Instance().DispatchEvents();
if (rootSpawnableIndex != NoRootSpawnable)
{
@@ -191,11 +191,18 @@ namespace AzToolsFramework
const AZStd::vector<AZ::Entity*>& entities, AZStd::vector<AZStd::unique_ptr<Prefab::Instance>>&& nestedPrefabInstances,
AZ::IO::PathView filePath, Prefab::InstanceOptionalReference instanceToParentUnder) override;
Prefab::InstanceOptionalReference InstantiatePrefab(
AZ::IO::PathView filePath, Prefab::InstanceOptionalReference instanceToParentUnder) override;
Prefab::InstanceOptionalReference GetRootPrefabInstance() override;
const AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& GetPlayInEditorAssetData() override;
//////////////////////////////////////////////////////////////////////////
void OnEntityRemoved(AZ::EntityId entityId);
void LoadReferencedAssets(AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& referencedAssets);
OnEntitiesAddedCallback m_entitiesAddedCallback;
OnEntitiesRemovedCallback m_entitiesRemovedCallback;
ValidateEntitiesCallback m_validateEntitiesCallback;
@@ -85,14 +85,14 @@ namespace AzToolsFramework
// if we're snapping, only increment current radians when we know
// preSnapRadians is greater than the angleStep
if (snapping)
if (snapping && AZStd::abs(angleStepDegrees) > 0.0f)
{
actionInternal.m_current.m_preSnapRadians += rotationAngleRad * rotateSign;
const float angleStepRad = AZ::DegToRad(angleStepDegrees);
const float preSnapRotateSign = Sign(actionInternal.m_current.m_preSnapRadians);
// if we move more than angleStep in a frame, make sure we catch up
while (fabsf(actionInternal.m_current.m_preSnapRadians) >= angleStepRad)
while (AZStd::abs(actionInternal.m_current.m_preSnapRadians) >= angleStepRad)
{
actionInternal.m_current.m_radians += angleStepRad * preSnapRotateSign;
actionInternal.m_current.m_preSnapRadians -= angleStepRad * preSnapRotateSign;
@@ -48,4 +48,4 @@ namespace AzToolsFramework
/// Type to inherit to implement BoxManipulatorRequests
using BoxManipulatorRequestBus = AZ::EBus<BoxManipulatorRequests>;
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -127,8 +127,7 @@ namespace AzToolsFramework
ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult(
worldSurfacePosition, viewportId,
&ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain,
ViewportInteraction::QPointFromScreenPoint(
mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates));
mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates);
AZ::Transform worldFromLocal;
AZ::TransformBus::EventResult(worldFromLocal, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM);
@@ -402,10 +401,10 @@ namespace AzToolsFramework
vertexIndex, localVertex);
const AZ::Vector3 worldVertex = worldFromLocal.TransformPoint(AZ::AdaptVertexOut<Vertex>(localVertex));
const QPoint screenPosition = GetScreenPosition(viewportId, worldVertex);
const AzFramework::ScreenPoint screenPosition = GetScreenPosition(viewportId, worldVertex);
// check if a vertex is inside the box select region
if (editorBoxSelect.BoxRegion()->contains(screenPosition))
if (editorBoxSelect.BoxRegion()->contains(ViewportInteraction::QPointFromScreenPoint(screenPosition)))
{
// see if vertexIndex is in active selection
auto vertexIt = AZStd::find(
@@ -769,12 +768,12 @@ namespace AzToolsFramework
template<typename Vertex>
void EditorVertexSelectionBase<Vertex>::DisplayViewport2d(
const AzFramework::ViewportInfo& /*viewportInfo*/,
const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
m_editorBoxSelect.Display2d(debugDisplay);
m_editorBoxSelect.Display2d(viewportInfo, debugDisplay);
}
template<typename Vertex>
@@ -42,6 +42,7 @@ namespace AzToolsFramework
~LinearManipulator() = default;
/// A Manipulator must only be created and managed through a shared_ptr.
/// @note worldFromLocal should not contain scale.
static AZStd::shared_ptr<LinearManipulator> MakeShared(const AZ::Transform& worldFromLocal);
/// Unchanging data set once for the linear manipulator.
@@ -103,8 +103,7 @@ namespace AzToolsFramework
ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult(
worldSurfacePosition, interaction.m_interactionId.m_viewportId,
&ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain,
ViewportInteraction::QPointFromScreenPoint(
interaction.m_mousePick.m_screenCoordinates));
interaction.m_mousePick.m_screenCoordinates);
m_startInternal = CalculateManipulationDataStart(
worldFromLocalUniformScale, worldSurfacePosition, GetLocalPosition(),
@@ -129,8 +128,7 @@ namespace AzToolsFramework
ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult(
worldSurfacePosition, interaction.m_interactionId.m_viewportId,
&ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain,
ViewportInteraction::QPointFromScreenPoint(
interaction.m_mousePick.m_screenCoordinates));
interaction.m_mousePick.m_screenCoordinates);
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
@@ -150,8 +148,7 @@ namespace AzToolsFramework
ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult(
worldSurfacePosition, interaction.m_interactionId.m_viewportId,
&ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain,
ViewportInteraction::QPointFromScreenPoint(
interaction.m_mousePick.m_screenCoordinates));
interaction.m_mousePick.m_screenCoordinates);
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
@@ -1,43 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/EBus/EBus.h>
namespace AZ
{
namespace Data
{
struct AssetId;
}
}
namespace AzToolsFramework
{
namespace MaterialBrowser
{
class MaterialBrowserRequests
: public AZ::EBusTraits
{
public:
// Only a single handler is allowed
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single;
virtual bool HasRecord(const AZ::Data::AssetId& assetId) = 0;
virtual bool IsMultiMaterial(const AZ::Data::AssetId& assetId) = 0;
};
using MaterialBrowserRequestBus = AZ::EBus<MaterialBrowserRequests>;
} // namespace MaterialBrowser
} // namespace AzToolsFramework
@@ -1,66 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/Serialization/SerializeContext.h>
#include <AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.h>
#include <AzToolsFramework/Thumbnails/ThumbnailerBus.h>
#include <AzToolsFramework/AssetBrowser/Thumbnails/FolderThumbnail.h>
#include <AzToolsFramework/AssetBrowser/Thumbnails/SourceThumbnail.h>
#include <AzToolsFramework/MaterialBrowser/MaterialThumbnail.h>
#include <AzToolsFramework/Thumbnails/SourceControlThumbnail.h>
#include <QApplication>
AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 4251: 'QBrush::d': class 'QScopedPointer<QBrushData,QBrushDataPointerDeleter>' needs to have dll-interface to be used by clients of class 'QBrush'
#include <QStyle>
AZ_POP_DISABLE_WARNING
namespace AzToolsFramework
{
namespace MaterialBrowser
{
MaterialBrowserComponent::MaterialBrowserComponent()
{
}
void MaterialBrowserComponent::Activate()
{
using namespace Thumbnailer;
using namespace AssetBrowser;
const char* contextName = "MaterialBrowser";
int thumbnailSize = qApp->style()->pixelMetric(QStyle::PM_SmallIconSize);
ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterContext, contextName, thumbnailSize);
ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(FolderThumbnailCache), contextName);
ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(SourceThumbnailCache), contextName);
ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(MaterialThumbnailCache), contextName);
ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(SourceControlThumbnailCache), contextName);
}
void MaterialBrowserComponent::Deactivate()
{
}
void MaterialBrowserComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
if (serialize)
{
serialize->Class<MaterialBrowserComponent, AZ::Component>();
}
}
void MaterialBrowserComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
required.push_back(AZ_CRC("ThumbnailerService", 0x65422b97));
}
} // namespace MaterialBrowser
} // namespace AzToolsFramework
@@ -1,41 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/Component/Component.h>
namespace AzToolsFramework
{
namespace MaterialBrowser
{
//! MaterialBrowserComponent allows initialization of MaterialBrowser systems, such as thumbnails
class MaterialBrowserComponent
: public AZ::Component
{
public:
AZ_COMPONENT(MaterialBrowserComponent, "{121F3F3B-2412-490D-9E3E-C205C677F476}")
MaterialBrowserComponent();
virtual ~MaterialBrowserComponent() = default;
//////////////////////////////////////////////////////////////////////////
// AZ::Component
//////////////////////////////////////////////////////////////////////////
void Activate() override;
void Deactivate() override;
static void Reflect(AZ::ReflectContext* context);
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required);
};
} // namespace MaterialBrowser
} // namespace AzToolsFramework
@@ -1,66 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzToolsFramework/MaterialBrowser/MaterialThumbnail.h>
#include <QPixmap>
namespace AzToolsFramework
{
namespace MaterialBrowser
{
static constexpr const char* SimpleMaterialIconPath = ":/MaterialBrowser/images/material_04.png";
static constexpr const char* MultiMaterialIconPath = ":/MaterialBrowser/images/material_06.png";
//////////////////////////////////////////////////////////////////////////
// MaterialThumbnail
//////////////////////////////////////////////////////////////////////////
MaterialThumbnail::MaterialThumbnail(Thumbnailer::SharedThumbnailKey key, int thumbnailSize)
: Thumbnail(key, thumbnailSize)
{
auto productKey = azrtti_cast<const AzToolsFramework::AssetBrowser::ProductThumbnailKey*>(m_key.data());
AZ_Assert(productKey, "Incorrect key type, excpected ProductThumbnailKey");
bool multiMat = false;
MaterialBrowserRequestBus::BroadcastResult(multiMat, &MaterialBrowserRequests::IsMultiMaterial, productKey->GetAssetId());
QString iconPath = multiMat ? MultiMaterialIconPath : SimpleMaterialIconPath;
m_pixmap = QPixmap(iconPath).scaled(m_thumbnailSize, m_thumbnailSize, Qt::KeepAspectRatio);
}
//////////////////////////////////////////////////////////////////////////
// MaterialThumbnailCache
//////////////////////////////////////////////////////////////////////////
MaterialThumbnailCache::MaterialThumbnailCache()
: ThumbnailCache<MaterialThumbnail, MaterialKeyHash, MaterialKeyEqual>() {}
MaterialThumbnailCache::~MaterialThumbnailCache() = default;
int MaterialThumbnailCache::GetPriority() const
{
return 1;
}
const char* MaterialThumbnailCache::GetProviderName() const
{
return ProviderName;
}
bool MaterialThumbnailCache::IsSupportedThumbnail(Thumbnailer::SharedThumbnailKey key) const
{
return azrtti_istypeof<const AzToolsFramework::AssetBrowser::ProductThumbnailKey*>(key.data());
}
} // namespace MaterialBrowser
} // namespace AzToolsFramework
#include "MaterialBrowser/moc_MaterialThumbnail.cpp"
@@ -1,86 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#if !defined(Q_MOC_RUN)
#include <AzToolsFramework/Thumbnails/Thumbnail.h>
#include <AzToolsFramework/AssetBrowser/Thumbnails/ProductThumbnail.h>
#include <AzToolsFramework/MaterialBrowser/MaterialBrowserBus.h>
#endif
namespace AzToolsFramework
{
namespace MaterialBrowser
{
//! Material Browser uses only 2 thumbnails: simple and multimaterial
class MaterialThumbnail
: public Thumbnailer::Thumbnail
{
Q_OBJECT
public:
MaterialThumbnail(Thumbnailer::SharedThumbnailKey key, int thumbnailSize);
};
namespace
{
class MaterialKeyHash
{
public:
size_t operator()(const Thumbnailer::SharedThumbnailKey& /*val*/) const
{
return 0; // there is only 2 thumbnails in this cache
}
};
class MaterialKeyEqual
{
public:
bool operator()(const Thumbnailer::SharedThumbnailKey& val1, const Thumbnailer::SharedThumbnailKey& val2) const
{
auto productThumbnailKey1 = azrtti_cast<const AzToolsFramework::AssetBrowser::ProductThumbnailKey*>(val1.data());
auto productThumbnailKey2 = azrtti_cast<const AzToolsFramework::AssetBrowser::ProductThumbnailKey*>(val2.data());
if (!productThumbnailKey1 || !productThumbnailKey2)
{
return false;
}
// check whether keys point to single or multimaterial asset type
bool multiMat1 = false;
bool multiMat2 = false;
MaterialBrowserRequestBus::BroadcastResult(multiMat1, &MaterialBrowserRequests::IsMultiMaterial, productThumbnailKey1->GetAssetId());
MaterialBrowserRequestBus::BroadcastResult(multiMat2, &MaterialBrowserRequests::IsMultiMaterial, productThumbnailKey2->GetAssetId());
return multiMat1 == multiMat2;
}
};
}
//! MaterialBrowserEntry thumbnails
class MaterialThumbnailCache
: public Thumbnailer::ThumbnailCache<MaterialThumbnail, MaterialKeyHash, MaterialKeyEqual>
{
public:
MaterialThumbnailCache();
~MaterialThumbnailCache() override;
int GetPriority() const override;
const char* GetProviderName() const override;
static constexpr const char* ProviderName = "CryMaterial Thumbnails";
protected:
bool IsSupportedThumbnail(Thumbnailer::SharedThumbnailKey key) const override;
};
} // namespace MaterialBrowser
} // namespace AzToolsFramework
@@ -216,4 +216,4 @@ namespace AzToolsFramework
///< intersecting point.
};
} // namespace Picking
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -52,4 +52,4 @@ namespace AzToolsFramework
RegisteredBoundId m_nextBoundId = RegisteredBoundId(1); ///< Next bound id to use when a bound is registered.
};
} // namespace Picking
} // namespace AzToolsFramework
} // namespace AzToolsFramework
@@ -16,7 +16,6 @@
#include <AzCore/Serialization/EditContext.h>
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
#include <AzToolsFramework/UI/EditorEntityUi/EditorEntityUiInterface.h>
#include <AzToolsFramework/UI/Outliner/EntityOutlinerWidgetInterface.h>
#include <AzToolsFramework/UI/Prefab/PrefabIntegrationBus.h>
namespace AzToolsFramework
@@ -80,6 +80,12 @@ namespace AzToolsFramework
void Instance::SetTemplateId(const TemplateId& templateId)
{
// If we aren't changing the template Id, there's no need to unregister / re-register
if (templateId == m_templateId)
{
return;
}
// If this instance's templateId is valid, we should be able to unregister this instance from
// Template to Instance mapping successfully.
if (m_templateId != InvalidTemplateId &&
@@ -200,7 +200,7 @@ namespace AzToolsFramework
}
return context.Report(result,
result.GetProcessing() == JSR::Processing::Completed ? "Succesfully loaded instance information for prefab." :
result.GetProcessing() == JSR::Processing::Completed ? "Successfully loaded instance information for prefab." :
"Failed to load instance information for prefab");
}
@@ -270,7 +270,7 @@ namespace AzToolsFramework
return parentInstance;
}
void InstanceToTemplatePropagator::AddPatchesToLink(PrefabDom& patches, Link& link)
void InstanceToTemplatePropagator::AddPatchesToLink(const PrefabDom& patches, Link& link)
{
PrefabDom& linkDom = link.GetLinkDom();
PrefabDomValueReference linkPatchesReference =
@@ -279,7 +279,14 @@ namespace AzToolsFramework
// This logic only covers addition of patches. If patches already exists, the given list of patches must be appended to them.
if (!linkPatchesReference.has_value())
{
linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patches, linkDom.GetAllocator());
/*
If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the
linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to
associate them with the linkDom's allocator.
*/
PrefabDom patchesCopy;
patchesCopy.CopyFrom(patches, linkDom.GetAllocator());
linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patchesCopy, linkDom.GetAllocator());
}
}
}
@@ -41,7 +41,7 @@ namespace AzToolsFramework
void ApplyPatchesToInstance(const AZ::EntityId& entityId, PrefabDom& patches, const Instance& instanceToAddPatches) override;
void AddPatchesToLink(PrefabDom& patches, Link& link);
void AddPatchesToLink(const PrefabDom& patches, Link& link);
private:
@@ -21,9 +21,9 @@
#include <AzToolsFramework/Prefab/Instance/TemplateInstanceMapperInterface.h>
#include <AzToolsFramework/Prefab/PrefabDomUtils.h>
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
#include <AzToolsFramework/Prefab/PrefabPublicNotificationBus.h>
#include <AzToolsFramework/Prefab/PrefabSystemComponentInterface.h>
#include <AzToolsFramework/Prefab/Template/Template.h>
#include <AzToolsFramework/UI/Outliner/EntityOutlinerWidgetInterface.h>
namespace AzToolsFramework
{
@@ -72,10 +72,18 @@ namespace AzToolsFramework
for (auto instance : findInstancesResult->get())
{
m_instancesUpdateQueue.emplace(instance);
m_instancesUpdateQueue.emplace_back(instance);
}
}
void InstanceUpdateExecutor::RemoveTemplateInstanceFromQueue(const Instance* instance)
{
AZStd::erase_if(m_instancesUpdateQueue, [instance](Instance* entry)
{
return entry == instance;
});
}
bool InstanceUpdateExecutor::UpdateTemplateInstancesInQueue()
{
bool isUpdateSuccessful = true;
@@ -90,20 +98,23 @@ namespace AzToolsFramework
if (instanceCountToUpdateInBatch > 0)
{
// Notify Propagation has begun
PrefabPublicNotificationBus::Broadcast(&PrefabPublicNotifications::OnPrefabInstancePropagationBegin);
EntityIdList selectedEntityIds;
ToolsApplicationRequestBus::BroadcastResult(selectedEntityIds, &ToolsApplicationRequests::GetSelectedEntities);
ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, EntityIdList());
// Disable the Outliner to avoid showing the propagation steps
EntityOutlinerWidgetInterface* entityOutlinerWidgetInterface = AZ::Interface<EntityOutlinerWidgetInterface>::Get();
if (entityOutlinerWidgetInterface)
{
entityOutlinerWidgetInterface->SetUpdatesEnabled(false);
}
for (int i = 0; i < instanceCountToUpdateInBatch; ++i)
// Process all instances in the queue, capped to the batch size.
// Even though we potentially initialized the batch size to the queue, it's possible for the queue size to shrink
// during instance processing if the instance gets deleted and it was queued multiple times. To handle this, we
// make sure to end the loop once the queue is empty, regardless of what the initial size was.
for (int i = 0; (i < instanceCountToUpdateInBatch) && !m_instancesUpdateQueue.empty(); ++i)
{
Instance* instanceToUpdate = m_instancesUpdateQueue.front();
m_instancesUpdateQueue.pop_front();
AZ_Assert(instanceToUpdate != nullptr, "Invalid instance on update queue.");
TemplateId instanceTemplateId = instanceToUpdate->GetTemplateId();
if (currentTemplateId != instanceTemplateId)
{
@@ -119,19 +130,21 @@ namespace AzToolsFramework
// Remove the instance from update queue if its corresponding template couldn't be found
isUpdateSuccessful = false;
m_instancesUpdateQueue.pop();
continue;
}
}
auto findInstancesResult = m_templateInstanceMapperInterface->FindInstancesOwnedByTemplate(instanceTemplateId)->get();
auto findInstancesResult = m_templateInstanceMapperInterface->FindInstancesOwnedByTemplate(instanceTemplateId);
AZ_Assert(
findInstancesResult.has_value(), "Prefab Instances corresponding to template with id %llu couldn't be found.",
instanceTemplateId);
if (findInstancesResult.find(instanceToUpdate) == findInstancesResult.end())
if (findInstancesResult == AZStd::nullopt ||
findInstancesResult->get().find(instanceToUpdate) == findInstancesResult->get().end())
{
// Since nested instances get reconstructed during propagation, remove any nested instance that no longer
// maps to a template.
isUpdateSuccessful = false;
m_instancesUpdateQueue.pop();
continue;
}
@@ -152,8 +165,6 @@ namespace AzToolsFramework
isUpdateSuccessful = false;
}
m_instancesUpdateQueue.pop();
}
for (auto entityIdIterator = selectedEntityIds.begin(); entityIdIterator != selectedEntityIds.end(); entityIdIterator++)
@@ -168,18 +179,8 @@ namespace AzToolsFramework
}
ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, selectedEntityIds);
// Enable the Outliner
if (entityOutlinerWidgetInterface)
{
entityOutlinerWidgetInterface->SetUpdatesEnabled(true);
auto prefabPublicInterface = AZ::Interface<PrefabPublicInterface>::Get();
if (prefabPublicInterface)
{
AZ::EntityId rootEntityId = prefabPublicInterface->GetLevelInstanceContainerEntityId();
entityOutlinerWidgetInterface->ExpandEntityChildren(rootEntityId);
}
}
// Notify Propagation has ended
PrefabPublicNotificationBus::Broadcast(&PrefabPublicNotifications::OnPrefabInstancePropagationEnd);
}
m_updatingTemplateInstancesInQueue = false;
@@ -14,7 +14,7 @@
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/Serialization/Json/JsonSerialization.h>
#include <AzCore/std/containers/queue.h>
#include <AzCore/std/containers/deque.h>
#include <AzToolsFramework/Prefab/Instance/InstanceUpdateExecutorInterface.h>
#include <AzToolsFramework/Prefab/PrefabIdTypes.h>
@@ -37,6 +37,7 @@ namespace AzToolsFramework
void AddTemplateInstancesToQueue(TemplateId instanceTemplateId) override;
bool UpdateTemplateInstancesInQueue() override;
virtual void RemoveTemplateInstanceFromQueue(const Instance* instance) override;
void RegisterInstanceUpdateExecutorInterface();
void UnregisterInstanceUpdateExecutorInterface();
@@ -45,7 +46,7 @@ namespace AzToolsFramework
PrefabSystemComponentInterface* m_prefabSystemComponentInterface = nullptr;
TemplateInstanceMapperInterface* m_templateInstanceMapperInterface = nullptr;
int m_instanceCountToUpdateInBatch = 0;
AZStd::queue<Instance*> m_instancesUpdateQueue;
AZStd::deque<Instance*> m_instancesUpdateQueue;
bool m_updatingTemplateInstancesInQueue { false };
};
}
@@ -31,6 +31,9 @@ namespace AzToolsFramework
// Update Instances in the waiting queue.
virtual bool UpdateTemplateInstancesInQueue() = 0;
// Remove an Instance from the waiting queue.
virtual void RemoveTemplateInstanceFromQueue(const Instance* instance) = 0;
};
}
}
@@ -14,6 +14,7 @@
#include <AzCore/Interface/Interface.h>
#include <AzToolsFramework/Prefab/Instance/Instance.h>
#include <AzToolsFramework/Prefab/Instance/InstanceUpdateExecutorInterface.h>
namespace AzToolsFramework
{
@@ -71,6 +72,12 @@ namespace AzToolsFramework
bool TemplateInstanceMapper::UnregisterInstance(Instance& instance)
{
// The InstanceUpdateExecutor queries the TemplateInstanceMapper for a list of instances related to a template.
// Consequently, if an instance gets unregistered for a template, we need to notify the InstanceUpdateExecutor as well
// so that it clears any internal associations that it might have in its queue.
AZ_Assert(AZ::Interface<InstanceUpdateExecutorInterface>::Get() != nullptr, "InstanceUpdateExecutor doesn't exist");
AZ::Interface<InstanceUpdateExecutorInterface>::Get()->RemoveTemplateInstanceFromQueue(&instance);
auto found = m_templateIdToInstancesMap.find(instance.GetTemplateId());
return found != m_templateIdToInstancesMap.end() &&
found->second.erase(&instance) != 0;
@@ -108,11 +108,9 @@ namespace AzToolsFramework
m_targetTemplateId = id;
}
void Link::SetTemplatePatches(const PrefabDomValue& patches)
void Link::SetLinkDom(const PrefabDomValue& linkDom)
{
PrefabDom newPatches;
newPatches.CopyFrom(patches, newPatches.GetAllocator());
m_linkDom.Swap(newPatches);
m_linkDom.CopyFrom(linkDom, m_linkDom.GetAllocator());
}
void Link::SetInstanceName(const char* instanceName)
@@ -184,16 +182,16 @@ namespace AzToolsFramework
else
{
AZ::JsonSerializationResult::ResultCode applyPatchResult = AZ::JsonSerialization::ApplyPatch(
linkedInstanceDom,
sourceTemplateDomCopy,
targetTemplatePrefabDom.GetAllocator(),
sourceTemplatePrefabDom,
patchesReference->get(),
AZ::JsonMergeApproach::JsonPatch);
linkedInstanceDom.CopyFrom(sourceTemplateDomCopy, targetTemplatePrefabDom.GetAllocator());
if (applyPatchResult.GetProcessing() != AZ::JsonSerializationResult::Processing::Completed)
{
AZ_Error("Prefab", false,
"Link::UpdateTarget - "
"ApplyPatches failed for Prefab DOM from source Template '%u' and target Template '%u'.",
AZ_Error(
"Prefab", false,
"Link::UpdateTarget - ApplyPatches failed for Prefab DOM from source Template '%u' and target Template '%u'.",
m_sourceTemplateId, m_targetTemplateId);
return false;
}
@@ -230,6 +228,10 @@ namespace AzToolsFramework
AZ_Assert(instanceDom.IsObject(), "Link Id '%u' cannot be added because the DOM of the instance is not an object.", m_id);
instanceDom.AddMember(rapidjson::StringRef(PrefabDomUtils::LinkIdName), rapidjson::Value().SetUint64(m_id), allocator);
}
else
{
linkIdReference->get().SetUint64(m_id);
}
}
} // namespace Prefab
@@ -47,7 +47,7 @@ namespace AzToolsFramework
void SetSourceTemplateId(TemplateId id);
void SetTargetTemplateId(TemplateId id);
void SetTemplatePatches(const PrefabDomValue& patches);
void SetLinkDom(const PrefabDomValue& linkDom);
void SetInstanceName(const char* instanceName);
bool IsValid() const;
@@ -27,6 +27,7 @@ namespace AzToolsFramework
using PrefabDomList = AZStd::vector<PrefabDom>;
using PrefabDomReference = AZStd::optional<AZStd::reference_wrapper<PrefabDom>>;
using PrefabDomConstReference = AZStd::optional<AZStd::reference_wrapper<const PrefabDom>>;
using PrefabDomValueReference = AZStd::optional<AZStd::reference_wrapper<PrefabDomValue>>;
using PrefabDomValueConstReference = AZStd::optional<AZStd::reference_wrapper<const PrefabDomValue>>;
@@ -11,8 +11,10 @@
*/
#include <AzCore/Asset/AssetManager.h>
#include <AzCore/Asset/AssetJsonSerializer.h>
#include <AzCore/JSON/prettywriter.h>
#include <AzCore/Serialization/Json/JsonSerialization.h>
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
#include <AzToolsFramework/Prefab/PrefabDomUtils.h>
#include <AzToolsFramework/Prefab/Instance/Instance.h>
@@ -115,6 +117,48 @@ namespace AzToolsFramework
return true;
}
bool LoadInstanceFromPrefabDom(
Instance& instance, const PrefabDom& prefabDom, AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& referencedAssets, LoadInstanceFlags 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
// is avoided.
AZ::Data::AssetManager::Instance().SuspendAssetRelease();
InstanceEntityIdMapper entityIdMapper;
entityIdMapper.SetLoadingInstance(instance);
if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId)
{
entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random);
}
AZ::JsonDeserializerSettings settings;
// The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is
// specific for the InstanceEntityIdMapper and once for the generic JsonEntityIdMapper. Because the Json Serializer's meta
// data has strict typing and doesn't look for inheritance both have to be explicitly added so they're found both locations.
settings.m_metadata.Add(static_cast<AZ::JsonEntityIdSerializer::JsonEntityIdMapper*>(&entityIdMapper));
settings.m_metadata.Add(&entityIdMapper);
settings.m_metadata.Create<AZ::Data::SerializedAssetTracker>();
AZ::JsonSerializationResult::ResultCode result =
AZ::JsonSerialization::Load(instance, prefabDom, settings);
AZ::Data::AssetManager::Instance().ResumeAssetRelease();
if (result.GetProcessing() == AZ::JsonSerializationResult::Processing::Halted)
{
AZ_Error("Prefab", false,
"Failed to de-serialize Prefab Instance from Prefab DOM. "
"Unable to proceed.");
return false;
}
AZ::Data::SerializedAssetTracker* assetTracker = settings.m_metadata.Find<AZ::Data::SerializedAssetTracker>();
referencedAssets = AZStd::move(assetTracker->GetTrackedAssets());
return true;
}
bool LoadInstanceFromPrefabDom(
Instance& instance, Instance::EntityList& newlyAddedEntities, const PrefabDom& prefabDom, LoadInstanceFlags flags)
{
@@ -155,6 +199,43 @@ namespace AzToolsFramework
return true;
}
void GetTemplateSourcePaths(const PrefabDomValue& prefabDom, AZStd::unordered_set<AZ::IO::Path>& templateSourcePaths)
{
PrefabDomValueConstReference findSourceResult = PrefabDomUtils::FindPrefabDomValue(prefabDom, PrefabDomUtils::SourceName);
if (!findSourceResult.has_value() || !(findSourceResult->get().IsString()) ||
findSourceResult->get().GetStringLength() == 0)
{
AZ_Assert(
false,
"PrefabDomUtils::GetDependentTemplatePath - Source value of prefab in the provided DOM is not a valid string.");
return;
}
templateSourcePaths.emplace(findSourceResult->get().GetString());
PrefabDomValueConstReference instancesReference = GetInstancesValue(prefabDom);
if (instancesReference.has_value())
{
const PrefabDomValue& instances = instancesReference->get();
for (PrefabDomValue::ConstMemberIterator instanceIterator = instances.MemberBegin();
instanceIterator != instances.MemberEnd(); ++instanceIterator)
{
GetTemplateSourcePaths(instanceIterator->value, templateSourcePaths);
}
}
}
PrefabDomValueConstReference GetInstancesValue(const PrefabDomValue& prefabDom)
{
PrefabDomValueConstReference findInstancesResult = FindPrefabDomValue(prefabDom, PrefabDomUtils::InstancesName);
if (!findInstancesResult.has_value() || !(findInstancesResult->get().IsObject()))
{
return AZStd::nullopt;
}
return findInstancesResult->get();
}
void PrintPrefabDomValue(
[[maybe_unused]] const AZStd::string_view printMessage,
[[maybe_unused]] const PrefabDomValue& prefabDomValue)
@@ -13,6 +13,7 @@
#pragma once
#include <AzCore/std/optional.h>
#include <AzCore/Asset/AssetCommon.h>
#include <AzToolsFramework/Prefab/Instance/Instance.h>
#include <AzToolsFramework/Prefab/PrefabDomTypes.h>
@@ -42,7 +43,7 @@ namespace AzToolsFramework
/**
* Stores a valid Prefab Instance within a Prefab Dom. Useful for generating Templates
* @param instance The instance to store
* @param prefabDom the prefabDom that will be used to store the Instance data
* @param prefabDom The prefabDom that will be used to store the Instance data
* @return bool on whether the operation succeeded
*/
bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom);
@@ -60,20 +61,32 @@ namespace AzToolsFramework
/**
* Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances.
* @param instance The Instance to load.
* @param prefabDom the prefabDom that will be used to load the Instance data.
* @param shouldClearContainers whether to clear containers in Instance while loading.
* @param prefabDom The prefabDom that will be used to load the Instance data.
* @param shouldClearContainers Whether to clear containers in Instance while loading.
* @return bool on whether the operation succeeded.
*/
bool LoadInstanceFromPrefabDom(
Instance& instance, const PrefabDom& prefabDom, LoadInstanceFlags flags = LoadInstanceFlags::None);
/**
* Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances.
* @param instance The Instance to load.
* @param referencedAssets AZ::Assets discovered during json load are added to this list
* @param prefabDom The prefabDom that will be used to load the Instance data.
* @param shouldClearContainers Whether to clear containers in Instance while loading.
* @return bool on whether the operation succeeded.
*/
bool LoadInstanceFromPrefabDom(
Instance& instance, const PrefabDom& prefabDom, AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& referencedAssets,
LoadInstanceFlags flags = LoadInstanceFlags::None);
/**
* Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances.
* @param instance The Instance to load.
* @param newlyAddedEntities The new instances added during deserializing the instance. These are the entities found
* in the prefabDom.
* @param prefabDom the prefabDom that will be used to load the Instance data.
* @param shouldClearContainers whether to clear containers in Instance while loading.
* @param prefabDom The prefabDom that will be used to load the Instance data.
* @param shouldClearContainers Whether to clear containers in Instance while loading.
* @return bool on whether the operation succeeded.
*/
bool LoadInstanceFromPrefabDom(
@@ -87,6 +100,20 @@ namespace AzToolsFramework
.Append(instanceName);
};
/**
* Gets a set of all the template source paths in the given dom.
* @param prefabDom The DOM to get the template source paths from.
* @param[out] templateSourcePaths The set of template source paths to populate.
*/
void GetTemplateSourcePaths(const PrefabDomValue& prefabDom, AZStd::unordered_set<AZ::IO::Path>& templateSourcePaths);
/**
* Gets the instances DOM value from the given prefab DOM.
*
* @return the instances DOM value or AZStd::nullopt if it instances can't be found.
*/
PrefabDomValueConstReference GetInstancesValue(const PrefabDomValue& prefabDom);
/**
* Prints the contents of the given prefab DOM value to the debug output console in a readable format.
* @param printMessage The message that will be printed before printing the PrefabDomValue
@@ -89,16 +89,14 @@ namespace AzToolsFramework
if (!RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, commonRootEntityOwningInstance->get(), entities, instances))
{
return AZ::Failure(
AZStd::string("Could not create a new prefab out of the entities provided - entities do not share a common root."));
AZStd::string("Could not create a new prefab out of the entities provided - invalid selection."));
}
// When we create a prefab with other prefab instances, we have to remove the existing links between the source and
// target templates of the other instances.
for (auto& nestedInstance : instances)
{
PrefabUndoHelpers::RemoveLink(
nestedInstance->GetTemplateId(), commonRootEntityOwningInstance->get().GetTemplateId(),
nestedInstance->GetInstanceAlias(), nestedInstance->GetLinkId(), undoBatch.GetUndoBatch());
RemoveLink(nestedInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch());
}
PrefabUndoHelpers::UpdatePrefabInstance(
@@ -124,27 +122,67 @@ namespace AzToolsFramework
AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId();
// Parent the non-container top level entities to the container entity.
// Parenting the top level container entities will be done during the creation of links.
for (AZ::Entity* topLevelEntity : topLevelEntities)
{
if (!IsInstanceContainerEntity(topLevelEntity->GetId()))
{
AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId);
}
}
// Update the template of the instance since the entities are modified since the template creation.
Prefab::PrefabDom serializedInstance;
if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(instanceToCreate->get(), serializedInstance))
{
m_prefabSystemComponentInterface->UpdatePrefabTemplate(instanceToCreate->get().GetTemplateId(), serializedInstance);
}
instanceToCreate->get().GetNestedInstances([&](AZStd::unique_ptr<Instance>& nestedInstance) {
AZ_Assert(nestedInstance, "Invalid nested instance found in the new prefab created.");
EntityOptionalReference nestedInstanceContainerEntity = nestedInstance->GetContainerEntity();
AZ_Assert(
nestedInstanceContainerEntity, "Invalid container entity found for the nested instance used in prefab creation.");
AZ::EntityId parentId;
AZ::TransformBus::EventResult(
parentId, nestedInstanceContainerEntity->get().GetId(), &AZ::TransformBus::Events::GetParentId);
auto entityIterator = AZStd::find_if(
entities.begin(), entities.end(), [parentId](AZ::Entity* entity) { return entity->GetId() == parentId; });
// If the previous parent entity of the nested instance is not part of the entities of the newly created prefab,
// then set the parent of the nested prefab as the container entity of the newly created prefab.
if (entityIterator == entities.end())
{
parentId = containerEntityId;
}
// These link creations shouldn't be undone because that would put the template in a non-usable state if a user
// chooses to instantiate the template after undoing the creation.
CreateLink(
{&nestedInstanceContainerEntity->get()}, *nestedInstance, instanceToCreate->get().GetTemplateId(),
undoBatch.GetUndoBatch(), containerEntityId);
undoBatch.GetUndoBatch(), parentId, false);
});
// Create a link between the templates of the newly created instance and the instance it's being parented under.
CreateLink(
topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(),
commonRootEntityId);
topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(),
undoBatch.GetUndoBatch(), commonRootEntityId);
// Change top level entities to be parented to the container entity
// Mark them as dirty so this change is correctly applied to the template
for (AZ::Entity* topLevelEntity : topLevelEntities)
{
m_prefabUndoCache.UpdateCache(topLevelEntity->GetId());
undoBatch.MarkEntityDirty(topLevelEntity->GetId());
AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId);
AZ::EntityId topLevelEntityId = topLevelEntity->GetId();
if (topLevelEntityId.IsValid())
{
m_prefabUndoCache.UpdateCache(topLevelEntity->GetId());
// Parenting entities would mark entities as dirty. But we want to unmark the top level entities as dirty because
// if we don't, the template created would be updated and cause issues with undo operation followed by instantiation.
ToolsApplicationRequests::Bus::Broadcast(
&ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId());
}
}
// Select Container Entity
@@ -161,6 +199,81 @@ namespace AzToolsFramework
return AZ::Success();
}
PrefabOperationResult PrefabPublicHandler::InstantiatePrefab(
AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position)
{
auto prefabEditorEntityOwnershipInterface = AZ::Interface<PrefabEditorEntityOwnershipInterface>::Get();
if (!prefabEditorEntityOwnershipInterface)
{
return AZ::Failure(AZStd::string("Could not instantiate prefab - internal error "
"(PrefabEditorEntityOwnershipInterface unavailable)."));
}
InstanceOptionalReference instanceToParentUnder;
// Get parent entity and owning instance
if (parent.IsValid())
{
instanceToParentUnder = m_instanceEntityMapperInterface->FindOwningInstance(parent);
}
if (!instanceToParentUnder.has_value())
{
instanceToParentUnder = prefabEditorEntityOwnershipInterface->GetRootPrefabInstance();
parent = instanceToParentUnder->get().GetContainerEntityId();
}
//Detect whether this instantiation would produce a cyclical dependency
auto relativePath = m_prefabLoaderInterface->GetRelativePathToProject(filePath);
Prefab::TemplateId templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(relativePath);
if (templateId == InvalidTemplateId)
{
// Load the template from the file
templateId = m_prefabLoaderInterface->LoadTemplateFromFile(filePath);
AZ_Assert(templateId != InvalidTemplateId, "Template with source path %s couldn't be loaded correctly.", filePath);
}
const PrefabDom& templateDom = m_prefabSystemComponentInterface->FindTemplateDom(templateId);
AZStd::unordered_set<AZ::IO::Path> templatePaths;
PrefabDomUtils::GetTemplateSourcePaths(templateDom, templatePaths);
if (IsCyclicalDependencyFound(instanceToParentUnder->get(), templatePaths))
{
return AZ::Failure(AZStd::string::format(
"Instantiate Prefab operation aborted - Cyclical dependency detected\n(%s depends on %s).",
relativePath.Native().c_str(), instanceToParentUnder->get().GetTemplateSourcePath().Native().c_str()));
}
{
// Initialize Undo Batch object
ScopedUndoBatch undoBatch("Instantiate Prefab");
PrefabDom instanceToParentUnderDomBeforeCreate;
m_instanceToTemplateInterface->GenerateDomForInstance(instanceToParentUnderDomBeforeCreate, instanceToParentUnder->get());
// Instantiate the Prefab
auto instanceToCreate = prefabEditorEntityOwnershipInterface->InstantiatePrefab(relativePath, instanceToParentUnder);
if (!instanceToCreate)
{
return AZ::Failure(AZStd::string("Could not instantiate the prefab provided - internal error "
"(A null instance is returned)."));
}
PrefabUndoHelpers::UpdatePrefabInstance(
instanceToParentUnder->get(), "Update prefab instance", instanceToParentUnderDomBeforeCreate, undoBatch.GetUndoBatch());
CreateLink({}, instanceToCreate->get(), instanceToParentUnder->get().GetTemplateId(), undoBatch.GetUndoBatch(), parent);
AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId();
// Apply position
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetWorldTranslation, position);
}
return AZ::Success();
}
PrefabOperationResult PrefabPublicHandler::FindCommonRootOwningInstance(
const AZStd::vector<AZ::EntityId>& entityIds, EntityList& inputEntityList, EntityList& topLevelEntities,
AZ::EntityId& commonRootEntityId, InstanceOptionalReference& commonRootEntityOwningInstance)
@@ -168,6 +281,21 @@ namespace AzToolsFramework
// Retrieve entityList from entityIds
inputEntityList = EntityIdListToEntityList(entityIds);
// Remove Level Container Entity if it's part of the list
AZ::EntityId levelEntityId = GetLevelInstanceContainerEntityId();
if (levelEntityId.IsValid())
{
AZ::Entity* levelEntity = GetEntityById(levelEntityId);
if (levelEntity)
{
auto levelEntityIter = AZStd::find(inputEntityList.begin(), inputEntityList.end(), levelEntity);
if (levelEntityIter != inputEntityList.end())
{
inputEntityList.erase(levelEntityIter);
}
}
}
// Find common root and top level entities
bool entitiesHaveCommonRoot = false;
@@ -183,20 +311,32 @@ namespace AzToolsFramework
// Retrieve the owning instance of the common root entity, which will be our new instance's parent instance.
commonRootEntityOwningInstance = GetOwnerInstanceByEntityId(commonRootEntityId);
if (!commonRootEntityOwningInstance)
{
AZ_Assert(
false,
"Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided");
return AZ::Failure(AZStd::string(
"Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided"));
}
AZ_Assert(
commonRootEntityOwningInstance.has_value(),
"Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided");
return AZ::Success();
}
bool PrefabPublicHandler::IsCyclicalDependencyFound(
InstanceOptionalConstReference instance, const AZStd::unordered_set<AZ::IO::Path>& templateSourcePaths)
{
InstanceOptionalConstReference currentInstance = instance;
while (currentInstance.has_value())
{
if (templateSourcePaths.contains(currentInstance->get().GetTemplateSourcePath()))
{
return true;
}
currentInstance = currentInstance->get().GetParentInstance();
}
return false;
}
void PrefabPublicHandler::CreateLink(
const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId,
UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId)
UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded)
{
AZ::EntityId containerEntityId = sourceInstance.GetContainerEntityId();
AZ::Entity* containerEntity = GetEntityById(containerEntityId);
@@ -222,17 +362,52 @@ namespace AzToolsFramework
m_instanceToTemplateInterface->GeneratePatch(patch, containerEntityDomBefore, containerEntityDomAfter);
m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId);
PrefabUndoHelpers::CreateLink(
sourceInstance.GetTemplateId(), targetTemplateId, patch, sourceInstance.GetInstanceAlias(),
undoBatch);
LinkId linkId;
if (isUndoRedoSupportNeeded)
{
linkId = PrefabUndoHelpers::CreateLink(
sourceInstance.GetTemplateId(), targetTemplateId, AZStd::move(patch), sourceInstance.GetInstanceAlias(), undoBatch);
}
else
{
linkId = m_prefabSystemComponentInterface->CreateLink(
targetTemplateId, sourceInstance.GetTemplateId(), sourceInstance.GetInstanceAlias(), patch,
InvalidLinkId);
m_prefabSystemComponentInterface->PropagateTemplateChanges(targetTemplateId);
}
sourceInstance.SetLinkId(linkId);
// Update the cache - this prevents these changes from being stored in the regular undo/redo nodes
m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter));
}
PrefabOperationResult PrefabPublicHandler::InstantiatePrefab(AZStd::string_view /*filePath*/, AZ::EntityId /*parent*/, AZ::Vector3 /*position*/)
void PrefabPublicHandler::RemoveLink(
AZStd::unique_ptr<Instance>& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch)
{
return AZ::Failure(AZStd::string("Prefab - InstantiatePrefab is yet to be implemented."));
LinkReference nestedInstanceLink = m_prefabSystemComponentInterface->FindLink(sourceInstance->GetLinkId());
AZ_Assert(
nestedInstanceLink.has_value(),
"A valid link was not found for one of the instances provided as input for the CreatePrefab operation.");
PrefabDomReference nestedInstanceLinkDom = nestedInstanceLink->get().GetLinkDom();
AZ_Assert(
nestedInstanceLinkDom.has_value(),
"A valid DOM was not found for the link corresponding to one of the instances provided as input for the "
"CreatePrefab operation.");
PrefabDomValueReference nestedInstanceLinkPatches =
PrefabDomUtils::FindPrefabDomValue(nestedInstanceLinkDom->get(), PrefabDomUtils::PatchesName);
AZ_Assert(
nestedInstanceLinkPatches.has_value(),
"A valid DOM for patches was not found for the link corresponding to one of the instances provided as input for the "
"CreatePrefab operation.");
PrefabDom patchesCopyForUndoSupport;
patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator());
PrefabUndoHelpers::RemoveLink(
sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(),
AZStd::move(patchesCopyForUndoSupport), undoBatch);
}
PrefabOperationResult PrefabPublicHandler::SavePrefab(AZ::IO::Path filePath)
@@ -322,9 +497,9 @@ namespace AzToolsFramework
AZ::EntityId entityId, UndoSystem::URSequencePoint* parentUndoBatch)
{
// Create Undo node on entities if they belong to an instance
InstanceOptionalReference instanceOptionalReference = m_instanceEntityMapperInterface->FindOwningInstance(entityId);
InstanceOptionalReference owningInstance = m_instanceEntityMapperInterface->FindOwningInstance(entityId);
if (instanceOptionalReference.has_value())
if (owningInstance.has_value())
{
PrefabDom afterState;
AZ::Entity* entity = GetEntityById(entityId);
@@ -340,12 +515,27 @@ namespace AzToolsFramework
if (patch.IsArray() && !patch.Empty() && beforeState.IsObject())
{
// Update the state of the entity
PrefabUndoEntityUpdate* state = aznew PrefabUndoEntityUpdate(AZStd::to_string(static_cast<AZ::u64>(entityId)));
state->SetParent(parentUndoBatch);
state->Capture(beforeState, afterState, entityId);
if (IsInstanceContainerEntity(entityId) && !IsLevelInstanceContainerEntity(entityId))
{
m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, entityId);
state->Redo();
// Save these changes as patches to the link
PrefabUndoLinkUpdate* linkUpdate =
aznew PrefabUndoLinkUpdate(AZStd::to_string(static_cast<AZ::u64>(entityId)));
linkUpdate->SetParent(parentUndoBatch);
linkUpdate->Capture(patch, owningInstance->get().GetLinkId());
linkUpdate->Redo();
}
else
{
// Update the state of the entity
PrefabUndoEntityUpdate* state = aznew PrefabUndoEntityUpdate(AZStd::to_string(static_cast<AZ::u64>(entityId)));
state->SetParent(parentUndoBatch);
state->Capture(beforeState, afterState, entityId);
state->Redo();
}
}
// Update the cache
@@ -467,11 +657,18 @@ namespace AzToolsFramework
if (!EntitiesBelongToSameInstance(entityIds))
{
return AZ::Failure(AZStd::string("DeleteEntitiesAndAllDescendantsInInstance - Deletion Error. Cannot delete multiple "
"entities belonging to different instances with one operation."));
return AZ::Failure(AZStd::string("Cannot delete multiple entities belonging to different instances with one operation."));
}
InstanceOptionalReference instance = GetOwnerInstanceByEntityId(entityIds[0]);
AZ::EntityId firstEntityIdToDelete = entityIds[0];
InstanceOptionalReference commonOwningInstance = GetOwnerInstanceByEntityId(firstEntityIdToDelete);
// If the first entity id is a container entity id, then we need to mark its parent as the common owning instance because you
// cannot delete an instance from itself.
if (commonOwningInstance->get().GetContainerEntityId() == firstEntityIdToDelete)
{
commonOwningInstance = commonOwningInstance->get().GetParentInstance();
}
// Retrieve entityList from entityIds
EntityList inputEntityList = EntityIdListToEntityList(entityIds);
@@ -511,14 +708,14 @@ namespace AzToolsFramework
AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DeleteEntities:UndoCaptureAndPurgeEntities");
Prefab::PrefabDom instanceDomBefore;
m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, instance->get());
m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, commonOwningInstance->get());
if (deleteDescendants)
{
AZStd::vector<AZ::Entity*> entities;
AZStd::vector<AZStd::unique_ptr<Instance>> instances;
bool success = RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, instance->get(), entities, instances);
bool success = RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, commonOwningInstance->get(), entities, instances);
if (!success)
{
@@ -532,6 +729,7 @@ namespace AzToolsFramework
for (auto& nestedInstance : instances)
{
RemoveLink(nestedInstance, commonOwningInstance->get().GetTemplateId(), currentUndoBatch);
nestedInstance.reset();
}
}
@@ -543,22 +741,22 @@ namespace AzToolsFramework
// If this is the container entity, it actually represents the instance so get its owner
if (owningInstance->get().GetContainerEntityId() == entityId)
{
auto instancePtr = instance->get().DetachNestedInstance(owningInstance->get().GetInstanceAlias());
instancePtr.reset();
auto instancePtr = commonOwningInstance->get().DetachNestedInstance(owningInstance->get().GetInstanceAlias());
RemoveLink(instancePtr, commonOwningInstance->get().GetTemplateId(), currentUndoBatch);
}
else
{
instance->get().DetachEntity(entityId);
commonOwningInstance->get().DetachEntity(entityId);
AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationRequests::DeleteEntity, entityId);
}
}
}
Prefab::PrefabDom instanceDomAfter;
m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomAfter, instance->get());
m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomAfter, commonOwningInstance->get());
PrefabUndoInstance* command = aznew PrefabUndoInstance("Instance deletion");
command->Capture(instanceDomBefore, instanceDomAfter, instance->get().GetTemplateId());
command->Capture(instanceDomBefore, instanceDomAfter, commonOwningInstance->get().GetTemplateId());
command->SetParent(selCommand);
}
@@ -686,6 +884,11 @@ namespace AzToolsFramework
const EntityList& inputEntities, Instance& commonRootEntityOwningInstance,
EntityList& outEntities, AZStd::vector<AZStd::unique_ptr<Instance>>& outInstances) const
{
if (inputEntities.size() == 0)
{
return false;
}
AZStd::queue<AZ::Entity*> entityQueue;
for (auto inputEntity : inputEntities)
@@ -773,7 +976,7 @@ namespace AzToolsFramework
outInstances.push_back(AZStd::move(commonRootEntityOwningInstance.DetachNestedInstance(instancePtr->GetInstanceAlias())));
}
return true;
return (outEntities.size() + outInstances.size()) > 0;
}
bool PrefabPublicHandler::EntitiesBelongToSameInstance(const EntityIdList& entityIds) const
@@ -821,5 +1024,5 @@ namespace AzToolsFramework
return true;
}
}
}
} // namespace Prefab
} // namespace AzToolsFramework
@@ -12,8 +12,8 @@
#pragma once
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/Math/Vector3.h>
#include <AzCore/Memory/SystemAllocator.h>
#include <AzToolsFramework/Prefab/Instance/Instance.h>
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
@@ -45,7 +45,7 @@ namespace AzToolsFramework
// PrefabPublicInterface...
PrefabOperationResult CreatePrefab(const AZStd::vector<AZ::EntityId>& entityIds, AZ::IO::PathView filePath) override;
PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, AZ::Vector3 position) override;
PrefabOperationResult 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;
@@ -77,10 +77,21 @@ namespace AzToolsFramework
* \param targetInstance The id of the target template.
* \param undoBatch The undo batch to set as parent for this create link action.
* \param commonRootEntityId The id of the entity that the source instance should be parented under.
* \param isUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not.
*/
void CreateLink(
const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId,
UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId);
UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded = true);
/**
* Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId.
*
* \param sourceInstance The instance corresponding to the source template of the link to be removed.
* \param targetTemplateId The id of the target template of the link to be removed.
* \param undoBatch The undo batch to set as parent for this remove link action.
*/
void RemoveLink(
AZStd::unique_ptr<Instance>& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch);
/**
* Given a list of entityIds, finds the prefab instance that owns the common root entity of the entityIds.
@@ -96,6 +107,16 @@ namespace AzToolsFramework
const AZStd::vector<AZ::EntityId>& entityIds, EntityList& inputEntityList, EntityList& topLevelEntities,
AZ::EntityId& commonRootEntityId, InstanceOptionalReference& commonRootEntityOwningInstance);
/* Checks whether the template source path of any of the ancestors in the instance hierarchy matches with one of the
* paths provided in a set.
*
* \param instance The instance whose ancestor hierarchy the provided set of template source paths will be tested against.
* \param templateSourcePaths The template source paths provided to be checked against the instance ancestor hierarchy.
* \return true if any of the template source paths could be found in the ancestor hierarchy of instance, false otherwise.
*/
bool IsCyclicalDependencyFound(
InstanceOptionalConstReference instance, const AZStd::unordered_set<AZ::IO::Path>& templateSourcePaths);
static Instance* GetParentInstance(Instance* instance);
static Instance* GetAncestorOfInstanceThatIsChildOfRoot(const Instance* ancestor, Instance* descendant);
static void GenerateContainerEntityTransform(const EntityList& topLevelEntities, AZ::Vector3& translation, AZ::Quaternion& rotation);
@@ -110,5 +131,5 @@ namespace AzToolsFramework
uint64_t m_newEntityCounter = 1;
};
}
}
} // namespace Prefab
} // namespace AzToolsFramework
@@ -58,7 +58,7 @@ namespace AzToolsFramework
* @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.
*/
virtual PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, AZ::Vector3 position) = 0;
virtual PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0;
/**
* Saves changes to prefab to disk.
@@ -0,0 +1,34 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/EBus/EBus.h>
namespace AzToolsFramework
{
namespace Prefab
{
class PrefabPublicNotifications
: public AZ::EBusTraits
{
public:
virtual ~PrefabPublicNotifications() = default;
virtual void OnPrefabInstancePropagationBegin() {}
virtual void OnPrefabInstancePropagationEnd() {}
};
using PrefabPublicNotificationBus = AZ::EBus<PrefabPublicNotifications>;
} // namespace Prefab
} // namespace AzToolsFramework
@@ -261,6 +261,29 @@ namespace AzToolsFramework
}
}
AZStd::unique_ptr<Instance> PrefabSystemComponent::InstantiatePrefab(AZ::IO::PathView filePath)
{
// Retrieve the template id for the source prefab filepath
Prefab::TemplateId templateId = GetTemplateIdFromFilePath(filePath);
if (templateId == Prefab::InvalidTemplateId)
{
// Load the template from the file
templateId = m_prefabLoader.LoadTemplateFromFile(filePath);
}
if (templateId == Prefab::InvalidTemplateId)
{
AZ_Error("Prefab", false,
"Could not load template from path %s during InstantiatePrefab. Unable to proceed",
filePath);
return nullptr;
}
return InstantiatePrefab(templateId);
}
AZStd::unique_ptr<Instance> PrefabSystemComponent::InstantiatePrefab(const TemplateId& templateId)
{
TemplateReference instantiatingTemplate = FindTemplate(templateId);
@@ -560,7 +583,7 @@ namespace AzToolsFramework
const TemplateId& linkTargetId,
const TemplateId& linkSourceId,
const InstanceAlias& instanceAlias,
const PrefabDomReference linkPatch,
const PrefabDomConstReference linkPatches,
const LinkId& linkId)
{
if (linkTargetId == InvalidTemplateId)
@@ -640,12 +663,13 @@ namespace AzToolsFramework
newLink.SetSourceTemplateId(linkSourceId);
newLink.SetInstanceName(instanceAlias.c_str());
newLink.GetLinkDom().SetObject();
newLink.GetLinkDom().AddMember(rapidjson::StringRef(PrefabDomUtils::SourceName),
rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLink.GetLinkDom().GetAllocator());
newLink.GetLinkDom().AddMember(
rapidjson::StringRef(PrefabDomUtils::SourceName), rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()),
newLink.GetLinkDom().GetAllocator());
if (linkPatch && linkPatch->get().IsArray() && !(linkPatch->get().Empty()))
if (linkPatches && linkPatches->get().IsArray() && !(linkPatches->get().Empty()))
{
m_instanceToTemplatePropagator.AddPatchesToLink(linkPatch.value(), newLink);
m_instanceToTemplatePropagator.AddPatchesToLink(linkPatches.value(), newLink);
}
//update the target template dom to have the proper values for the source template dom
@@ -697,6 +721,8 @@ namespace AzToolsFramework
TemplateId PrefabSystemComponent::GetTemplateIdFromFilePath(AZ::IO::PathView filePath) const
{
AZ_Assert(!filePath.IsAbsolute(), "Prefab - GetTemplateIdFromFilePath was passed an absolute path. Prefabs use paths relative to the project folder.");
auto found = m_templateFilePathToIdMap.find(filePath);
if (found != m_templateFilePathToIdMap.end())
{
@@ -747,8 +773,8 @@ namespace AzToolsFramework
return false;
}
Template& sourceTemplate = sourceTemplateReference->get();
#if defined(AZ_ENABLE_TRACING)
Template& sourceTemplate = sourceTemplateReference->get();
Template& targetTemplate = targetTemplateReference->get();
#endif
@@ -759,22 +785,21 @@ namespace AzToolsFramework
link.SetInstanceName(instanceName.data());
PrefabDomValue& instance = instanceIterator->value;
AZ_Assert(instance.IsObject(), "Nested instance DOM provided is not a valid JSON object.");
PrefabDomValueReference sourceTemplateName = PrefabDomUtils::FindPrefabDomValue(instance, PrefabDomUtils::SourceName);
AZ_Assert(sourceTemplateName, "Couldn't find source template name in the DOM of the nested instance while creating a link.");
AZ_Assert(
sourceTemplateName->get() == sourceTemplate.GetFilePath().c_str(),
"The name of the source template in the nested instance DOM does not match the name of the source template already loaded");
PrefabDomValueReference patchesReference = PrefabDomUtils::FindPrefabDomValue(instance, PrefabDomUtils::PatchesName);
if (!patchesReference.has_value())
if (patchesReference.has_value())
{
PrefabDom& newLinkDom = link.GetLinkDom();
newLinkDom.SetObject();
newLinkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::SourceName),
rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLinkDom.GetAllocator());
}
else
{
link.SetTemplatePatches(patchesReference->get());
AZ_Assert(patchesReference->get().IsArray(), "Patches in the nested instance DOM are not represented as an array.");
}
link.SetLinkDom(instance);
if (!link.UpdateTarget())
{
AZ_Error("Prefab", false,
@@ -115,9 +115,16 @@ namespace AzToolsFramework
*/
void RemoveAllTemplates() override;
/**
* Generates a new Prefab Instance based on the Template whose source is stored in filepath.
* @param filePath the path to the prefab source file containing the template being instantiated.
* @return A unique_ptr to the newly instantiated instance. Null if operation failed.
*/
AZStd::unique_ptr<Instance> InstantiatePrefab(AZ::IO::PathView filePath) override;
/**
* Generates a new Prefab Instance based on the Template referenced by templateId
* @param templateId the id of the template being instantiated
* @param templateId the id of the template being instantiated.
* @return A unique_ptr to the newly instantiated instance. Null if operation failed.
*/
AZStd::unique_ptr<Instance> InstantiatePrefab(const TemplateId& templateId) override;
@@ -149,7 +156,7 @@ namespace AzToolsFramework
const TemplateId& linkTargetId,
const TemplateId& linkSourceId,
const InstanceAlias& instanceAlias,
const PrefabDomReference linkPatch,
const PrefabDomConstReference linkPatches,
const LinkId& linkId = InvalidLinkId) override;
/**
@@ -43,9 +43,9 @@ namespace AzToolsFramework
PrefabDomValue::MemberIterator& instanceIterator, InstanceOptionalReference instance) = 0;
//creates a new Link
virtual LinkId CreateLink(const TemplateId& linkTargetId, const TemplateId& linkSourceId,
const InstanceAlias& instanceAlias, const PrefabDomReference linkPatch,
const LinkId& linkId = InvalidLinkId) = 0;
virtual LinkId CreateLink(
const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias,
const PrefabDomConstReference linkPatches, const LinkId& linkId = InvalidLinkId) = 0;
virtual void RemoveLink(const LinkId& linkId) = 0;
@@ -58,6 +58,7 @@ namespace AzToolsFramework
virtual void UpdatePrefabTemplate(TemplateId templateId, const PrefabDom& updatedDom) = 0;
virtual void PropagateTemplateChanges(TemplateId templateId) = 0;
virtual AZStd::unique_ptr<Instance> InstantiatePrefab(AZ::IO::PathView filePath) = 0;
virtual AZStd::unique_ptr<Instance> InstantiatePrefab(const TemplateId& templateId) = 0;
virtual AZStd::unique_ptr<Instance> CreatePrefab(const AZStd::vector<AZ::Entity*>& entities,
AZStd::vector<AZStd::unique_ptr<Instance>>&& instancesToConsume, AZ::IO::PathView filePath,
@@ -113,7 +113,7 @@ namespace AzToolsFramework
, m_sourceId(InvalidTemplateId)
, m_instanceAlias("")
, m_linkId(InvalidLinkId)
, m_linkDom(PrefabDom())
, m_linkPatches(PrefabDom())
, m_linkStatus(LinkStatus::LINKSTATUS)
{
m_prefabSystemComponentInterface = AZ::Interface<PrefabSystemComponentInterface>::Get();
@@ -124,7 +124,7 @@ namespace AzToolsFramework
const TemplateId& targetId,
const TemplateId& sourceId,
const InstanceAlias& instanceAlias,
PrefabDomReference linkDom,
PrefabDom linkPatches,
const LinkId linkId)
{
m_targetId = targetId;
@@ -132,10 +132,7 @@ namespace AzToolsFramework
m_instanceAlias = instanceAlias;
m_linkId = linkId;
if (linkDom.has_value())
{
m_linkDom = AZStd::move(linkDom->get());
}
m_linkPatches = AZStd::move(linkPatches);
//if linkId is invalid, set as ADD
if (m_linkId == InvalidLinkId)
@@ -193,7 +190,7 @@ namespace AzToolsFramework
void PrefabUndoInstanceLink::AddLink()
{
m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkDom, m_linkId);
m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkPatches, m_linkId);
}
void PrefabUndoInstanceLink::RemoveLink()
@@ -228,7 +225,7 @@ namespace AzToolsFramework
if (link.has_value())
{
m_linkDomPrevious = AZStd::move(link->get().GetLinkDom());
m_linkDomPrevious.CopyFrom(link->get().GetLinkDom(), m_linkDomPrevious.GetAllocator());
}
//get source templateDom
@@ -275,7 +272,7 @@ namespace AzToolsFramework
if (patchesIter == m_linkDomNext.MemberEnd())
{
m_linkDomNext.AddMember(
rapidjson::GenericStringRef(PrefabDomUtils::PatchesName), patchLinkCopy, m_linkDomNext.GetAllocator());
rapidjson::GenericStringRef(PrefabDomUtils::PatchesName), AZStd::move(patchLinkCopy), m_linkDomNext.GetAllocator());
}
else
{
@@ -303,9 +300,7 @@ namespace AzToolsFramework
return;
}
PrefabDom moveLink;
moveLink.CopyFrom(linkDom, linkDom.GetAllocator());
link->get().GetLinkDom() = AZStd::move(moveLink);
link->get().SetLinkDom(linkDom);
//propagate the link changes
link->get().UpdateTarget();
@@ -101,7 +101,7 @@ namespace AzToolsFramework
const TemplateId& targetId,
const TemplateId& sourceId,
const InstanceAlias& instanceAlias,
PrefabDomReference linkDom = PrefabDomReference(),
PrefabDom linkPatches = PrefabDom(),
const LinkId linkId = InvalidLinkId);
void Undo() override;
@@ -120,7 +120,7 @@ namespace AzToolsFramework
InstanceAlias m_instanceAlias;
LinkId m_linkId;
PrefabDom m_linkDom; //data for delete/update
PrefabDom m_linkPatches; //data for delete/update
LinkStatus m_linkStatus;
PrefabSystemComponentInterface* m_prefabSystemComponentInterface = nullptr;
@@ -33,24 +33,24 @@ namespace AzToolsFramework
state->Redo();
}
void CreateLink(
TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch,
LinkId CreateLink(
TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDom patch,
const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch)
{
auto linkAddUndo = aznew PrefabUndoInstanceLink("Create Link");
linkAddUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, patch, InvalidLinkId);
linkAddUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, AZStd::move(patch), InvalidLinkId);
linkAddUndo->SetParent(undoBatch);
linkAddUndo->Redo();
return linkAddUndo->GetLinkId();
}
void RemoveLink(
TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias,
LinkId linkId, UndoSystem::URSequencePoint* undoBatch)
TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId,
PrefabDom linkPatches, UndoSystem::URSequencePoint* undoBatch)
{
auto linkRemoveUndo = aznew PrefabUndoInstanceLink("Remove Link");
PrefabDom emptyLinkDom;
linkRemoveUndo->Capture(
targetTemplateId, sourceTemplateId, instanceAlias, emptyLinkDom, linkId);
linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, AZStd::move(linkPatches), linkId);
linkRemoveUndo->SetParent(undoBatch);
linkRemoveUndo->Redo();
}
@@ -21,12 +21,12 @@ namespace AzToolsFramework
void UpdatePrefabInstance(
const Instance& instance, AZStd::string_view undoMessage, const PrefabDom& instanceDomBeforeUpdate,
UndoSystem::URSequencePoint* undoBatch);
void CreateLink(
TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch,
LinkId CreateLink(
TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDom patch,
const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch);
void RemoveLink(
TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias,
LinkId linkId, UndoSystem::URSequencePoint* undoBatch);
TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId,
PrefabDom linkPatches, UndoSystem::URSequencePoint* undoBatch);
}
} // namespace Prefab
} // namespace AzToolsFramework
@@ -63,7 +63,7 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
AZStd::move(uniqueName), context.GetSourceUuid(), AZStd::move(serializer));
AZ_Assert(spawnable, "Failed to create a new spawnable.");
bool result = SpawnableUtils::CreateSpawnable(*spawnable, prefab);
bool result = SpawnableUtils::CreateSpawnable(*spawnable, prefab, object.GetReferencedAssets());
if (result)
{
AzFramework::Spawnable::EntityList& entities = spawnable->GetEntities();
@@ -84,8 +84,6 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
}
SpawnableUtils::SortEntitiesByTransformHierarchy(*spawnable);
context.GetProcessedObjects().push_back(AZStd::move(object));
context.RemovePrefab(prefabName);
}
else
{
@@ -10,6 +10,8 @@
*
*/
#include <AzFramework/Spawnable/Spawnable.h>
#include <AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h>
namespace AzToolsFramework::Prefab::PrefabConversionUtils
@@ -24,37 +26,14 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
return result.second;
}
bool PrefabProcessorContext::RemovePrefab(AZStd::string_view prefabName)
{
if (!m_isIterating)
{
return m_prefabs.erase(prefabName) > 0;
}
else
{
m_delayedDelete.emplace_back(prefabName);
}
return false;
}
void PrefabProcessorContext::ListPrefabs(const AZStd::function<void(AZStd::string_view, PrefabDom&)>& callback)
{
m_isIterating = true;
for (auto& it : m_prefabs)
{
if (AZStd::find(m_delayedDelete.begin(), m_delayedDelete.end(), it.first) == m_delayedDelete.end())
{
callback(it.first, it.second);
}
callback(it.first, it.second);
}
m_isIterating = false;
// Clear out any prefabs that have been deleted.
for (AZStd::string& deleted : m_delayedDelete)
{
m_prefabs.erase(deleted);
}
m_delayedDelete.clear();
}
void PrefabProcessorContext::ListPrefabs(const AZStd::function<void(AZStd::string_view, const PrefabDom&)>& callback) const
@@ -70,6 +49,44 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
return !m_prefabs.empty();
}
bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(AZStd::string prefabName, AZStd::string dependentPrefabName)
{
using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore;
prefabName += AzFramework::Spawnable::DotFileExtension;
uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName));
dependentPrefabName += AzFramework::Spawnable::DotFileExtension;
uint32_t spawnablePrefabSubId = ConversionUtils::BuildSubId(AZStd::move(dependentPrefabName));
return RegisterSpawnableProductAssetDependency(spawnableSubId, spawnablePrefabSubId);
}
bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(AZStd::string prefabName, const AZ::Data::AssetId& dependentAssetId)
{
using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore;
prefabName += AzFramework::Spawnable::DotFileExtension;
uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName));
AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableSubId);
return RegisterProductAssetDependency(spawnableAssetId, dependentAssetId);
}
bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId)
{
AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableAssetSubId);
AZ::Data::AssetId dependentSpawnableAssetId(GetSourceUuid(), dependentSpawnableAssetSubId);
return RegisterProductAssetDependency(spawnableAssetId, dependentSpawnableAssetId);
}
bool PrefabProcessorContext::RegisterProductAssetDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId)
{
return m_registeredProductAssetDependencies[assetId].emplace(dependentAssetId).second;
}
PrefabProcessorContext::ProcessedObjectStoreContainer& PrefabProcessorContext::GetProcessedObjects()
{
return m_products;
@@ -80,6 +97,16 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
return m_products;
}
PrefabProcessorContext::ProductAssetDependencyContainer& PrefabProcessorContext::GetRegisteredProductAssetDependencies()
{
return m_registeredProductAssetDependencies;
}
const PrefabProcessorContext::ProductAssetDependencyContainer& PrefabProcessorContext::GetRegisteredProductAssetDependencies() const
{
return m_registeredProductAssetDependencies;
}
void PrefabProcessorContext::SetPlatformTags(AZ::PlatformTagSet tags)
{
m_platformTags = AZStd::move(tags);
@@ -29,6 +29,8 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
{
public:
using ProcessedObjectStoreContainer = AZStd::vector<ProcessedObjectStore>;
using ProductAssetDependencyContainer =
AZStd::unordered_map<AZ::Data::AssetId, AZStd::unordered_set<AZ::Data::AssetId>>;
AZ_CLASS_ALLOCATOR(PrefabProcessorContext, AZ::SystemAllocator, 0);
AZ_RTTI(PrefabProcessorContext, "{C7D77E3A-C544-486B-B774-7C82C38FE22F}");
@@ -37,14 +39,21 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
virtual ~PrefabProcessorContext() = default;
virtual bool AddPrefab(AZStd::string prefabName, PrefabDom prefab);
virtual bool RemovePrefab(AZStd::string_view prefabName);
virtual void ListPrefabs(const AZStd::function<void(AZStd::string_view, PrefabDom&)>& callback);
virtual void ListPrefabs(const AZStd::function<void(AZStd::string_view, const PrefabDom&)>& callback) const;
virtual bool HasPrefabs() const;
virtual bool RegisterSpawnableProductAssetDependency(AZStd::string prefabName, AZStd::string dependentPrefabName);
virtual bool RegisterSpawnableProductAssetDependency(AZStd::string prefabName, const AZ::Data::AssetId& dependentAssetId);
virtual bool RegisterSpawnableProductAssetDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId);
virtual bool RegisterProductAssetDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId);
virtual ProcessedObjectStoreContainer& GetProcessedObjects();
virtual const ProcessedObjectStoreContainer& GetProcessedObjects() const;
virtual ProductAssetDependencyContainer& GetRegisteredProductAssetDependencies();
virtual const ProductAssetDependencyContainer& GetRegisteredProductAssetDependencies() const;
virtual void SetPlatformTags(AZ::PlatformTagSet tags);
virtual const AZ::PlatformTagSet& GetPlatformTags() const;
virtual const AZ::Uuid& GetSourceUuid() const;
@@ -57,7 +66,8 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
NamedPrefabContainer m_prefabs;
ProcessedObjectStoreContainer m_products;
AZStd::vector<AZStd::string> m_delayedDelete;
ProductAssetDependencyContainer m_registeredProductAssetDependencies;
AZ::PlatformTagSet m_platformTags;
AZ::Uuid m_sourceUuid;
bool m_isIterating{ false };
@@ -56,6 +56,16 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils
return *m_asset;
}
AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& ProcessedObjectStore::GetReferencedAssets()
{
return m_referencedAssets;
}
const AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& ProcessedObjectStore::GetReferencedAssets() const
{
return m_referencedAssets;
}
AZStd::unique_ptr<AZ::Data::AssetData> ProcessedObjectStore::ReleaseAsset()
{
return AZStd::move(m_asset);

Some files were not shown because too many files have changed in this diff Show More